Last active
April 8, 2022 07:28
-
-
Save legend80s/b952872651128625e4809ed973ad173d to your computer and use it in GitHub Desktop.
AES/ECB/PKCS5Padding Cipher and Decipher of Node.js and can communicate with other languages
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
// modified based on [node.js AES/ECB/PKCS5Padding 与其他语言的加密解密通用](http://yijiebuyi.com/blog/13e2ae33082ac12ba4946b033be04bb5.html) | |
const crypto = require('crypto'); | |
module.exports = class Crypto { | |
/** | |
* 加解密必须使用同一套 key 和 iv | |
* @param {String} algorithm 算法名称,比如 `aes-128-ecb` | |
* @param {String} key 秘钥 | |
* @param {String} iv initialization vector,默认空字符串 | |
*/ | |
constructor(algorithm, key, iv = '') { | |
this.algorithm = algorithm; | |
this.key = key; | |
this.iv = iv; | |
} | |
/** | |
* 加密算法 | |
* | |
* @param {String} message 明文 | |
* @param {String} messageEncoding 明文编码 | |
* @param {String} cipherEncoding 密文编码 | |
* | |
* @return {String} encrypted 密文 | |
*/ | |
encrypt(message, messageEncoding = 'utf8', cipherEncoding = 'base64') { | |
const cipher = crypto.createCipheriv(this.algorithm, this.key, this.iv); | |
cipher.setAutoPadding(true); | |
let encrypted = cipher.update(message, messageEncoding, cipherEncoding); | |
encrypted += cipher.final(cipherEncoding); | |
return encrypted; | |
} | |
/** | |
* 解密算法 | |
* | |
* @param {String} encrypted 密文 | |
* @param {String} cipherEncoding 密文编码 | |
* @param {String} messageEncoding 明文编码 | |
* | |
* @return {String} decrypted 明文 | |
*/ | |
decrypt(encrypted, cipherEncoding = 'base64', messageEncoding = 'utf8') { | |
const decipher = crypto.createDecipheriv(this.algorithm, this.key, this.iv); | |
decipher.setAutoPadding(true); | |
let decrypted = decipher.update(encrypted, cipherEncoding, messageEncoding); | |
decrypted += decipher.final(messageEncoding); | |
return decrypted; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated.