我用python编写服务器,用C编写客户端。他们的工作是从服务器到客户端发送一条秘密消息,该消息用RSA private key加密。我正在使用openssl/rsa.h库,即用私钥初始化rsa对象,并使用RSA_public_encrypt(length_of_message, "Secret Message", to, rsa, RSA_PKCS1_PADDING)加密消息。然后,我将此加密消息发送到python服务器,并尝试使用库使用相同的私钥对其进行解密。问题是它不能正确解密它。它总是输出128位长消息,其中秘密消息被随机放置在(e.g. '\x23\xa3x\43...Secret Message\xef\x4a')中,通常应该只返回Secret Message。
发布于 2014-03-14 09:50:24
问题在于填充物。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发布于 2019-01-28 11:23:08
是否可以在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);https://stackoverflow.com/questions/22398745
复制相似问题