I tried to do RSA encryption in javascript and decryption in java. I referred this as example (#2 post)
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
yourVariablePublic = kp.getPublic();
yourVariablePublic = kp.getPrivate();
} catch(NoSuchAlgorithmException e) {
}
Now let`s move to java code of our current page:
// receiving public key from where you store it
Key publicKey = YourCarrierClass.getYourVariablePublic();
KeyFactory fact;
// initializing public key variable
RSAPublicKeySpec pub = new RSAPublicKeySpec(BigInteger.ZERO, BigInteger.ZERO);
try {
fact = KeyFactory.getInstance("RSA");
pub = fact.getKeySpec(publicKey, RSAPublicKeySpec.class);
} catch(NoSuchAlgorithmException e1) {
} catch(InvalidKeySpecException e) {
}
// now you should pass Modulus string onto your html(jsp) in such way
String htmlUsedModulus = pub.getModulus().toString(16);
// send somehow this String to page, so javascript can use it
And to decrypt it in java code:
Key privateKey = YourCarrierClass.getYourVariablePrivate();
Cipher cipher;
BigInteger passwordInt = new BigInteger(ajaxSentPassword, 16);
byte[] dectyptedText = new byte[1];
try {
cipher = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding");
byte[] passwordBytes = passwordInt.toByteArray();
cipher.init(Cipher.DECRYPT_MODE, privateKey);
dectyptedText = cipher.doFinal(passwordBytes);
} catch(NoSuchAlgorithmException e) {
} catch(NoSuchPaddingException e) {
} catch(InvalidKeyException e) {
} catch(IllegalBlockSizeException e) {
} catch(BadPaddingException e) {
}
String passwordNew = new String(dectyptedText);
System.out.println("Password new " + passwordNew);
Like in example, I used the following code in javascript
function sendPassword() {
var password = $('#passwordField').val();
var rsa = new RSAKey();
rsa.setPublic($('#keyModulus').text(), '10001');
var res = rsa.encrypt(password);
$('#ajaxSentPassword').val(res);
}
I've altered the keypair generation part with Get method of servlet and stored the value to be passed to jsp in session. And changed the decryption part to POST method of servlet. I do get those keys for decryption by retrieving from session. This is just for my learning and I do realise that it'll be vulnerable if implemented in real time. This is to learn from the basics for me.
The problem is, in javascript code, it doesn't recognize the RSAkey(), I got as "Uncaught reference error: RSAKey() is not defined". Does anyone know what's the .js file used for that example. I tried jsencrypt.js, which shows as "Uncaught reference error: RSAKey() is not defined", and if I use rsa.js file - I got Invalid RSA Public key error. It's not stated which .js file is used by him.
It can also be found here (2nd answer)
Encrypt a small string with RSA in javascript then decrypt in java on server