7.node.js的DES的加密和解密操作示例

原文地址:https://mygo.iteye.com/blog/2018882

最近用到这个功能,所以存在自己博客方便查找。

var assert = require('assert');  
var crypto = require('crypto');  
  
function test_des(param) {  
    var key = new Buffer(param.key);  
    var iv = new Buffer(param.iv ? param.iv : 0)  
    var plaintext = param.plaintext  
    var alg = param.alg  
    var autoPad = param.autoPad  
      
    //encrypt  
    var cipher = crypto.createCipheriv(alg, key, iv);  
    cipher.setAutoPadding(autoPad)  //default true  
    var ciph = cipher.update(plaintext, 'utf8', 'hex');  
    ciph += cipher.final('hex');  
    console.log(alg, ciph)  
  
    //decrypt  
    var decipher = crypto.createDecipheriv(alg, key, iv);  
    cipher.setAutoPadding(autoPad)  
    var txt = decipher.update(ciph, 'hex', 'utf8');//我使用的是base64  
    txt += decipher.final('utf8');      
    assert.equal(txt, plaintext, 'fail');  
}  
  
test_des({  
    alg: 'des-ecb',  
    autoPad: true,  
    key: '01234567',  
    plaintext: '1234567812345678',  
    iv: null  
})  
  
test_des({  
    alg: 'des-cbc',  
    autoPad: true,  
    key: '01234567',  
    plaintext: '1234567812345678',  
    iv: '12345678'  
})  
  
test_des({  
    alg: 'des-ede3',    //3des-ecb  
    autoPad: true,  
    key: '0123456789abcd0123456789',  
    plaintext: '1234567812345678',  
    iv: null  
})  
  
test_des({  
    alg: 'des-ede3-cbc',    //3des-cbc  
    autoPad: true,  
    key: '0123456789abcd0123456789',  
    plaintext: '1234567812345678',  
    iv: '12345678'  
})  

 

转载于:https://www.cnblogs.com/Nick-Hu/p/10593713.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值