I am trying decrypt in a web application (developed with java/servlet) a token encrypted on the client-side with a javascript/JSEncrypt code.
this is the javascript code:
function submit() {
var form = document.querySelector("form");
var plainText = document.querySelector("input[name=ip]").value;
var fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.addEventListener('change', function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onloadend = function (e) {
var privateKey = e.target.result;
var encryptor = new JSEncrypt();
encryptor.setPrivateKey(privateKey);
var encryptedText = encryptor.encrypt(plainText);
const params = new URLSearchParams();
params.append('token', encryptedText);
fetch(form.action, {
method: form.method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params
})
.then(response => {
var main = document.querySelector("main");
var p = document.createElement("h1");
p.textContent = response.text();
main.appendChild(p);
//window.location.href = "http://localhost/inbox/home";
})
.catch(error => {
var main = document.querySelector("main");
var p = document.createElement("h1");
p.textContent = error.text();
main.appendChild(p);
});
};
reader.readAsText(file);
});
fileInput.click();
}
this is the java code that is trying to do the decryption:
public class RSADecryptor {
public static String decrypt(byte[] cipherText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSAKeyGenerator.RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
int keySize = ((RSAKey) publicKey).getModulus().bitLength();
int blockSize = keySize / 8;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int offset = 0;
while(offset < cipherText.length) {
int length = Math.min(cipherText.length - offset, blockSize);
byte[] block = cipher.doFinal(cipherText, offset, length);
outputStream.write(block, 0, block.length);
offset += blockSize;
}
byte[] decryptedBytes = outputStream.toByteArray();
//byte[] decryptedBytes = cipher.doFinal(cipherext);
return new String(decryptedBytes);
}
}
Anyone can point out what I am doing wrong here?