首页 > 解决方案 > RSA Encryption Using Generated Key Pair

问题描述

I have been stuck on this problem since morning. I have generated key pair for RSA encryption using ssh-keygen.

Encryption works fine:

with open("keys.pub", "rb") as f:
    pubkey = f.read()

with open("keys", "rb") as f:
    prvkey = f.read()

from Crypto.PublicKey import RSA

from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5

msg = "test"
print("raw msg->", msg)
keyPub = RSA.importKey(pubkey) # import the public key
cipher = Cipher_PKCS1_v1_5.new(keyPub)
cipher_text = cipher.encrypt(msg.encode()) # now we have the cipher
print("cipher text->", cipher_text)

However, I get error in decryption:

keyPriv = RSA.importKey(prvkey) # import the private key
cipher = Cipher_PKCS1_v1_5.new(keyPriv)
decrypt_text = cipher.decrypt(cipher_text, None).decode()
print("decrypted msg->", decrypt_text)
assert msg == decrypt_text # check that
print("test passed")

ValueError: RSA key format is not supported

I am using PyCrypto 2.6.1. Any help would be greatly appreciated. I am not able to attach the keys due to to some server error.

标签: python

解决方案


发出 RSA.importKey 后,变量 keyPriv 是否正确包含密钥?

您生成的 RSA 密钥对似乎与 pycrypto 2.6.1 不兼容。安装 pycryptodome 3,它是 pycrypto 的一个分支并且正在积极开发中,应该可以解决这个问题。


推荐阅读