【问题标题】:RSA encrypt/decrypt between C and pythonC和python之间的RSA加密/解密
【发布时间】:2014-04-19 09:00:07
【问题描述】:

我在 python 中编写了服务器,在 C 中编写了客户端。他们的工作是从服务器向客户端发送一条使用RSA private key 加密的秘密消息。我正在使用 openssl/rsa.h 库,即我使用私钥初始化 rsa 对象并使用 RSA_public_encrypt(length_of_message, "Secret Message", to, rsa, RSA_PKCS1_PADDING) 加密消息。然后我将此加密消息发送到python 服务器并尝试使用from Crypto.PublicKey import RSA用相同的私钥解密它。问题是它没有正确解密它。它总是输出 128 位长度的消息,其中秘密消息随机放置在其中 (e.g. '\x23\xa3x\43...Secret Message\xef\x4a'),它通常应该只返回 Secret Message

【问题讨论】:

  • “用使用相同的私钥解密它”——最好是一个错字。
  • 要在 RSA 方案中加密,您应该使用公钥...
  • 我正在使用 RSA_public_encrypt(length_of_message, "Secret Message", to, rsa, RSA_PKCS1_PADDING) 加密公共。当我从私钥生成公钥并使用它时,函数会出错。
  • 我认为它与标准填充选项有关,但我还不能解决它。当我使用rsautl -encrypt -in msg.file -inkey tvfp.pem -out out.bin 加密并使用openssl rsautl -decrypt -in out.bin -inkey tvfp.pem 解密时,它可以正常工作。但是,当我在解密时添加 -raw 选项进行填充时,它会打印出与 python 解密器类似的结果。

标签: python c openssl rsa


【解决方案1】:

问题在于填充。 Python 的 rsa 模块使用 PKCS1 填充解密结果,并且不删除填充。使用下面我从here 获取的函数,问题得到了解决:

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】:

    是否可以在 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-13
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2015-07-15
      • 2015-03-16
      • 2021-12-07
      相关资源
      最近更新 更多