Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created August 28, 2022 05:54
Show Gist options
  • Save yano3nora/422183f268646e411e6af4edc83b4a8c to your computer and use it in GitHub Desktop.
Save yano3nora/422183f268646e411e6af4edc83b4a8c to your computer and use it in GitHub Desktop.
[js: crypto] Node.js encryption library. #js
import {
createCipheriv,
createDecipheriv,
} from 'crypto'
const PASSWORD = 'xxxxxxxxx'
const SALT = 'xxxxxxxxx'
const CIPHER_KEY = crypto.scryptSync(PASSWORD, SALT, 32).toString('hex')
const CIPHER_IV = crypto.randomBytes(16).toString('hex')
// ↑ まで事前に作っておいて環境変数とかにつっこむ
const ALGO = 'aes-256-cbc'
const KEY = Buffer.from(process.env.CIPHER_KEY || '', 'hex')
const IV = Buffer.from(process.env.CIPHER_IV || '', 'hex')
export const encryptPassword = (password: string) => {
let crypted
// 都度生成が必要っぽい
// https://stackoverflow.com/questions/51280576/trying-to-add-data-in-unsupported-state-at-cipher-update
const cipher = createCipheriv(ALGO, KEY, IV)
crypted = cipher.update(password, 'utf-8', 'hex')
crypted += cipher.final('hex')
return crypted
}
export const decryptPassword = (encrypted: string) => {
let decrypted
const decipher = createDecipheriv(ALGO, KEY, IV)
decrypted = decipher.update(encrypted, 'hex', 'utf-8')
decrypted += decipher.final('utf-8')
return decrypted
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment