AES:高級加密標準 ( Advanced Encryption Standard )算法
AES是一種對稱加密算法:加密須要密鑰,且加密密鑰和解密密鑰相同ui
下面是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";
//AES加密的密鑰 let keyword = "This is the key";
//使用自定義的aesEncrept方法進行加密 let encrepted = aesEncrept(data, keyword);
//使用自定義的aesDecrept方法對加密數據進行解密 let decrepted = aesDecrept(encrepted, keyword); console.log( "原始數據:" + data ); console.log( "經AES加密後:" + encrepted ); console.log( "經相應的解密後:" + decrepted );
注:spa
1.update方法只能對源數據的前16位進行加密,對加密數據的前32位進行解密;.net
2.final方法就是解決上面的缺陷,能夠對剩餘的數據進行加密/解密;code
因此纔有了下面的這個寫法:對象
let decrypted = decipher.update(encrepted, "hex", "utf8");
decrypted += decipher.final("utf-8");blog
目的就是爲了對所有的數據進行加密/解密ip
3.AES加密算法除了aes192
外,還有aes-128-ecb
,aes-256-cbc
等utf-8
拓展閱讀:AES加密算法的詳細介紹與實現
來源:CSDN
做者:TimeShatter