https://cyberspy.io/articles/crypto101/
加密:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.
key := []byte("0123456789ABCDEF")
plaintext := []byte("Apple")
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
nonce := make([]byte, 12)
if false {
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
}
fmt.Printf("nonce: %x\n", nonce)
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Printf("cipher:%x\n", ciphertext)
}
解密:
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"encoding/hex"
)
func main (){
key := []byte("0123456789ABCDEF")
ciphertext, _ := hex.DecodeString("08f24c28f0fc9aef5812a35ce66235bc2488d6c29b") //加密生成的結(jié)果
nonce, _ := hex.DecodeString("000000000000000000000000") //加密用的nonce
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
fmt.Println(string(plaintext))
}
跟蹤 tls(https) 代碼里面空执, server 和client 走的 就是 aes GCM奶栖。
nonce 應(yīng)該就是隨機(jī)數(shù)(random)