Created
February 27, 2023 06:37
-
-
Save dalenguyen/b3fa4a6de6502b59988662457dbfc047 to your computer and use it in GitHub Desktop.
Webhooks payload encrypt & decrypt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CryptoJS = require('crypto-js') | |
const secret = 'my-secret-key' // shared by producer & consumer | |
// Producer | |
const payload = { | |
name: 'John Doe', | |
email: '[email protected]', | |
phone: '555-1234', | |
} | |
// send via header | |
const signature = CryptoJS.HmacSHA256(JSON.stringify(payload), secret).toString() | |
const encrypted = CryptoJS.AES.encrypt(JSON.stringify(payload), secret).toString() | |
console.log({ signature, encrypted }) | |
// { | |
// signature: 'eb463519efbb1073912188c21758719f5774389c697e5bb45c2b990ffc72b457', | |
// encrypted: 'U2FsdGVkX1/ZiUfmnwwUW/xbmw5bx7DDcMZhTICKBxIZgQVy+OnUULeu0uzNtVckVXqXFQCf6scdAwT/kTHuVU+EhZm69jgUtB5V2CE5d958idRR1pt4Z1wYhsw1bRlN' | |
// } | |
// Consumer | |
const bytes = CryptoJS.AES.decrypt(encrypted, secret) | |
const decryptedPayload = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)) | |
// verify the integrity of data using signature | |
const verified = CryptoJS.HmacSHA256(JSON.stringify(decryptedPayload), secret).toString() === signature | |
console.log({ decryptedPayload, verified }) | |
// { | |
// decryptedPayload: { | |
// name: 'John Doe', | |
// email: '[email protected]', | |
// phone: '555-1234' | |
// }, | |
// verified: true | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment