码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-09-18 03:19:11      阅读:62      评论:0      收藏:0      [点我收藏+]

标签: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}<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 = ‘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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!