JS与Python(pycrypto)之间的RSA加解密

RSA Encrypt and Decrypt between JS and Python(pycrypto)

我从 JS RSA 库 (http://www-cs-students.stanford.edu/~tjw/jsbn/) 加密纯文本并从 python、Crypto.PublicKey.

解密

但是,当我用 python 从 JS 解密密文时,它有虚拟文本。我不知道为什么。

所以,我想要没有虚拟的明文。(例如测试)

步骤

  1. 在Python中制作密钥对。

    key = RSA.generate(1024) #(publicKey, privateKey)
    
  2. 在JS中保存模数、指数并加密"test"

    var rsa = new RSAKey();
    rsa.setPublic(modulus, exponent); //modulus and exponent hex string
    rsa.encrypt("test");
    

    result(hex string): d0ab7e22f92adcca7182e3c622b513382d163033df5ca0f3c0327e8a1774258800ae57dfc98522f5ed40a4bed2f4b54f46ea800ff1ef522b104b0f874a598f6bbcf5453506f8bf2f8aa3b04b0c73f0018564707304b3a059326d51945d3ff0282d63c2c4c1ea6ba5a2172af83ef8bdc1d104a8d67ba95ee97ab89b36cd5c34d4

  3. 使用Python

    中的私钥解密
    key.decrypt(above_result.decode('hex'))
    

    结果:\x02\xf0\xae\xafK\xd3\x17\xfc\xf4\xd6\xd9=\xee7\x04\x94\xea\x9c\xd8\xf7--\x19\x05$!'#\xad\x82'\xfcKG\xadK\xb6_\xabMZ:\x9dU\xa4\xc0[\x8c\xa6hC\x93\xf7\xbc\xf1:\x9f\x107D\xe8\xfe\x07R\x8c\xd7\xb3\xe6\xc6\xcf^\x92\xa2\xe2X\xe4\xaf|\x8aS\xfe\xd3\x84)\xc3\x82\xdc\xd1\x7f\xc9\x12\xd0\x94\xd2jS\xee\x83\xfda\xc6\xc7d\xdd\x0b2\xe6\x1d\x84\x0c\x93\x8aK\xc2\x10U\xc0Y~\xbf\x15\xfa\x00测试

pycrypto rsa decrypt() method is a low-level method, hence you are getting the expected output, a PKCS#1, version 1.5, block type 2 array of bytes. As you seem to find that inconvenient, you should follow the advice in the API docs and instead use the PKCS1_v1_5 module

我一直在使用 JSEncrypt JavaScript file to achieve conversation between JavaScript and Python using pycrypto,但是在 JavaScript 加密期间,它在函数 pkcs1pad2 中使用了随机填充,需要将其删除并开始工作。这是一个 hack,但它成功了。以下是从 function pkcs1pad2(s,n)

中注释掉的行
 while(n > 2) { // random non-zero pad
    x[0] = 0;
    while(x[0] == 0) rng.nextBytes(x);
    ba[--n] = x[0];
  }

  ba[--n] = 2;
  ba[--n] = 0;