GolangNote

Golang笔记

用golang 实现 CrytoJs.AES 加密解密

Permalink

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

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
51
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)
}

本文网址: https://golangnote.com/topic/280.html 转摘请注明来源

Related articles

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

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

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