C和Python之间的RSA加密/解密
我有一个用 python
写的服务器和一个用 C
写的客户端。它们的任务是把一条秘密信息从服务器发送到客户端,这条信息是用 RSA 私钥
加密的。我使用的是 openssl/rsa.h
库,也就是说,我先用私钥初始化一个 rsa
对象,然后用 RSA_public_encrypt(length_of_message, "Secret Message", to, rsa, RSA_PKCS1_PADDING)
来加密这条信息。接着,我把这个加密后的信息发送到 python
服务器,并尝试用同样的私钥通过 from Crypto.PublicKey import RSA
库来解密。问题是,它解密得不对。它总是输出一个128位长度的信息,里面随机放着我的秘密信息 (例如 '\x23\xa3x\43...Secret Message\xef\x4a')
,而正常情况下应该只返回 Secret Message
。
2 个回答
0
在Python和C语言中,能否创建一对相同的RSA密钥?请看下面的代码,如果需要任何修改才能让它工作,请告诉我。
Python中的代码
key = RSA.generate(2048)
file_out_pub = open("pubkey.der", "wb")
file_out_pub.write(key.publickey().exportKey())
file_out_pub.close()
file_out_pub = open("pubkey.der", "`enter code here`r")
public_key = RSA.importKey(file_out_pub.read())
cipher = PKCS1_OAEP.new(public_key)
password = pw
ciphertext = cipher.encrypt(password)
C语言中的代码
int clen = 0, num, ret;
clen = strnlen_s(req->pw,2048);
unsigned char ptext[2048];
RSA *rsa = RSA_new();
BIGNUM *e = BN_new();
ret = RSA_generate_key_ex(rsa, 2048, e, NULL );
num = RSA_private_decrypt(clen, req->pw , ptext, rsa, RSA_PKCS1_OAEP_PADDING);
// Start authentication process
strncpy(req->pw,ptext,MAX_PASSWORD_STR);
3
这个问题跟“填充”有关。Python的rsa模块在解密时使用了PKCS1
填充,但它不会自动去掉这个填充。下面这个函数是我从这里找到的,使用它后问题就解决了:
def pkcs1_unpad(text):
if len(text) > 0 and text[0] == '\x02':
# Find end of padding marked by nul
pos = text.find('\x00')
if pos > 0:
return text[pos+1:]
return None