RSA Java encryption and Node.js decryption does not work

I have a system that requires an RSA key pair to be generated in javascript, then the public key is then stored in the database on the server side (as a string), then the server side, which is in Java, will encrypt the string using the saved open key and send it to the client side, which will decrypt the string using the private key.

I am using the viewed version of node -rsa in my client browser.

First, on the client, I generate a key pair and export the keys, saving them as strings

var NodeRSA = require('node-rsa'); var key = new NodeRSA({b: 1024}); key.exportKey("pkcs8-private"); key.exportKey("pkcs8-public-pem"); 

The export private key is stored by the client and the public on the server

Then I used java to encrypt the string with the resulting public key, so I parsed the pkcs8 public key in the Java PublicKey.

 String pubKey = "<Retrieved pkcs8 public key>"; pubKey = pubKey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", ""); byte[] keyBytes = Base64.decodeBase64(pubKey); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pk = kf.generatePublic(spec); 

And encrypt the text with

 byte[] cipherText; Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pk); cipherText = cipher.doFinal("Hello World!".getBytes()); return Base64.encodeBase64String(cipherText); 

Which works well and returns me a Base64 encoded encrypted string like this

 WTS1J2f4w5icsUOCtulyHDaBmB5lN7D8mnj0QWMDBkUGiPHkM8nHVx9pd0MtbQAQNasQS2X8kisLMYyEMPasFZtDH0zX1e8lNYaW0xMKsg++ge87f+95nl+TmxDy6S1m7Ce/n0wXno+0MbSv8YsJtsUcAleyyfQX2bxqX8u7Gjs= 

Then I try to decrypt the string on the client side

First I reimport the stored keys in node -rsa

 var NodeRSA = require('node-rsa'); var key = new NodeRSA(); key.importKey("<exported private key string>","pkcs8-private"); key.importKey("<exported public key string>","pkcs8-public-pem"); 

Then I try to decrypt an encrypted Base64 encoded string

 key.decrypt("<Base64 Encoded Encrypted>", 'utf-8'); 

This is where the problem arises, javascript throws this error

Error on failure: error during decryption (possibly incorrect key). Original error: Error: decoding error message, lHash calculated on the attached label, and lHash in the encrypted data do not match. (...) However, I tested that if I only encrypt and decrypt text in javascript, it works fine. It makes me think that this is some kind of difference between how I encrypted it in java and how it was done in javascript

Can anyone point out the mistake I made here?

+5
source share
1 answer

Oh, I found a solution. This was a difference in the encryption method.

I just needed to initialize Cipher with

 Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); 

instead

 Cipher.getInstance("RSA"); 

to match node -rsa

+4
source

Source: https://habr.com/ru/post/1240788/


All Articles