
寻求 go 中的 aes 加密方法
问题描述
需要在 go 中使用 aes 加密算法,具体要求如下:
解决方案
以下代码段提供了 go 中符合指定要求的 aes 加密方法:
package main
import (
"crypto/aes"
"encoding/base64"
"log"
)
func AesEncryptECB(origData []byte, key []byte) string {
cipher, _ := aes.NewCipher(generateKey(key))
length := (len(origData) + aes.BlockSize) / aes.BlockSize
plain := make([]byte, length*aes.BlockSize)
copy(plain, origData)
encrypted := make([]byte, len(plain))
// Block encryption
for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
}
return base64.StdEncoding.EncodeToString(encrypted)
}
func AesDecryptECB(str string, key []byte) (decrypted []byte) {
encrypted, _ := base64.StdEncoding.DecodeString(str)
cipher, _ := aes.NewCipher(generateKey(key))
decrypted = make([]byte, len(encrypted))
for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
}
trim := 0
if len(decrypted) > 0 {
trim = len(decrypted) - int(decrypted[len(decrypted)-1])
}
return decrypted[:trim]
}
func generateKey(key []byte) (genKey []byte) {
genKey = make([]byte, 16)
copy(genKey, key)
for i := 16; i < len(key); {
for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
genKey[j] ^= key[i]
}
}
return genKey
}
func main() {
origin := []byte("406BF0AD11310101220213481000320000")
key := []byte("ER2Fb6ts3ECX")
encrypted := AesEncryptECB(origin, key)
log.Println("encrypted: ", encrypted)
decrypted := AesDecryptECB(encrypted, key)
log.Println("decrypted: ", string(decrypted))
}此代码使用 ecb(电子密码本)模式,不进行填充。它提供了所需的加密和解密功能,可用于您的应用程序中。
以上就是如何在 Go 中实现无填充的 AES-ECB 加密?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号