Взаимодействие Python JavaScript RSA Шифрование - PullRequest
0 голосов
/ 10 сентября 2018

Python с PyCrypto на сервере, библиотека 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
...