RSA加密算法坑:pyasn1-error-when-reading-a-pem-string

2021-03-26 21:25

阅读:406

标签:lag   schema   print   err   字符   abc   not   bsp   rom   

开发只给了一串字符串,要转化成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} not in asn1Spec: >

import rsa
import base64
from pbkdf2 import xrange

s = ‘MIIBCgKCAQEA4/7F9IluZZ2Y8VnJMatXn8UJ0fcuLqfQWSc5xdX3L+CpqcwZ4V1IN5HwqEyU0AyjRWJ2o3JD4Q2XrI76BEjWtfQ1KSgLppHaXOd5WdwcWId67cjCxYPLKPpuR8vxY/bgFKDprxw6KTf54mNcu4e28sjGpJjcqxk85P/S2yVFwUmTvfFxGtT9kKabJfkL2GxvA9G4TtCGwwolLOdix9E920NxIbSOXfD2YVaU5JtYMA+aeE4npOWp4oTwym7LDWIIcTJXgHCBgVmpl5dPDQLwqXucZcAOuiAVNU8IKryjN5qTwzKK1yz3/SPpZEqpR64Z2fKjVWCY+AdGhy1jcqD7pQIDAQAB
pubkey_str =(‘-----BEGIN RSA PUBLIC KEY-----‘+‘\n‘ + ‘\n‘.join(s[pos:pos+64] for pos in xrange(0, len(s), 64)) + ‘\n‘+‘-----END RSA PUBLIC KEY-----\n‘)
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)

总算找到解决方案。。




RSA加密算法坑:pyasn1-error-when-reading-a-pem-string

标签:lag   schema   print   err   字符   abc   not   bsp   rom   

原文地址:https://www.cnblogs.com/bright-carol/p/13680634.html


评论


亲,登录后才可以留言!