互操作Python JavaScript RSA加密

2024-06-17 12:47:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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 )

在商店.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

Tags: key服务器valuesessionvarjavascriptdocumentoffset