ex_pic_to_video/crypt.go

88 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
)
func padToLength(s string, length int, padChar rune) string {
if len(s) >= length {
return s
}
// 计算需要填充的字符数
padding := make([]rune, length-len(s))
for i := range padding {
padding[i] = padChar
}
// 将原字符串和填充字符组合起来
return s + string(padding)
}
// 加密函数
func encrypt(key []byte, text string) (string, error) {
plaintext := []byte(text)
// 创建一个新的cipher.Block
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// 创建一个新的GCM模式的加密器
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 创建一个nonce随机数
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
// 加密数据
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
// 返回Base64编码的加密字符串
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// 解密函数
func decrypt(key []byte, encryptedText string) (string, error) {
// 解码Base64字符串
ciphertext, err := base64.StdEncoding.DecodeString(encryptedText)
if err != nil {
return "", err
}
// 创建一个新的cipher.Block
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// 创建一个新的GCM模式的解密器
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 分离nonce和实际加密数据
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return "", errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}