JavaScript 加解密(crypto-js)

JeffChang
2 min readDec 13, 2018

--

快速入門使用AES加解密,做個學習筆記記錄。

安裝

首先,我們要先透過npm安裝套件,

npm i --save crypto-js

若是使用TypeScript的話,記得要多一個@type/scrypt-js

npm i --save crypto-js @types/crypto-js

使用方法

const CryptoJS = require('crypto-js')
const words = 'Hello, This is Jeff.'
const secretKey = 'ThisIsMyKey'
console.log(`Before encrypt => ${words}`)
// Encrypt
const ciphertext = CryptoJS.AES.encrypt(words, secretKey).toString()
console.log(`After encrypt => ${ciphertext}`)
// Decrypt
const originalText = CryptoJS.AES.decrypt(ciphertext, secretKey).toString(CryptoJS.enc.Utf8)
console.log(`After decrypt => ${originalText}`)

執行的結果如下

--

--