最近遇到前后端传输数据需要进行加密的需求,本篇文章就分别介绍使用 Node.js 和 go 进行 AES 加密解密的方法, AES 有很多不同的算法,如aes192,aes-128-ecb,aes-256-cbc等,根据不同的密钥长度会使用不同的算法。 加密后的结果有两种表示方法:hex和base64,我们这里使用 hex.

golang

使用 golang 实现 aes 加密,我使用标准库的方法实现,我使用的 CBC 模式。

加密

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func AesEncrypt(encryptStr string, key []byte, iv string) (string, error) {
	encryptBytes := []byte(encryptStr)
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	blockSize := block.BlockSize()
	encryptBytes = pkcs5Padding(encryptBytes, blockSize)

	blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
	encrypted := make([]byte, len(encryptBytes))
	blockMode.CryptBlocks(encrypted, encryptBytes)
	return hex.EncodeToString(encrypted), nil
}

解密

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
func AesDecrypt(decryptStr string, key []byte, iv string) (string, error) {
	decryptBytes, err := hex.DecodeString(decryptStr)
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
	decrypted := make([]byte, len(decryptBytes))

	blockMode.CryptBlocks(decrypted, decryptBytes)
	decrypted = pkcs5UnPadding(decrypted)
	return string(decrypted), nil
}

运行加密解密例子

 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
65
66
67
68
69
70
71
72
package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
)

func AesEncrypt(encryptStr string, key []byte, iv string) (string, error) {
	encryptBytes := []byte(encryptStr)
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	blockSize := block.BlockSize()
	encryptBytes = pkcs5Padding(encryptBytes, blockSize)

	blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
	encrypted := make([]byte, len(encryptBytes))
	blockMode.CryptBlocks(encrypted, encryptBytes)
	return hex.EncodeToString(encrypted), nil
}

func AesDecrypt(decryptStr string, key []byte, iv string) (string, error) {
	decryptBytes, err := hex.DecodeString(decryptStr)
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
	decrypted := make([]byte, len(decryptBytes))

	blockMode.CryptBlocks(decrypted, decryptBytes)
	decrypted = pkcs5UnPadding(decrypted)
	return string(decrypted), nil
}

func pkcs5Padding(cipherText []byte, blockSize int) []byte {
	padding := blockSize - len(cipherText)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(cipherText, padText...)
}

func pkcs5UnPadding(decrypted []byte) []byte {
	length := len(decrypted)
	unPadding := int(decrypted[length-1])
	return decrypted[:(length - unPadding)]
}
func main() {
	data := "i am test data"
	key := []byte("1111111111111111")
	iv := "1111122211111111"
	encrypt, err := AesEncrypt(data, key, iv)
	if err != nil {
		panic(err)
		return
	}
	fmt.Println(encrypt)
	decrypt, err := AesDecrypt(encrypt, key, iv)
	if err != nil {
		panic(err)
	}
	fmt.Println(decrypt)
}

img_1.png

可以看到顺利生成加密后的字符串,加密后的字符串也顺利解密成功。

Node.JS

Node.js 我们同样使用标准库来进行加密解密,crypto模块提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能,但速度会非常慢。Nodejs用C/C++实现这些算法后,通过cypto这个模块暴露为JavaScript接口,这样用起来方便,运行速度也快。

加密

1
2
3
4
5
6
function aesEncode(data, secret,iv) {
    const cipher = crypto.createCipheriv('aes-128-cbc', secret, iv);
    var crypted = cipher.update(data, "binary", "hex");
    crypted += cipher.final('hex');
    return crypted
}

我们根据输入的 data, key,iv 创建 Cipheriv 对象,设置输入的data的格式,输出加密后 hex 编码的字符串。

解密

1
2
3
4
5
6
function aesDecode(data, secret,iv) {
    const cipher = crypto.createDecipheriv('aes-128-cbc', secret, iv);
    var crypted = cipher.update(data, "hex", "binary");
    crypted += cipher.final('binary');
    return crypted
}

我们根据输入的 加密字符串, key,iv 创建 Decipheriv 对象,设置输入的data的格式,输出数据的原始数据。

运行例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var crypto = require("crypto");

function aesEncode(data, secret,iv) {
    const cipher = crypto.createCipheriv('aes-128-cbc', secret, iv);
    var crypted = cipher.update(data, "binary", "hex");
    crypted += cipher.final('hex');
    return crypted
}

function aesDecode(data, secret,iv) {
    const cipher = crypto.createDecipheriv('aes-128-cbc', secret, iv);
    var crypted = cipher.update(data, "hex", "binary");
    crypted += cipher.final('binary');
    return crypted
}

const date_crypto = aesEncode("111", "1234567812345678","1234567812345678")
console.log(date_crypto)
console.log(aesDecode(date_crypto, "1234567812345678","1234567812345678"))

img.png

node go 互相加密解密

接下来我们来简单模拟下 go 和 node 之间的数据传输过程。 统一使用 data = “i am test data” key = “abcdefghabcdefgh” iv = “1234567812345678”

go 加密数据 node 解密

这是使用 go 加密后的数据,我们接下来使用 node解密

1
42961cdaeab0aba366826529fdc36035

img_2.png

可以看到顺利输出了原始数据

node 加密数据 go 解密

接下来我们先使用 node 加密同样的数据,然后使用 go 解密,看看能不能输出原始数据。

可以看到 node 也输出了同样的字符串 42961cdaeab0aba366826529fdc36035,接下来使用 go 解密。

可以看到也顺利还原数据成功。

1
i am test data

小结

本文简单介绍了使用 node 和 go 进行 aes 加密解密。本文的代码放在了这里: https://github.com/overstarry/aes-demo/tree/master

参考