Created
January 24, 2022 23:28
-
-
Save num8er/9233f6c5397418ec428debe30da3e23f to your computer and use it in GitHub Desktop.
This file contains 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
const crypto = require('crypto'); | |
class Crypter { | |
constructor (secretKey, secretKeySalt) { | |
this._keychain = { | |
key: this.createKey(secretKey, secretKeySalt), | |
iv: this.createIV(secretKey, secretKeySalt) | |
}; | |
} | |
createKey (secretKey, secretKeySalt) { | |
const data = [...secretKeySalt].reverse().join(secretKey); | |
return crypto.createHash('md5').update(data).digest('hex'); | |
} | |
createIV (secretKey, secretKeySalt) { | |
const data = [...secretKey].reverse().join(secretKeySalt); | |
return crypto.createHash('md5').update(data).digest('hex').slice(0, 16); | |
} | |
get cipher () { | |
return crypto.createCipheriv('aes-256-ctr', this._keychain.key, this._keychain.iv); | |
} | |
get decipher () { | |
return crypto.createDecipheriv('aes-256-ctr', this._keychain.key, this._keychain.iv); | |
} | |
encrypt (data) { | |
if (!data) data = ''; | |
const cipher = this.cipher; | |
return cipher.update(data, 'utf8', 'hex') + cipher.final('hex'); | |
} | |
decrypt (data) { | |
if (!data) data = ''; | |
const decipher = this.decipher; | |
return decipher.update(data, 'hex', 'utf8') + decipher.final('utf8'); | |
} | |
} | |
module.exports = new Crypter(process.env.CRYPTER_KEY, process.env.CRYPTER_SALT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment