I am trying to encrypt Credit Card data of customer to AES 256 CBC format but anytime I I call the API I get this error:
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: ERR_INVALID_ARG_TYPE
at ServerResponse.writeHead (_http_server.js:259:11)
at ServerResponse._implicitHeader (_http_server.js:250:8)
This is my code for the encryption:
const crypto = require('crypto');
const encryptionType = 'aes-256-cbc';
const encryptionEncoding = 'base64';
const bufferEncryption = 'utf8';
export class AesEncryption {
AesKey: string;
AesIV: string;
init() {
this.AesKey = process.env.SECRET as string;
this.AesIV = process.env.SECRET?.slice(0, 16) as string;
}
encrypt(jsonObject: Object): string {
const val = JSON.stringify(jsonObject);
const key = Buffer.from(this.AesKey, bufferEncryption);
const iv = Buffer.from(this.AesIV, bufferEncryption);
const cipher = crypto.createCipheriv(encryptionType, key, iv);
let encrypted = cipher.update(val, bufferEncryption, encryptionEncoding);
encrypted += cipher.final(encryptionEncoding);
return encrypted;
}
}
This is the code of where I am using it:
public async createPayment(data: IPaymentDetails): Promise<IPaymentDetails> {
try {
PaymentService.checkPaymentRequiredFields(data);
data.encryptedData = new AesEncryption().encrypt(data.card)
console.log(data.encryptedData)
...
headers: {
'Content-Type': 'application/json',
Cookie: 'PHPSESSID=7hnkto3se3mlsbnht755ok2ak6',
},
data: JSON.stringify({
merchantId: data.merchantId,
method: 'Card',
id: data.trans_id,
encryptedData: data.encryptedData,
}),
})
Anytime I call the API I get the above error.
The problem is because the key and iv from process.env is not updating correctly, so it was throwing undefined.
I have to pass the process.env.SECRET directly into the function instead of passing them inside a variable.
It worked.