码迷,mamicode.com
首页 > Web开发 > 详细

Node.js 内置模块crypto加密模块(2) AES

时间:2019-06-10 13:20:16      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:this   高级   final   UNC   sha   style   targe   fun   utf8   

AES:高级加密标准 ( Advanced Encryption Standard )

AES是一种对称加密算法:加密需要密钥,且加密密钥和解密密钥相同

下面是AES加密的Node实现:

"use strict";
const crypto = require("crypto");

//封装使用AES加密的方法
function aesEncrept(data, key){
  //实例化一个cipher加密对象,使用aes192进行加密,key作为密钥
  const cipher = crypto.createCipher("aes192",key);
  //使用cipher对data进行加密,源数据类型为utf-8,输出数据类型为hex
  let crypted = cipher.update(data, "utf-8", "hex");
  crypted += cipher.final("hex");
  return crypted;
}

//封装对应的AES解密方法
function aesDecrept(encrepted, key) {
  //实例化一个decipher解密对象,使用aes192进行解密,key作为密钥
  const decipher = crypto.createDecipher("aes192", key);
  //使用decipher对encrepted进行解密,源数据类型为hex,输出数据类型为utf-8
  let decrypted = decipher.update(encrepted, "hex", "utf-8");
  decrypted += decipher.final("utf-8");
  return decrypted;
}


let data = "This is what needs to be encrepted",
keyword = "This is the key",
encrepted = aesEncrept(data, keyword),
decrepted = aesDecrept(encrepted, keyword);

console.log( "原始数据:" + data );
console.log( "经过AES加密后:" + encrepted );
console.log( "经过相应的解密后:" + decrepted );

 

注:

1.update方法只能对源数据或加密数据的前16位进行加密或解密

2.final方法就是解决上面的缺陷,可以对剩余的数据进行加密

所以才有了下面的这个写法:

  let decrypted = decipher.update(encrepted, "hex", "utf8");
  decrypted += decipher.final("utf-8");

目的就是为了对全部的数据进行加密或解密

 

 

拓展阅读:AES加密算法的详细介绍与实现

        来源:CSDN

        作者:TimeShatter

Node.js 内置模块crypto加密模块(2) AES

标签:this   高级   final   UNC   sha   style   targe   fun   utf8   

原文地址:https://www.cnblogs.com/hros/p/10997019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!