1. 程式人生 > 實用技巧 >RSA加密演算法坑:pyasn1-error-when-reading-a-pem-string

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

開發只給了一串字串,要轉化成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)

總算找到解決方案。。