1 回答
TA贡献1805条经验 获得超9个赞
下面是一个例子:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
)
func main() {
key := []byte("xxxxxxxxxxxxxxxx") // 32 bytes
plaintext := []byte("TEST")
fmt.Printf("%s\n", plaintext)
ciphertext, err := encrypt(key, plaintext)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%0x\n", ciphertext)
result, err := decrypt(key, ciphertext)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", result)
}
func encrypt(key, text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
b := base64.StdEncoding.EncodeToString(text)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
return ciphertext, nil
}
func decrypt(key, text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(text) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := text[:aes.BlockSize]
text = text[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(text, text)
data, err := base64.StdEncoding.DecodeString(string(text))
if err != nil {
return nil, err
}
return data, nil
}
主要借鉴和改编自:https : //golang.org/src/crypto/cipher/example_test.go
// Input => TEST
// Output => 13360adba03733e11dd2702de441ff8bbb90676ad762fc83
更新
要将字符串用作decode函数的参数,您需要将字符串转换为byteusinghex.Decodestring
data, _ := hex.DecodeString("1d6f12d3aa2353b23c6012dbc85816632129363d58a76063")
result, err := decrypt(key, data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", result)
不要忘记包含"encoding/hex"在包列表中。
- 1 回答
- 0 关注
- 226 浏览
添加回答
举报