|
| 1 | + |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +/* |
| 6 | +
|
| 7 | +aes-encrypt-decrypt-nodejs.js |
| 8 | +
|
| 9 | +30-04-26 |
| 10 | +
|
| 11 | +
|
| 12 | +*/ |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +const crypto = require("crypto"); |
| 17 | + |
| 18 | +function importAesKey(base64) { |
| 19 | + return Buffer.from(base64, "base64"); // raw 32‑byte key |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | +function aesEncryptNode(keyBuf, plaintext) { |
| 24 | + const iv = crypto.randomBytes(12); |
| 25 | + |
| 26 | + const cipher = crypto.createCipheriv("aes-256-gcm", keyBuf, iv); |
| 27 | + |
| 28 | + const encrypted = Buffer.concat([ |
| 29 | + cipher.update(plaintext, "utf8"), |
| 30 | + cipher.final() |
| 31 | + ]); |
| 32 | + |
| 33 | + const tag = cipher.getAuthTag(); |
| 34 | + |
| 35 | + return { |
| 36 | + iv: iv.toString("base64"), |
| 37 | + data: encrypted.toString("base64"), |
| 38 | + tag: tag.toString("base64"), |
| 39 | + }; |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +function aesDecryptNode(keyBuf, encrypted) { |
| 45 | + const iv = Buffer.from(encrypted.iv, "base64"); |
| 46 | + const data = Buffer.from(encrypted.data, "base64"); |
| 47 | + const tag = Buffer.from(encrypted.tag, "base64"); |
| 48 | + |
| 49 | + const decipher = crypto.createDecipheriv("aes-256-gcm", keyBuf, iv); |
| 50 | + decipher.setAuthTag(tag); |
| 51 | + |
| 52 | + const decrypted = Buffer.concat([ |
| 53 | + decipher.update(data), |
| 54 | + decipher.final() |
| 55 | + ]); |
| 56 | + |
| 57 | + return decrypted.toString("utf8"); |
| 58 | +} |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + |
0 commit comments