Skip to content

Instantly share code, notes, and snippets.

@bhoriuchi
Created April 23, 2019 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhoriuchi/5aea6bee6f36980da69e344a7d15b702 to your computer and use it in GitHub Desktop.
Save bhoriuchi/5aea6bee6f36980da69e344a7d15b702 to your computer and use it in GitHub Desktop.
nodejs Chef Databag V3 Encrypt/Decrypt
import crypto from 'crypto';
// decrypt a v3 databag
export function decryptV3(data, key) {
try {
const decipher = crypto.createDecipheriv(
data.cipher.trim(),
crypto
.createHash('sha256')
.update(key.trim())
.digest(),
Buffer.from(data.iv.trim(), 'base64'),
);
decipher.setAuthTag(Buffer.from(data.auth_tag.trim(), 'base64'));
let cleartext = decipher.update(
data.encrypted_data.trim(),
'base64',
'utf8',
);
cleartext += decipher.final('utf8');
const obj = JSON.parse(cleartext);
return obj.json_wrapper;
} catch (err) {
throw err;
}
}
// encrypt a v3 databag
export function encryptV3(obj, key) {
const version = 3
const cipher = 'aes-256-gcm'
// convert data to string
const data = JSON.stringify({ json_wrapper: obj })
const iv = crypto.randomBytes(12)
const c = crypto.createCipheriv(
cipher,
crypto
.createHash('sha256')
.update(key.trim())
.digest(),
iv,
)
const enc = c.update(Buffer.from(data))
const final = c.final()
const encryptedData = Buffer.concat([enc, final])
const authTag = c.getAuthTag()
return {
encrypted_data: encryptedData.toString('base64'),
iv: iv.toString('base64'),
auth_tag: authTag.toString('base64'),
version,
cipher,
}
}
// generates a secret key
export function generateSecretKey(length) {
if (typeof length !== 'number' || length % 128 !== 0) {
throw new Error('key length must be a multiple of 128')
}
return crypto.randomBytes(length).toString('base64')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment