7.node.js的3DES 加密和解密的方法封装

原文:http://blog.csdn.net/ererfei/article/details/73558226

 1 var assert = require('assert');  
 2 var crypto = require('crypto');  
 3 
 4 function test_des(param) {  
 5     var key = new Buffer(param.key);  
 6     var iv = new Buffer(param.iv ? param.iv : 0)  
 7     var plaintext = param.plaintext  
 8     var alg = param.alg  
 9     var autoPad = param.autoPad  
10 
11     //encrypt  
12     var cipher = crypto.createCipheriv(alg, key, iv);  
13     cipher.setAutoPadding(autoPad)  //default true  
14     var ciph = cipher.update(plaintext, 'utf8', 'hex');  
15     ciph += cipher.final('hex');  
16     console.log(alg, ciph)  
17 
18     //decrypt  
19     var decipher = crypto.createDecipheriv(alg, key, iv);  
20     cipher.setAutoPadding(autoPad)  
21     var txt = decipher.update(ciph, 'hex', 'utf8');  
22     txt += decipher.final('utf8');      
23     assert.equal(txt, plaintext, 'fail');  
24 }  
25 
26 test_des({  
27     alg: 'des-ecb',  
28     autoPad: true,  
29     key: '01234567',  
30     plaintext: '1234567812345678',  
31     iv: null  
32 })  
33 
34 test_des({  
35     alg: 'des-cbc',  
36     autoPad: true,  
37     key: '01234567',  
38     plaintext: '1234567812345678',  
39     iv: '12345678'  
40 })  
41 
42 test_des({  
43     alg: 'des-ede3',    //3des-ecb  
44     autoPad: true,  
45     key: '0123456789abcd0123456789',  
46     plaintext: '1234567812345678',  
47     iv: null  
48 })  
49 
50 test_des({  
51     alg: 'des-ede3-cbc',    //3des-cbc  
52     autoPad: true,  
53     key: '0123456789abcd0123456789',  
54     plaintext: '1234567812345678',  
55     iv: '12345678'  
56 })  

结果:

des-ecb cb22e0c49a73e0e0cb22e0c49a73e0e008bb5db6b37c06d7 
des-cbc 388d44f8b0f709c0915e14abc8eb782604ae07d96110ab0d 
des-ede3 0a5f769c1a6eb5710a5f769c1a6eb5713bba29a037c699da 
des-ede3-cbc 99988858eabe3e95ace8349b9e19dda66abb82b44b5f8f62 
原文地址:https://www.cnblogs.com/Nick-Hu/p/8335143.html