GolangNote

Golang笔记

用golang 实现 CrytoJs.AES 加密解密

Permalink

crypto-js 库 AES 加密解密的 go 实现

用golang 实现 CrytoJs.AES 加密解密

JavaScript: CrytoJs.AES 加密解密
1
2
3
4
5
6
7
8
9
10
11
12
13
var CryptoJS = require("crypto-js");
 
var data = [{id: 1}, {id: 2}]
 
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123').toString();
 
// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
 
console.log(decryptedData); // [{id: 1}, {id: 2}]

golang 实现

Go: crypto/aes
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
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
	"io"
)

func encrypt(key []byte, text []byte) []byte {
	c, _ := aes.NewCipher(key)
	gcm, _ := cipher.NewGCM(c)

	nonce := make([]byte, gcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		panic(err.Error())
	}

	result := gcm.Seal(nonce, nonce, text, nil)

	return result
}

func decrypt(key []byte, ciphertext []byte) string {
	c, _ := aes.NewCipher(key)
	gcm, _ := cipher.NewGCM(c)

	nonceSize := gcm.NonceSize()
	if len(ciphertext) < nonceSize {
		panic("ciphertext size is less than nonceSize")
	}

	var nonce []byte
	nonce, ciphertext = ciphertext[:nonceSize], ciphertext[nonceSize:]
	plaintext, _ := gcm.Open(nil, nonce, ciphertext, nil)

	return string(plaintext)
}

func main() {
	text := []byte("待加密的字符串")

	key := []byte("T+U2YMDrIz2G+fsasSZ+mQ==")

	secret := encrypt(key, text)
	plainString := decrypt(key, secret)

	fmt.Println(plainString, string(text) == plainString)
}

Related articles

golang rot13 简单加密字符

ROT13 是一种简单的字符加密方法,把 26 个英文字母的前 13 个字母与后 13 个字母的编码互换。...

Write a Comment to "用golang 实现 CrytoJs.AES 加密解密"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.3 Processed in 0ms