如何使用Python gdata.tlslite.utils.ASN1Parser来获得指数和模数?

时间:2011-11-30 14:17:48

标签: python google-app-engine openssl rsa asn.1

我要做的是使用Python GAE读取一些PEM公钥。

RSAKey模块不解析PEM格式的公钥,只是私有。

如果我可以从PEM获得模数和指数,我可以从那里开始。

使用openssl asn1parse探索典型的PEM(我将使用的那种)我可以找到他们居住的BIT STRING

但我无法弄清楚如何使用gdata ASN1Parser找到它们。

例如openssl输出:

openssl asn1parse -i -in test.pem
 0:d=0  hl=3 l= 159 cons: SEQUENCE          
 3:d=1  hl=2 l=  13 cons:  SEQUENCE          
 5:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
16:d=2  hl=2 l=   0 prim:   NULL              
18:d=1  hl=3 l= 141 prim:  BIT STRING

然后向下钻取我可以看到RSA模数和指数:

openssl asn1parse -strparse 18 -i -in test.pem 
  0:d=0  hl=3 l= 137 cons: SEQUENCE          
  3:d=1  hl=3 l= 129 prim:  INTEGER           :09C7A8007111B2B...
135:d=1  hl=2 l=   3 prim:  INTEGER           :010001

如果我接着使用相同的PEM并在Python中将其粘贴到bytes,我如何让正确的孩子获得这些值?

asn1 = ASN1Parser(bytes)
modulus = asn1.getChild(1).getChild(0).value
exponent = asn1.getChild(1).getChild(1).value
binascii.hexlify(modulus)

或者是什么?我无法弄清楚我需要看的等级。我也不知道我在做什么...使用hexlify我可以在那里看到值,但总是(玩儿童和深度)前面有额外的东西,和/或不是如图所示的全部数字在openssl。

1 个答案:

答案 0 :(得分:0)

我修改了tlslite来做你正在谈论的内容......这是一个应该帮助你的片段。 “bytes”是DER编码的公钥。

我认为你遇到的问题是某些键可能有“填充”。填充长度是有效负载的第一个字节。然后,您需要跳过填充字节和填充的许多字节。

@staticmethod
def parseDERPublicKey(bytes):
    a = ASN1Parser(bytes)
    b = a.getChild(1)
    padding = b.value[1]
    # TODO: I am assuming padding is 0, this is wrong.
    #       Skip the padding as well.
    c = b.value[1:] # get the mod/exp portion after the padding
    d = ASN1Parser(c)

    modulus = bytesToNumber(d.getChild(0).value)
    exponent = bytesToNumber(d.getChild(1).value)
相关问题