简体   繁体   English

RSA在C和python之间进行加密/解密

[英]RSA encrypt/decrypt between C and python

I have server written in python and client in C . python编写的服务器和用C编写的客户端。 Their job is to send a secret message from server to client which is encrypted with RSA private key . 他们的工作是将秘密消息从服务器发送到客户端,并使用RSA private key I am using openssl/rsa.h library, that is I initialize a rsa object with a private key and encrypte a message with RSA_public_encrypt(length_of_message, "Secret Message", to, rsa, RSA_PKCS1_PADDING) . 我正在使用openssl/rsa.h库,也就是我用私钥初始化rsa对象,并使用RSA_public_encrypt(length_of_message, "Secret Message", to, rsa, RSA_PKCS1_PADDING)加密消息。 Then I send this encrypted message to python server and try to decrypt it with same private key using from Crypto.PublicKey import RSA library. 然后,我将此加密的消息发送到python服务器,并尝试使用from Crypto.PublicKey import RSA库使用相同的私钥对其进行解密 Problem is that it does not decrypt it properly. 问题是它无法正确解密。 It always outputs 128-bit length message where the secret message is randomly placed in it (eg '\\x23\\xa3x\\43...Secret Message\\xef\\x4a') , where it should normally return just Secret Message . 它总是输出128位长度的消息,在其中秘密消息被随机放置在其中(eg '\\x23\\xa3x\\43...Secret Message\\xef\\x4a') ,在该Secret Message通常应仅返回Secret Message

The problem was about the padding. 问题是关于填充。 Python's rsa module decrypts result with PKCS1 padding and does not removes padding. Python的rsa模块使用PKCS1填充解密结果,但不会删除填充。 With the function below which I have taken from here problem was solved: 使用下面我从此处采取的功能解决了问题:

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

Is it possible to create a same pair of RSA key in Python and C . 是否可以在Python和C中创建同一对RSA密钥。 please find the code below and let me know if any modification needed to get it worked. 请找到下面的代码,让我知道是否需要进行任何修改才能使其正常工作。

Code in python 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)

Code in C 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM