Home > Net >  Convert NodeJS code snippet into Java code for encryption/decryption
Convert NodeJS code snippet into Java code for encryption/decryption

Time:11-15

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;
    }
}

CodePudding user response:

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. And createCipher[iv] and createDecipher[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.)

byte[] keyIn = "0Z8ZUcy1Qh8lnt199MTwTPEe2g1E2tE3" .getBytes("ASCII"); 
    // if any non-ASCII char(s) must select same encoding nodejs does, I believe utf8
    // instead of string form can use e.g. StandardCharsets.US_ASCII
byte[] keyHash = MessageDigest.getInstance("SHA-256") .doFinal(keyIn);
    // or "sha-256" Java crypto names are case-insensitive
    // can separate steps with hasher = .getInstance(); hasher.update(keyIn); result = hasher.doFinal()
    // but cannot do fluent-style result = .getInstance() .update(keyIn) .doFinal()
byte[] iv = new byte[16]; // Java automatically fills numeric array with (binary) zeros
Cipher dec = Cipher.getInstance("AES/CBC/PKCS5Padding");
dec.init (Cipher.DECRYPT_MODE, new SecretKeySpec(keyHash,"AES"), new IvParameterSpec(iv));
String clear = new String( dec.doFinal (Base64.getDecoder().decode( someAuthString )), "UTF-8");
    // or StandardCharsets.UTF_8
  • Related