Javascript Encryption v2
Encryption Class
Create a new Encryption.js class and paste in the following Javascript code.
const crypto = require('crypto');
class Encryption{
constructor(ivKey, secretKey, algorithm) {
this.IVKey = ivKey;
this.secretKey = secretKey;
this.algorithm = algorithm;
}
encrypt(payload){
let key = crypto
.createHash('sha256')
.update(this.secretKey)
.digest('hex')
.substring(0, 32);
key = Buffer.from(key);
// prepare the IV key
let iv = crypto
.createHash('sha256')
.update(this.IVKey)
.digest('hex')
.substring(0, 16);
iv = Buffer.from(iv);
const cipher = crypto
.createCipheriv(this.algorithm, Buffer.from(key), iv);
let encrypted = cipher.update(payload);
encrypted = Buffer
.concat([encrypted, cipher.final()]);
let base64 = Buffer
.from(encrypted, 'binary')
.toString('base64');
return Buffer
.from(base64, 'binary')
.toString('base64')
}
}
module.exports = Encryption
Encryption Class Usage (Node.js)
Most people still have a misconception that Node.js would run on the browser. Node.js is a run-time environment that only runs on a server. For this example, we will use the Express Framework to create a realistic use case.
Create an Express app if you do not have one using the following commands. A more in-depth guide can be found here.
Step 1: Create a project directory $ mkdir checkout-demo
Step 2: Go into the project directory $ cd checkout-demo
Step 3: Initialize an NPM project accepting all prompts $ npm init -y
Step 4: Install the express framework $ npm install express --save
Then create a file CheckoutEncryption.js
and paste in the code below. Open a terminal session in your project directory and run the application using the command node CheckoutEncryption.js
const cors = require("cors")
const express = require('express');
const Encryption = require('./Encryption')
const app = express();
const port = 3000;
app.use(cors())
// enable parsing application/json
app.use(express.json());
app.post('/checkout-encryption', (req, res) => {
const accessKey = "<YOUR_ACCESS_KEY>"
const IVKey = "<YOUR_IV_KEY>";
const secretKey = "<YOUR_SECRET_KEY>";
const algorithm = "aes-256-cbc";
// get the request body
const requestBody = req.body;
let encryption = new Encryption(IVKey, secretKey, algorithm)
const payload = JSON
.stringify(requestBody)
.replace(/\//g, '\\/');
console.log(`https://developer.tingg.africa/checkout/v2/express/?params=${encryption.encrypt(payload)}&accessKey=${accessKey}&countryCode=${requestBody.countryCode}`)
// return a JSON response
res.json({
params: encryption.encrypt(payload),
accessKey,
countryCode: requestBody.countryCode
});
});
app.listen(
port,
() => console.log(`Listening on port ${port}!`)
);