Java Class in JScriptor - ngduyquockhanh/JScriptor GitHub Wiki
AES GCM use Java class
var KeyGenerator = Java.type("javax.crypto.KeyGenerator");
var GCMParameterSpec = Java.type("javax.crypto.spec.GCMParameterSpec");
var SecretKey = Java.type("javax.crypto.SecretKey");
var SecureRandom = Java.type("java.security.SecureRandom");
var String = Java.type("java.lang.String");
var Cipher = Java.type("javax.crypto.Cipher");
function toUTF8Array(str) {
let utf8 = [];
for (let i = 0; i < str.length; i++) {
let charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6),
0x80 | (charcode & 0x3f));
}
else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
// surrogate pair
else {
i++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode = 0x10000 + (((charcode & 0x3ff)<<10)
| (str.charCodeAt(i) & 0x3ff));
utf8.push(0xf0 | (charcode >>18),
0x80 | ((charcode>>12) & 0x3f),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
}
return utf8;
}
var keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
var key = keyGenerator.generateKey();
var iv = new Uint8Array(12);
var gcmSpec = new GCMParameterSpec(128, iv);
var cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec);
var inputStr = "Hello, World!";
var inputData = toUTF8Array(inputStr);
cipher.update(inputData);
var encryptedData = cipher.doFinal();
cipher.init(Cipher.DECRYPT_MODE, key, gcmSpec);
cipher.update(encryptedData);
var decryptedData = cipher.doFinal();