Skip to content

Instantly share code, notes, and snippets.

@kuboon
Last active June 12, 2020 01:03
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 kuboon/8fd1ee2c2d311e590f316400018df992 to your computer and use it in GitHub Desktop.
Save kuboon/8fd1ee2c2d311e590f316400018df992 to your computer and use it in GitHub Desktop.
Typescript nodejs stdlib enc/dec sample
import * as crypto from 'crypto'
import assert from 'assert'
const ivKey = 'randomString1-fah3f;aklajr'
const initialVec = Buffer.alloc(16, 0)
crypto
.createHash('sha256')
.update(ivKey)
.digest().copy(initialVec)
const key = (passphrase: string) => crypto
.createHash('sha256')
.update(passphrase)
.digest()
const plainEncoding = 'utf8'
const encryptedEncoding = 'base64'
export function enc (plain: string, passphrase: string) {
const salt = crypto.randomBytes(3).toString('base64')
const cipher = crypto.createCipheriv('aes256', key(passphrase), initialVec)
return cipher.update(salt + plain, plainEncoding, encryptedEncoding) + cipher.final(encryptedEncoding)
}
export function dec (encrypted: string, passphrase: string) {
const decipher = crypto.createDecipheriv('aes256', key(passphrase), initialVec)
const ret = decipher.update(encrypted, encryptedEncoding, plainEncoding) + decipher.final(plainEncoding)
return ret.slice(4)
}
function test (msg: string) {
const passphrase = 'pass'
const encrypted = [enc(msg, passphrase), enc(msg, passphrase)]
console.log(encrypted)
assert.strict.notEqual(encrypted[0], encrypted[1])
const decrypted = encrypted.map(x => dec(x, passphrase))
console.log(msg, decrypted)
assert.strict.equal(decrypted[0], decrypted[1])
}
test('hogehogefugafuga')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment