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 时区时差处理方式

个人习惯用 0 时区时间戳记录时间,可以方便转到不同时区,下面介绍 Golang 时区时差处理...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

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

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