我在 golang 中编写了一个快速函数,在写入磁盘之前将我的有效负载加密为 AES256 CBC 字符串。该程序(一旦编译)似乎就是这样做的(正如使用此 site 解密所确认的那样),但是使用此 OpenSSL 命令我得到了最终块长度错误。有人可以帮帮我吗?谢谢!
键:
export AES_KEY=$(python -c 'import uuid;print(uuid.uuid4().hex)')
export AES_IV=$(python -c 'import uuid;print(uuid.uuid4().hex[:16])')
func AesEncrypt(plaintext string) (string, error) {
key := GetEnv("AES_KEY", "")
iv := GetEnv("AES_IV", "")
if key == "" || iv == "" {
return "", errors.New("AES_KEY and AES_IV must be set")
}
bKey := []byte(key)
bIV := []byte(iv)
bPlaintext := PKCS5Padding([]byte(plaintext), aes.BlockSize)
block, err := aes.NewCipher(bKey)
if err != nil {
return "", err
}
ciphertext := make([]byte, len(bPlaintext))
mode := cipher.NewCBCEncrypter(block, bIV)
mode.CryptBlocks(ciphertext, bPlaintext)
return base64.StdEncoding.EncodeToString(ciphertext), nil
// return hex.EncodeToString(ciphertext), nil
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := (blockSize - len(ciphertext)%blockSize)
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func AesDecrypt(ciphertext string) (string, error) {
key := GetEnv("AES_KEY", "")
iv := GetEnv("AES_IV", "")
if key == "" || iv == "" {
return "", errors.New("AES_KEY and AES_IV must be set")
}
bKey := []byte(key)
bIV := []byte(iv)
// base64 decode
cipherTextDecoded, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
// cipherTextDecoded, err := hex.DecodeString(cipherText)
block, err := aes.NewCipher(bKey)
if err != nil {
return "", err
}
mode := cipher.NewCBCDecrypter(block, bIV)
mode.CryptBlocks([]byte(cipherTextDecoded), []byte(cipherTextDecoded))
return string(cipherTextDecoded), nil
}
用于解密的 OpenSSL 命令(使用 go binary 导出文件后):
openssl aes-256-cbc -d -a -v -nosalt \
-K $AES_KEY \
-iv $AES_IV \
-in variables.enc -out variables.dec
结果:
bad decrypt
8503165248:error:06FFF06D:digital envelope routines:CRYPTO_internal:wrong final block length:/AppleInternal/Library/BuildRoots/9e200cfa-7d96-11ed-886f-a23c4f261b56/Library/Caches/com.apple.xbs/Sources/libressl/libressl-3.3/crypto/evp/evp_enc.c:540: