I want to convert this below piece of code into java but I am unable to do, Basically I have to implement 'crypto' module in Java. Thanks in advance!
let encKey = "0Z8ZUcy1Qh8lnt199MTwTPEe2g1E2tE3";
encKey = crypto.createHash('sha256').update(encKey).digest('bin').slice(0, 32);
let char = String.fromCharCode(0x0);
let iv = char + char + char + char + char + char + char + char + char + char + char + char + char + char + char + char;
let decryptor = crypto.createDecipheriv("aes-256-cbc", encKey, iv);
let dec = decryptor.update(someAuthString, 'base64', 'utf8') + decryptor.final('utf8');
dec = removePKCS5Padding(dec);
removePKCS5Padding
function removePKCS5Padding(text) {
let pad = ord(text[text.length - 1]);
pad = text.substr(0, -1 * pad)
if (_.isEmpty(pad)) {
return text;
} else {
return pad;
}
}
First you don't need to implement the whole module, just particular algorithms from it.
Second whoever wrote that code didn't know what they were doing. SHA-256 already produces a 32-byte value (always) so
.slice(0,32)accomplishes nothing. AndcreateCipher[iv]andcreateDecipher[iv]for a block mode already add and remove 'PKCS5' padding automatically unless explicitly disabled. (Prior to PKCS5v2.1 it was technically more correct to say PKCS7 or PKCS5/7, but in practice people often don't bother, and Java calls it PKCS5. OpenSSL, which nodejs crypto uses internally, punts and calls it PKCS padding -- although there are several PKCS1 paddings which are quite different, and which OpenSSL also implements.)