前端MD5加密、AES加解密

MD5加密

blueimp-md5

https://www.bootcdn.cn/blueimp-md5/

32位和16位

  • 32 位 MD5blueimp-md5 库默认计算得到的就是 32 位的十六进制字符串表示的 MD5 哈希值。
  • 16 位 MD5:16 位的 MD5 哈希值实际上是 32 位 MD5 哈希值中间的 16 位字符。

示例

1
2
3
// 从 32 位结果中截取 16 位
const md5_16 = md5_32.slice(8, 24);
console.log('16 位 MD5 哈希值:', md5_16);

浏览器

引用

1
<script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.19.0/js/md5.min.js"></script>

使用

1
console.info(md5("123456"));

ES6

npm

1
npm install blueimp-md5

使用

1
2
3
import md5 from "blueimp-md5";

console.info(md5("123456"));

结果

e10adc3949ba59abbe56e057f20f883e

NodeJS

1
2
3
4
5
6
7
8
9
10
11
12
// 引入 blueimp-md5 库
const md5 = require('blueimp-md5');

// 定义要计算 MD5 哈希值的字符串
const inputString = 'Hello, World!';

// 计算 MD5 哈希值
const hash = md5(inputString);

// 输出结果
console.log(`输入字符串: ${inputString}`);
console.log(`MD5 哈希值: ${hash}`);

AES加解密

添加依赖

1
npm install crypto-js --save

aes_ecb.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import CryptoJS from 'crypto-js'
export const aes = {
keystr: 'makeshuopsvmczzj',
// 字符串转hex
string2hex: function () {
let str = this.keystr
let tempstr = ''
for (let i = 0; i < str.length; i++) {
if (tempstr === '') tempstr = str.charCodeAt(i).toString(16)
else tempstr += str.charCodeAt(i).toString(16)
}
return tempstr
},
encrypt: function (srcStr) {
srcStr = srcStr + ''
let key = this.string2hex()
key = CryptoJS.enc.Hex.parse(key)
const enc = CryptoJS.AES.encrypt(srcStr, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
return enc.ciphertext.toString()
},
decrypt: function (encedStr) {
try {
let key = this.string2hex()
key = CryptoJS.enc.Hex.parse(key)
const dec = CryptoJS.AES.decrypt(CryptoJS.format.Hex.parse(encedStr), key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
return CryptoJS.enc.Utf8.stringify(dec)
} catch (e) {
return ''
}
}
}

调用

1
2
import { aes } from '@/assets/utils/aes_ecb'
let str = aes.encrypt("123456");