编程语言
首页 > 编程语言> > python string 类型的公钥转换类型并解密

python string 类型的公钥转换类型并解密

作者:互联网

python3.X

 1 def checkLicense(str):#str为解密的字符串
 2     str_base64 = base64.b64decode(str)
 3     public_key = "1qaz2wsx3edc"
 4 
 5     de_public_key = str2key(public_key)
 6 
 7     modulus = int(de_public_key[0], 16)
 8     exponent = int(de_public_key[1], 16)
 9 
10     rsa_public = rsa.PublicKey(modulus, exponent)
11 
12     public_rsa_key = rsa_public.save_pkcs1()
13 
14     newPublic = rsa.PublicKey.load_pkcs1(public_rsa_key)
15 
16     entrypted = rsa.transform.bytes2int(str_base64)
17     decryted = rsa.core.decrypt_int(entrypted, newPublic.e, newPublic.n)
18 
19     decrypted_bytes = rsa.transform.int2bytes(decryted)
20 
21     # if len(decrypted_bytes) > 0 and list(six.iterbytes(decrypted_bytes))[0] == 1:
22     if len(decrypted_bytes) > 0:
23         try:
24             raw_info = decrypted_bytes[decrypted_bytes.find(b'\x00') + 1:]
25             print(raw_info.decode("utf-8"))
26             return (raw_info.decode("utf-8"))
27         except Exception as e:
28             print(e)
29             print ("解析失败")
30 
31     return 'a'
32 
33 
34 def str2key(s):
35     # 对字符串解码
36     b_str = base64.b64decode(s)
37 
38     if len(b_str) < 162:
39         return False
40 
41     hex_str = ''
42     hex_str = b_str.hex()
43 
44     # 找到模数和指数的开头结束位置
45     m_start = 29 * 2
46     e_start = 159 * 2
47     m_len = 128 * 2
48     e_len = 3 * 2
49 
50     modulus = hex_str[m_start:m_start + m_len]
51     exponent = hex_str[e_start:e_start + e_len]
52 
53     return modulus, exponent

 

上面有一个问题,就是说rsa加密密文过长,就会解析失败,20,21行注释掉就是因为这个原因,做了报错处理,要是要各位明白这里的,还望不吝指导下

 

标签:key,decrypted,公钥,string,python,rsa,len,str,public
来源: https://www.cnblogs.com/notchangeworld/p/13435507.html