互操作性Python JavaScript RSA加密

时间:2018-09-10 15:26:02

标签: javascript python encryption rsa transferable

在服务器上具有PyCrypto的Python,在客户端上是Tom Wu的JavaScript库。 http://www-cs-students.stanford.edu/~tjw/jsbn/ 我可以在服务器上的Python中进行加密和解密,并在客户端的JavaScript中进行相同的操作。但是我无法在客户端上进行加密,也无法在服务器上进行解密。 之前已经讨论了该主题,但尚未提供解决方案。

在Python中:

  key = RSA.generate(2048, e=65537)
  pri_key = key.exportKey()
  n = key.n

  session['S_publicKey']  = n
  session['S_privateKey'] = pri_key

  publicKey_IntN = session.get('S_publicKey')
  publicKey_HexN = hex(publicKey_IntN)[2:].rstrip("L")  

  render_template('Shop.html', t1=publicKey_HexN )

在Shop.html(JavaScript)中:

function submitToPython() {
  var d1 = document.getElementById('input1').value;
  var d2 = document.getElementById('input2').value;

  var strJSON = JSON.stringify({data1:d1,data2:d2});   
  var publicKey_HexStrN = sessionStorage.getItem("SpublicKey");

  jsonRsa = do_encrypt(strJSON, publicKey_HexStrN);

  document.getElementById("messageJSON").value = jsonRsa;
  document.getElementById('input1').value = "";
  document.getElementById('input2').value = "";
  document.getElementById("form1").action = "/Order";
  document.getElementById("form1").method = "POST";
  document.getElementById("form1").submit();
}

function do_encrypt(strIn, nKey) {
  var rsa = new RSAKey();
  rsa.setPublic( nKey, "10001" );   # also tested "0x10001"
  var strOut = rsa.encrypt(strIn);
  return strOut;
}

在Python中:

  jsonrsa    = request.form['messageJSON']     
  jsonrsa    = codecs.decode( jsonrsa, 'hex' ) 
  #jsonrsa    = jsonrsa.encode('utf-8')  # in Python 3, must pass bytes 

  privateKey = session.get('S_privateKey')
  jsonStr = decrypt_string(jsonrsa,privateKey)  # ERROR invalid decryption

def decrypt_string(encrypted,private_key):    
    rsakey = RSA.importKey(private_key)
    rsakey = PKCS1_OAEP.new(rsakey)    

    chunk_size = 256
    offset     = 0    
    decrypted  = ""   

    while offset < len(encrypted):
        decrypted += rsakey.decrypt(encrypted[offset:offset+chunk_size])
        offset += chunk_size    

    return decrypted

0 个答案:

没有答案