I want to encrypt data between a Java Server backend and a GWT Client. On the GWT client I use the sbn.js library. It works very fast and is much faster that gwt-crypto.
Here is How I encrypt on the client side given (e,n) of RSA. I created a JSFiddle:
var n = "BC86E3DC782C446EE756B874ACECF2A115E613021EAF1ED5EF295BEC2BED899D26FE2EC896BF9DE84FE381AF67A7B7CBB48D85235E72AB595ABF8FE840D5F8DB";
var e = "3";
var d = "7daf4292fac82d9f44e47af87348a1c0b9440cac1474bf394a1b929d729e5bbcf402f29a9300e11b478c091f7e5dacd3f8edae2effe3164d7e0eeada87ee817b";
function do_encrypt() {
var before = new Date();
var rsa = new RSAKey();
rsa.setPublic(n, e);
var res = rsa.encrypt($("#plaintext").val());
$("#ciphertext").val(res);
$("#cipherb64").val(hex2b64(res));
console.log("res");
}
$("#encrypt").click(function () {
do_encrypt();
});
I use the hex representation of the encrypted plaintext to be decrypted on the server. Here is how I decrypt on the server.
I use the following libs:
compile 'org.bouncycastle:bcprov-jdk15on:1.51'
compile 'org.bouncycastle:bcprov-ext-jdk15on:1.51'
Here is how I decrypt on the server using (d,n) of RSA:
try {
BigInteger modulus = new BigInteger("BC86E3DC782C446EE756B874ACECF2A115E613021EAF1ED5EF295BEC2BED899D26FE2EC896BF9DE84FE381AF67A7B7CBB48D85235E72AB595ABF8FE840D5F8DB",16);
BigInteger exponent = new BigInteger("3");
RSAKeyParameters publicKey = new RSAKeyParameters(false, modulus, exponent)
BigInteger exponent2 = new BigInteger("7daf4292fac82d9f44e47af87348a1c0b9440cac1474bf394a1b929d729e5bbcf402f29a9300e11b478c091f7e5dacd3f8edae2effe3164d7e0eeada87ee817b", 16);
RSAKeyParameters privateKey = new RSAKeyParameters(true, modulus, exponent2)
String encryptedData = "a7f7d5c77c246729141cdfcc77f1f7b38d5f8066b0bc53b2e85119f3f1784f43be2140b5c382ad483bb57cc1b586962cbb1e831e6070a27e4880bbc549e20a372571d09c6b1269ddd7288916f10c96a9138f4165569c4767bfb489de2d44b450ed1495c99da985dc264dabadd9709ccd950ae55095373ccbc3344a26b3efd2dc";
////// decrypt
AsymmetricBlockCipher d = new RSAEngine();
d = new PKCS1Encoding(d);
d.init(false, privateKey);
byte[] messageBytes2 = new BigInteger(encryptedData,16).toByteArray();
byte[] hexEncodedCipher2 = d.processBlock(messageBytes2, 0, messageBytes2.length);
println("encrypted:"+new String(hexEncodedCipher2));
}
catch(Exception e) {
e.printStackTrace()
println "#################### error"
}
I got the following exception:
Error |
org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.
I suppose that the line println("encrypted:"+new String(hexEncodedCipher2)); is the problem.
How can I decrypt on the client side?
Why do I get different encryptions every time I ran the client side encryption with the same (e,n) and the same plaintext?