# 加密
# AES
# AES 应用场景
数据传输
# AES 代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import CryptoJS from 'crypto-js'
const key = CryptoJS.enc.Utf8.parse('1234567890123456') const iv = CryptoJS.enc.Utf8.parse('1234567890123456')
const encryptedData = CryptoJS.AES.encrypt('hello world', key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }).toString()
const decryptedData = CryptoJS.AES.decrypt(encryptedData, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }).toString(CryptoJS.enc.Utf8)
|
# RSA
# 原理解析
https://zhuanlan.zhihu.com/p/450180396
https://blog.csdn.net/dbs1215/article/details/48953589
# RSA 应用场景
数据传输
# RSA 代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const crypto = require('crypto')
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'pkcs1', format: 'pem' }, privateKeyEncoding: { type: 'pkcs1', format: 'pem' } })
const encryptedData = crypto.publicEncrypt(publicKey, Buffer.from('hello world'))
const decryptedData = crypto.privateDecrypt(privateKey, encryptedData)
|
# MD5、SHA-1\SHA-256
# MD5 应用场景
1. 文件完整性检查
2. 密码哈希存储
3. 数字签名
# MD5 代码示例
1 2 3 4
| const crypto = require('crypto') const md5 = crypto.createHash('md5') md5.update('hello world') const hash = md5.digest('hex')
|
1 2
| const md5 = require('md5') const hash = md5('hello world')
|
1 2 3 4
| const crypto = require('crypto') const sha256 = crypto.createHash('sha256') sha256.update('hello world') const hash = sha256.digest('hex')
|
# SHA
# SHA 应用场景
密码明文转密文存储
# SHA 代码示例
# Base64
- 编码算法,可逆,常用于图片、音频等二进制数据的编码
# Base64 应用场景
# Base64 代码示例
1 2
| const fs = require('fs') const base64 = fs.readFileSync('image.png', 'base64')
|
1 2 3
| const fs = require('fs') const base64 = 'data:image/png;base64,iVBORw0KGg...' fs.writeFileSync('image.png', base64, 'base64')
|