要使不同服务器上使用相同的密钥进行RSA加密正常工作,可以采用以下步骤:
1.生成RSA公私钥:
from Crypto.PublicKey import RSA
random_generator = Random.new().read
rsa = RSA.generate(1024, random_generator)
private_pem = rsa.exportKey()
with open('private.pem', 'wb') as f:
f.write(private_pem)
public_pem = rsa.publickey().exportKey()
with open('public.pem', 'wb') as f:
f.write(public_pem)
2.将公钥文件传输到所有服务器。
3.在所有服务器上使用公钥加密:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
with open('public.pem', 'rb') as f:
public_key = RSA.importKey(f.read())
cipher = PKCS1_v1_5.new(public_key)
ciphertext = cipher.encrypt('Hello World!')
4.在特定服务器上使用私钥解密:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
with open('private.pem', 'rb') as f:
private_key = RSA.importKey(f.read())
cipher = PKCS1_v1_5.new(private_key)
message = cipher.decrypt(ciphertext, None)
使用不同私钥进行解密会导致解密失败。因此,要在不同服务器上使用相同的密钥进行RSA加密,需要确保所有服务器均使用相同的公钥,同时使用私钥的服务器必须与之匹配的私钥。
下一篇:不同服务器上行为不一致的问题