I have server written in python
and client in C
. Their job is to send a secret message from server to client which is encrypted with 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)
. 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. 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 (e.g. '\x23\xa3x\43...Secret Message\xef\x4a')
, where it should normally return just Secret Message
.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
The problem was about the padding. Python's rsa module decrypts result with PKCS1
padding and does not removes padding. 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
回答2:
Is it possible to create a same pair of RSA key in Python and C . please find the code below and let me know if any modification needed to get it worked.
Code in 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
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);