将HEX数据中的公钥等的OID转换为点格式

时间:2018-04-04 14:16:06

标签: python python-3.x certificate rsa pyasn1

大家好,

我有 CV1 RSA证书略有修改。所以,我不想使用asn1wrap来解析'der'文件,因为它有时太复杂了,而是因为标签已经修复了通过将二进制数据转换为十六进制并提取所需的数据范围,我可以解析此'der'文件的HEX数据

但是为了表示我希望 OID 采用点格式 例如: ABSOLUTE OID 1.3.6.33.4.11.5318.2888.18.10377.5

我可以从整个十六进制数据中提取十六进制字符串,如下所示: 的 '060D2B0621040BA946964812D10905'

任何可以直接执行此转换的 python3 函数。或者任何人都可以帮助转换相同的逻辑。

1 个答案:

答案 0 :(得分:0)

为有兴趣的人找到答案。不使用pyasn1或asn1crypto我没有找到任何包将十六进制值转换为OID表示法。 所以我浏览了一下,混合了其他语言的代码并在python中创建了一个代码。

def notation_OID(oidhex_string):

    ''' Input is a hex string and as one byte is 2 charecters i take an 
        empty list and insert 2 characters per element of the list.
        So for a string 'DEADBEEF' it would be ['DE','AD','BE,'EF']. '''
    hex_list = [] 
    for char in range(0,len(oidhex_string),2):
        hex_list.append(oidhex_string[char]+oidhex_string[char+1])

    ''' I have deleted the first two element of the list as my hex string
        includes the standard OID tag '06' and the OID length '0D'. 
        These values are not required for the calculation as i've used 
        absolute OID and not using any ASN.1 modules. Can be removed if you
        have only the data part of the OID in hex string. '''
    del hex_list[0]
    del hex_list[0]

    # An empty string to append the value of the OID in standard notation after
    # processing each element of the list.
    OID_str = ''

    # Convert the list with hex data in str format to int format for 
    # calculations.
    for element in range(len(hex_list)):
        hex_list[element] = int(hex_list[element],16)

    # Convert the OID to its standard notation. Sourced from code in other 
    # languages and adapted for python.

    # The first two digits of the OID are calculated differently from the rest. 
    x = int(hex_list[0] / 40)
    y = int(hex_list[0] % 40)
    if x > 2:
        y += (x-2)*40
        x = 2;

    OID_str += str(x)+'.'+str(y)

    val = 0
    for byte in range(1,len(hex_list)):
        val = ((val<<7) | ((hex_list[byte] & 0x7F)))
        if (hex_list[byte] & 0x80) != 0x80:
            OID_str += "."+str(val)
            val = 0

    # print the OID in dot notation.
    print (OID_str)

notation_OID('060D2B0621040BA946964812D10905')

希望这有助于...... cHEErs!