RSA encryption using JSEncrypt and decryption using BouncyCastle (Java)

This may be a duplicate of the answer to this question , but I cannot get the same results. We hope for some recommendations here.

JSEncrypt (client)

let encrypt = new Encrypt.JSEncrypt();
encrypt.setPublicKey(this.publicKey);  // retrieved from server
encrypt.encrypt(password);

BouncyCastle (server) - RSA key generation

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair pair = generator.generateKeyPair();
PublicKey pubKey = pair.getPublic();
PrivateKey privKey = pair.getPrivate();

// returned to client
String publicKeyStr = new String(Base64.encodeBase64(pubKey.getEncoded()));
String privateKeyStr = new String(Base64.encodeBase64(privKey.getEncoded()));

BouncyCastle (server) - Decryption

Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// org.apache.commons.codec.binary.Hex

byte[] cipherText = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));
decrypted = new String(cipherText, BaseConstant.ENC_UTF8);

Error

org.apache.commons.codec.DecoderException: Invalid hexadecimal character I at index 0 on org.apache.commons.codec.binary.Hex.toDigit (Hex.java:178) on org.apache.commons.codec.binary.Hex .decodeHex (Hex.java:89)

One thing that I noticed is the length of the JSEncrypt ciphertext, which is 172, and the server-side encryption is 256.

RSA/None/PKCS1Padding, . ?

+4
1

Hex.decodeHex(), , , .

JSEncrypt.encrypt() Base64 ( Hex-). , base64.

, :

byte[] cipherText = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));

:

byte[] cipherText = cipher.doFinal(Base64.decodeBase64(encrypted.toCharArray()));
+2

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


All Articles