Are there any asymmetric encryption options for JavaScript?

后端 未结 5 589
独厮守ぢ
独厮守ぢ 2020-12-05 07:45

I have to transfer some sensitive information over a JavaScript AJAX Call, over an unencrypted channel (HTTP, not HTTPS).

I\'d like to encrypt the data, but encrypti

5条回答
  •  有刺的猬
    2020-12-05 07:59

    I've done it. I use this JavaScript client-side asymetric RSA encryption to prevent the login credentials to be send in plain text over HTTP.

    The goal is to prevent login request replay attacks based on network sniffing. Of course, this is not as secure as HTTPS since it would not resist to man-in-the-middle attacks, but it can be sufficient for local networks.

    The client-side encryption uses Travis Tridwell's excellent work which is based on JSBN. Travis' web page can also generate the private and public RSA keys (if you are too lazy to use openssl). The keys are generated in PKCS#1 PEM format. I encrypt username+password+timeInMs+timezone so that the encrypted content changes at each login.

    On the server-side, my Java code read read the PKCS#1 PEM file using Apache JMeter's org.apache.jmeter.protocol.oauth.sampler.PrivateKeyReader :

    PrivateKey pk = (new PrivateKeyReader("myPrivateKeyFile.pem")).getPrivateKey();
    

    Then I decrypt the encrypted content using

    byte[] enc = DatatypeConverter.parseBase64Binary(clientData);
    Cipher rsa = Cipher.getInstance("RSA");
    rsa.init(Cipher.DECRYPT_MODE, pk);
    byte[] dec = rsa.doFinal(enc);
    String out = new String(dec, "UTF8");
    

    Then I check if the client-side timestamp/timezone match the server-side timestamp/timezone. If the delay is less than a few seconds, the login process continues. Otherwise the request is considered a replay attack and the login fails.

提交回复
热议问题