编程学习资讯网

nodejs aes 加解密实例学习,实用代码

发布时间:2018-10-12 10:28:53   来源:本站编辑   浏览次数:

如下所示:

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'use strict';
const crypto = require('crypto');
 
/**
 * AES加密的配置
 * 1.密钥
 * 2.偏移向量
 * 3.算法模式CBC
 * 4.补全值
 */
var AES_conf = {
  key: getSecretKey(), //密钥
  iv: '1012132405963708', //偏移向量
  padding: 'PKCS7Padding' //补全值
}
 
/**
 * 读取密钥key
 * 更具当前客户端的版本vid、平台platform获取对应的key
 */
function getSecretKey(){
  return "abcdabcdabcdabcd";
}
 
/**
 * AES_128_CBC 加密
 * 128位
 * return base64
 */
function encryption(data) {
  let key = AES_conf.key;
  let iv = AES_conf.iv;
  // let padding = AES_conf.padding;
 
  var cipherChunks = [];
  var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
  cipher.setAutoPadding(true);
  cipherChunks.push(cipher.update(data, 'utf8', 'base64'));
  cipherChunks.push(cipher.final('base64'));
  return cipherChunks.join('');
}
 
 
/**
 * 解密
 * return utf8
 */
function decryption(data){
 
  let key = AES_conf.key;
  let iv = AES_conf.iv;
  // let padding = AES_conf.padding;
 
  var cipherChunks = [];
  var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
  decipher.setAutoPadding(true);
  cipherChunks.push(decipher.update(data, 'base64', 'utf8'));
  cipherChunks.push(decipher.final('utf8'));
  return cipherChunks.join('');
}
 
 
console.log(encryption('aaaaa4'));
console.log(decryption('VuoXtyUolFyPrK50JnNUdw=='));

?

编程学习网 http://www.javalearns.cn

关注微信号:javalearns   随时随地学Java

或扫一扫


随时随地学Java