Skip to content

Instantly share code, notes, and snippets.

@mwgamera
Last active May 23, 2020 21:35
Show Gist options
  • Save mwgamera/5bad53a3c3721b8909bfe6bee2f83f0f to your computer and use it in GitHub Desktop.
Save mwgamera/5bad53a3c3721b8909bfe6bee2f83f0f to your computer and use it in GitHub Desktop.
'use strict'
const crypto = require('crypto')
const {promisify} = require('util')
let pwtokey = (pass, salt='', iter=100) =>
promisify(crypto.pbkdf2)(pass, salt, iter, 16, 'sha256')
let encrypt = async (key, msg) => {
let iv = await promisify(crypto.randomBytes)(16)
let ctx = crypto.createCipheriv('aes-128-gcm', key, iv)
return Buffer.concat([
iv,
ctx.update(msg, 'utf8'),
ctx.final(),
ctx.getAuthTag()
]).toString('base64')
}
let decrypt = async (key, msg) => {
let buf = Buffer.from(msg, 'base64')
let ctx = crypto.createDecipheriv('aes-128-gcm', key, buf.slice(0, 16))
ctx.setAuthTag(buf.slice(-16))
return ctx.update(buf.slice(16, -16), null, 'utf8') + ctx.final('utf8')
}
module.exports = {
pwtokey,
encrypt,
decrypt,
}
'use strict'
let str2buf = (e => e.encode.bind(e))(new TextEncoder('utf-8'))
let buf2str = (e => e.decode.bind(e))(new TextDecoder('utf-8'))
let asc2buf = asc => Uint8Array.from(atob(asc), s => s.charCodeAt(0))
let buf2asc = buf => btoa(String.fromCharCode.apply(null, new Uint8Array(buf)))
let pwtokey = async (pass, salt='', iter=100) =>
crypto.subtle.deriveKey({
name: 'PBKDF2',
salt: str2buf(salt),
iterations: iter,
hash: 'SHA-256'
}, await crypto.subtle.importKey(
'raw', str2buf(pass),
{name: 'PBKDF2'}, false, ['deriveKey']
), {
name: 'AES-GCM',
length: 128
}, false, ['encrypt', 'decrypt'])
let decrypt = async (key, msg) => {
let buf = await asc2buf(msg)
return buf2str(await crypto.subtle.decrypt({
name: 'AES-GCM',
iv: buf.slice(0, 16)
}, key, buf.slice(16)))
}
let encrypt = async (key, msg) => {
let iv = crypto.getRandomValues(new Uint8Array(16))
let cm = await crypto.subtle.encrypt({
name: 'AES-GCM', iv
}, key, str2buf(msg))
let buf = new Uint8Array(cm.byteLength + 16)
buf.set(iv)
buf.set(new Uint8Array(cm), 16)
return buf2asc(buf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment