我试图在存储敏感数据之前对其进行加密。首先,我生成一个用于加密过程的密钥:
import (
"crypto/aes"
CR "crypto/rand"
"encoding/hex"
"errors"
"log"
"os"
)
// []byte key used to encrypt tokens before saving to local file system
var key = make([]byte, 32)
func createKey(key *[]byte) {
_, err = CR.Read(*key)
if err != nil {
log.Println("Error creating key from crypto/rand package:", err)
}
}
接下来我创建分别加密和解密字符串的函数:
func encryptToken(t token) string {
original := t.ID // ID is string member of token
cipher, err := aes.NewCipher(key)
if err != nil {
log.Println("Error creating cipher during encrypt:", err)
}
out := make([]byte, len(original))
cipher.Encrypt(out, []byte(original))
return hex.EncodeToString(out) // this will be written to a csv file
// appears in file as: cec35df876e1b77diefg9023366c5f2f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
}
func decryptToken(s string) string {
ciphertext, err := hex.DecodeString(s) // s is read from csv file
if err != nil {
log.Println("Error decoding string from hex:", err)
}
cipher, err := aes.NewCipher(key)
if err != nil {
log.Println("Error creating cipher during decrypt:", err)
}
original := make([]byte, len(ciphertext))
cipher.Decrypt(original, ciphertext)
originalAsString := string(original[:])
return originalAsString // returns: 6f928e728f485403
// original token was: 6f928e728f485403e254049f684ea5ec853adcfa9553cdfc956fr45671447c57
}
考虑到encryptToken()返回一个包含这么多零的十六进制字符串,我确定这就是我的问题所在。我试过调整 的长度key,但使用 32 以外的值var key = make([]byte, 32)将导致涉及无效内存地址或 nil 指针取消引用的恐慌。为什么是这样?
白板的微信
UYOU
至尊宝的传说
相关分类