1

I need to convert crypto from NodeJS to Java. My secretKey is 63 bytes, and don't use IV. How can I convert 2 functions below to Java? Can anyone show me a snippet? Thank you!

var secretKey = 'fkldsjfweurioweurioewur819734897489327489327843fsdkfjdskjfdsklj'; //63 bytes
function textEncrypt() {
    const cipher = crypto.createCipher('aes-256-cbc', secretKey);
    let crypted = cipher.update(data, 'utf-8', 'hex');
    crypted += cipher.final('hex');
    return crypted;
}
function textDecrypt(encrypted) {
    const decipher = crypto.createDecipher('aes-256-cbc', secretKey);
    let decrypted = decipher.update(encrypted, 'hex', 'utf-8');
    decrypted += decipher.final('utf-8');
    return decrypted;
}
Xperia
  • 79
  • 9
  • Does [this](https://stackoverflow.com/questions/46835158/aes-256-cbc-in-java) answer help? –  Jun 10 '20 at 04:46
  • @Mandy8055 - The main problem is not covered by the link. `createCipher` uses a key derivation function from OpenSSL (`EVP_BytesToKey`) which derives key and IV from a password. Therefore, to implement `createCipher` in Java, `EVP_BytesToKey` must also be implemented. Such an implementation is available [here](https://stackoverflow.com/a/11786924). – Topaco Jun 10 '20 at 06:28
  • The key derivation function (KDF) used by `createCipher` is relatively weak and based on the proprietary OpenSSL function `EVP_BytesToKey`. `createCipher` is also deprecated (probably because of this). Its use only makes sense if you need compatibility to OpenSSL regarding key generation. Otherwise `createCipheriv` makes more sense. Here, key and IV are specified directly (which can be derived in a separate step with a reliable KDF if needed). – Topaco Jun 10 '20 at 06:29

0 Answers0