Encryption Snippets
You can use below code snippet to perform encryption and decryption of request and response
Javascript
const crypto = require('crypto');
const secretKey = SHARED_SECRET_KEY';
function encryption(token) {
try {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(secretKey), iv);
const encrypted = Buffer.concat([cipher.update(Buffer.from(token)), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, encrypted, tag]).toString('base64');
} catch (err) {
console.error(err);
return '';
}
}
function decryption(encryptedToken) {
try {
const encryptedBuffer = Buffer.from(encryptedToken, 'base64');
const nonce = encryptedBuffer.slice(0, 12);
const ciphertext = encryptedBuffer.slice(12, -16);
const tag = encryptedBuffer.slice(-16);
const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(secretKey), nonce);
decipher.setAuthTag(tag);
let decrypted = decipher.update(ciphertext);
decrypted += decipher.final();
return decrypted.toString('base64');
} catch (err) {
console.error(err);
return '';
}
}
Go
func Decrypt(key []byte, payload string) ([]byte, error) {
ciphertext, _ := base64.StdEncoding.DecodeString(payload)
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, err
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
Python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
nonce = get_random_bytes(12)
cipher = AES.new(b'u8x/A?D(G+KbPeShVmYq3t6w9y$B&E)H', AES.MODE_GCM, nonce=nonce)
import json
import base64
data = b'{"merchantPaymentReferenceId":"PAY-123-456","merchantOrderId":"ORD-123-456","merchantOrderDetailsUrl":"https://merchant.com/order/ORD-123-456","txnInfo":{"currency":"INR","amount":"700"},"transactionContext":"eyJmYXJlRGV0YWlscyI6eyJ0b3RhbEFtb3VudCI6IjQwMCIsInBheWFibGVBbW91bnQiOiI0MDAifSwiY2FydERldGFpbHMiOnsiY2FydEl0ZW1zIjpbeyJjYXRlZ29yeSI6IkZPT0QiLCJpdGVtSWQiOiJNRVItSVRFTS0xMDEiLCJwcmljZSI6IjQwMCIsIml0ZW1OYW1lIjoiU01PT1IiLCJxdWFudGl0eSI6MSwiYWRkaXRpb25hbEluZm8iOnsic2hpcHBpbmdJbmZvIjp7ImRlbGl2ZXJ5TG9jYXRpb24iOiJiYW5nYWxvcmUifX19XX19"}'
cipher_text, tag = cipher.encrypt_and_digest(data)
cipher_text = base64.b64encode(nonce+cipher_text+tag).decode('utf-8')
print("nonce {}".format(nonce))
print("cipher text {}".format(cipher_text))