使用Python RSA库加密字符串时遇PEM起始标记错误求助
问题解决:RSA公钥加载报错(No PEM start marker)
错误原因
你当前使用的rsa.PublicKey.load_pkcs1()方法仅支持PKCS#1格式的RSA公钥(文件开头标记为-----BEGIN RSA PUBLIC KEY-----),但你的pubkey.pem是PKCS#8格式(开头标记为-----BEGIN PUBLIC KEY-----),两者格式不匹配,导致无法识别起始标记,触发错误。另外注意原代码中加密逻辑部分存在缩进错误,需同步修正。
解决方法
方法1:转换公钥为PKCS#1格式
用OpenSSL命令直接转换公钥格式,终端执行:
openssl rsa -pubin -in pubkey.pem -outform PEM -RSAPublicKey_out -out pubkey_pkcs1.pem
转换完成后,将代码里的pubkey.pem替换为新生成的pubkey_pkcs1.pem,原代码逻辑修正缩进后即可正常运行:
import rsa # Load the public key with open('pubkey_pkcs1.pem', 'rb') as key_file: key_data = key_file.read() public_key = rsa.PublicKey.load_pkcs1(key_data) # Encrypt the string using the public key message = b"Abiodun" encrypted_message = rsa.encrypt(message, public_key) # Print the encrypted message print(encrypted_message)
方法2:修改代码兼容PKCS#8格式
借助cryptography库解析PKCS#8公钥,再转换为rsa库支持的格式:
- 先安装依赖:
pip install cryptography
- 使用以下代码:
import rsa from cryptography.hazmat.primitives import serialization # 加载PKCS#8格式公钥 with open('pubkey.pem', 'rb') as key_file: public_key_crypto = serialization.load_pem_public_key(key_file.read()) # 转换为PKCS#1格式字节数据 public_key_pkcs1 = public_key_crypto.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1 ) # 用rsa库加载公钥 public_key = rsa.PublicKey.load_pkcs1(public_key_pkcs1) # 加密并输出 message = b"Abiodun" encrypted_message = rsa.encrypt(message, public_key) print(encrypted_message)
内容的提问来源于stack exchange,提问作者Abiodun Adeoye
相关产品推荐
相关产品推荐

