typescript - RSA encrypt using JSEncrypt and decrypt using BouncyCastle (Java) -
this might duplicate of this answered question, can't seem same results. hoping guidance here.
jsencrypt (client)
let encrypt = new encrypt.jsencrypt(); encrypt.setpublickey(this.publickey); // retrieved 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 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: illegal hexadecimal character @ index 0 @ org.apache.commons.codec.binary.hex.todigit(hex.java:178) @ org.apache.commons.codec.binary.hex.decodehex(hex.java:89)
one thing noticed length of encrypted text jsencrypt, 172, while encryption @ server side produces 256.
the answered question mentioned use rsa/none/pkcs1padding, had set. else missing?
the error occurs in hex.decodehex() method, means data not hex encoded string.
jsencrypt.encrypt() method returns encrypted data in base64 (instead of hex string). in order decrypt it, must decode base64 format.
so instead of:
byte[] ciphertext = cipher.dofinal(hex.decodehex(encrypted.tochararray())); do this:
byte[] ciphertext = cipher.dofinal(base64.decodebase64(encrypted.tochararray()));
Comments
Post a Comment