开发只给了一串字符串,要转化成RSA加密的结果。
找了一堆rsa加密的算法:
# -*- coding: utf-8 -*- import rsa import base64 # 随机成一对密钥,然后保存.pem格式文件,也可以直接使用 (pubkey, privkey) = rsa.newkeys(2048) pub = pubkey.save_pkcs1() pubfile = open('public.pem', 'w+') pubfile.write(str(pub, encoding="utf-8")) pubfile.close() pri = privkey.save_pkcs1() prifile = open('private.pem', 'w+') prifile.write(str(pri)) prifile.close() message = 'abcdef' with open('public.pem') as publickfile: p = publickfile.read() pubkey = rsa.PublicKey.load_pkcs1(p.encode(encoding='utf-8')) with open('private.pem') as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p.encode(encoding='utf-8')) # 公钥加密(为了展示可以用base64编码) crypto = base64.b64encode(rsa.encrypt(message.encode(encoding='utf-8'), pubkey)) print("rsa加密结果:", crypto) # 私钥解密 message = rsa.decrypt(base64.b64decode(crypto), privkey) print("rsa解密结果:", message) # sign 用私钥签名 signature = base64.b64encode(rsa.sign(message, privkey, 'SHA-1')) print("加签结果:", signature) # 再用公钥验证签名 res = rsa.verify(message, base64.b64decode(signature), pubkey) print( "验签结果:",res)
将其中的一部分替换成了我自己的方法,生成了一个跟p一模一样的文件,怎么都不行,一直报错:
{PyAsn1Error}<TagSet object, tags 0:32:16> not in asn1Spec: <Integer schema object, tagSet <TagSet object, tags 0:0:2>>
import rsa import base64 from pbkdf2 import xrange s = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANkHLKYS2dByWQ3gKjQDvQbuWb/2Y9z4eYuLEfgXdiP5qc5cG/5c+c/GgIl6yQY7AYeZVXiBXLaGzxiLZ5Y4fi0CAwEAAQ==' pubkey_str =('-----BEGIN RSA PUBLIC KEY-----'+' ' + ' '.join(s[pos:pos+64] for pos in xrange(0, len(s), 64)) + ' '+'-----END RSA PUBLIC KEY----- ') pubkey_byte = pubkey_str.encode(encoding='utf-8') pubkey = rsa.PublicKey.load_pkcs1(pubkey_byte)
报错解决办法查找到这个链接:
https://stackoverflow.com/questions/25243761/pyasn1-error-when-reading-a-pem-string
pyasn1-error-when-reading-a-pem-string
import rsa pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(b"""-----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANkHLKYS2dByWQ3gKjQDvQbuWb/2Y9z4 eYuLEfgXdiP5qc5cG/5c+c/GgIl6yQY7AYeZVXiBXLaGzxiLZ5Y4fi0CAwEAAQ== -----END PUBLIC KEY-----""") crypto = rsa.encrypt(b"Secret", pubkey)
总算找到解决方案。。