I have following code in node.js using crypto-js to encrypt password using AES with Secret Key and IV.
const crypto = require('crypto-js');
const cryptKey = 'b676eac8cf70442385dfd4bcfaa61b52';
const createRandomIv = function () {
const keySize = 192 / 32;
const ivSize = 128 / 32;
const evp = crypto.algo.EvpKDF.create({ keySize: keySize + ivSize, hasher: crypto.algo.SHA1 }).compute(cryptKey);
const iv = crypto.lib.WordArray.create(evp.words.slice(keySize), ivSize * 4);
return iv.toString();
};
const encryptPassword = function (password) {
const iv = createRandomIv();
const hash = crypto.AES.encrypt(
password,
cryptKey, {
iv,
mode: crypto.mode.CTR
}
);
const base64 = crypto.enc.Base64.parse(hash.toString());
const eHex = base64.toString(crypto.enc.Hex);
return `${iv}:${eHex}`;
};
const decryptPassword = function (encryptedPwd) {
const split = encryptedPwd.split(':');
if (split.length < 2) return '';
const reb64 = crypto.enc.Hex.parse(split[1]);
const bytes = reb64.toString(crypto.enc.Base64);
const hash = crypto.AES.decrypt(bytes, cryptKey, {
iv: split[0],
mode: crypto.mode.CTR
});
const plain = hash.toString(crypto.enc.Utf8);
return plain;
};
And here is the encrypted password from node js.
const encryptedPassword = encryptPassword("Stack Overflow");
console.log(encryptedPassword);
// 2db5c01b4825b6d4dd7a7b96f04f3bb5:53616c7465645f5f691671363cda1b9d05ee6bdd637e1e99bc3b29ef2ad7ec53
And already tried go decrpyt it using golang as follow
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"strings"
)
func main() {
secretKey := "b676eac8cf70442385dfd4bcfaa61b52"
encryptedPwd := "2db5c01b4825b6d4dd7a7b96f04f3bb5:53616c7465645f5f691671363cda1b9d05ee6bdd637e1e99bc3b29ef2ad7ec53"
split := strings.Split(encryptedPwd, ":")
c, _ := aes.NewCipher([]byte(secretKey))
cfbdec := cipher.NewCBCDecrypter(c, []byte(split[0]))
plaintext := make([]byte, len(split[1]))
cfbdec.CryptBlocks(plaintext, []byte(split[1]))
fmt.Println(plaintext)
}
But it panics as follow.
panic: cipher.NewCBCDecrypter: IV length must equal block size goroutine 1 [running]: crypto/cipher.NewCBCDecrypter({0x10c4ee8, 0xc000066060}, {0xc00001e040, 0x1, 0x20})
Updated 1
I updated the code to decrypted without using iv, but the result is not human readable.
split := strings.Split(encryptedPwd, ":")
ciphertext, _ := hex.DecodeString(split[1])
c, _ := aes.NewCipher([]byte(secretKey))
plaintext := make([]byte, len(ciphertext))
c.Decrypt(plaintext, []byte(ciphertext))
fmt.Println(string(plaintext))
|A/��c�*Z�S/�x
What's wrong with the decryption in my golang code, can anybody please help me? I already use the same key and iv by splitting it from the encrypted password.