var crypto = require("crypto");
var algorithm = "aes-256-cbc";
var self = module.exports = {
encryption: function (inputdata, key) {
// Generating 16 bytes random value & convert to hex
var iv = crypto.randomBytes(16);
var id = "a5b459000402bd8999fac0d68ec2b90e467f358f45880ada3375d81e4819c1c1";
iv = iv.toString("hex");
var hash = crypto.createHash('sha256').update(String(key));
var hashstring = hash.toString("hex").substring(0, 32);
var cipher = crypto.createCipheriv(algorithm, Buffer.from(hashstring, "hex"), Buffer.from(iv, "hex"));
var encrypted = cipher.update(inputdata, "utf8", "base64") + cipher.final("base64");
encrypted = encrypted.replace(/+/g, "-").replace(///g, "_"); // Replace + with - and / with _
return id + "." + iv + "." + encrypted;
},
decryption: function (encryptdata, iv, key) {
var hash = crypto.createHash("sha256").update(key).digest();
var hashstring = hash.toString("hex").substring(0, 32);
iv = Buffer.from(iv, "hex");
encryptdata = encryptdata.replace(/-/g, "+").replace(/_/g, "/"); // Replace - with + and _ with /
var decipher = crypto.createDecipheriv(algorithm, Buffer.from(hashstring, "hex"), iv);
var decrypted = decipher.update(encryptdata, "base64", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
};
var inputdata = { "data": 123 };
var encdata = self.encryption(JSON.stringify(inputdata), "uKxLYDvUrz");
console.log("Encrypted data:", encdata);
This is my complete code,
But while encryption, Its throwing error
node:internal/crypto/cipher:121
this[kHandle].initiv(cipher, credential, iv, authTagLength);
^
RangeError: Invalid key length
at Cipheriv.createCipherBase (node:internal/crypto/cipher:121:19)
at Cipheriv.createCipherWithIV (node:internal/crypto/cipher:140:3)
at new Cipheriv (node:internal/crypto/cipher:243:3)
at Object.createCipheriv (node:crypto:147:10)
at Object.encryption (D:DesktopeNachNodeindex.js:13:29)
at Object.<anonymous> (D:DesktopeNachNodeindex.js:36:20)
at Module._compile (node:internal/modules/cjs/loader:1358:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
at Module.load (node:internal/modules/cjs/loader:1208:32)
at Module._load (node:internal/modules/cjs/loader:1024:12) {
code: 'ERR_CRYPTO_INVALID_KEYLEN'
}
Node.js v20.15.0
Credentials I got from CamsPay
Encryption / Decryption Key
uKxLYDvUrz / 37D3T
Encryption ID
a5b459000402bd8999fac0d68ec2b90e467f358f45880ada3375d81e4819c1c1
Want to solve this issue @ earliest pls