常见的加密

# 加密

# 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')
  • SHA-256
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 代码示例

  • 图片转 base64
1
2
const fs = require('fs')
const base64 = fs.readFileSync('image.png', 'base64')
  • base64 转图片
1
2
3
const fs = require('fs')
const base64 = 'data:image/png;base64,iVBORw0KGg...'
fs.writeFileSync('image.png', base64, 'base64')