Created
August 28, 2022 05:54
-
-
Save yano3nora/422183f268646e411e6af4edc83b4a8c to your computer and use it in GitHub Desktop.
[js: crypto] Node.js encryption library. #js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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