0

在服务器上使用 Python 和 PyCrypto,在客户端上使用 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
4

0 回答 0