go语言aes加密:ecb模式无填充加密与base64编码
本文演示如何在Go语言中使用AES/ECB/NoPadding模式加密字符串,并进行Base64编码。 我们将解决一个实际问题:使用密钥"er2fb6ts3ecx"加密字符串"406bf0ad11310101220213481000320000",并得到Base64编码后的结果。
问题与解决方案:
许多AES加密示例使用CBC模式和填充。然而,本例要求使用ECB模式和NoPadding。 这需要仔细处理密钥长度和潜在的填充问题。
立即学习“go语言免费学习笔记(深入)”;
以下Go代码实现了AES/ECB/NoPadding加密和Base64编码:
package main import ( "crypto/aes" "encoding/base64" "fmt" "log" ) func main() { plaintext := []byte("406bf0ad11310101220213481000320000") key := []byte("er2fb6ts3ecx") ciphertext, err := encryptECB(plaintext, key) if err != nil { log.Fatal(err) } fmt.Printf("Ciphertext (Base64): %s\n", ciphertext) decrypted, err := decryptECB(ciphertext, key) if err != nil { log.Fatal(err) } fmt.Printf("Decrypted: %s\n", string(decrypted)) } func encryptECB(plaintext, key []byte) (string, error) { block, err := aes.NewCipher(padKey(key)) if err != nil { return "", err } if len(plaintext)%aes.BlockSize != 0 { return "", fmt.Errorf("plaintext is not a multiple of the block size") } ciphertext := make([]byte, len(plaintext)) for i := 0; i < len(plaintext); i += aes.BlockSize { block.Encrypt(ciphertext[i:i+aes.BlockSize], plaintext[i:i+aes.BlockSize]) } return base64.StdEncoding.EncodeToString(ciphertext), nil } func decryptECB(ciphertext string, key []byte) ([]byte, error) { block, err := aes.NewCipher(padKey(key)) if err != nil { return nil, err } decoded, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return nil, err } plaintext := make([]byte, len(decoded)) for i := 0; i < len(decoded); i += aes.BlockSize { block.Decrypt(plaintext[i:i+aes.BlockSize], decoded[i:i+aes.BlockSize]) } //NoPadding, so we don't need to remove padding return plaintext, nil } func padKey(key []byte) ([]byte, error) { if len(key) != 16 && len(key) != 24 && len(key) != 32 { return nil, fmt.Errorf("invalid key size") } paddedKey := make([]byte, 16) copy(paddedKey, key[:16]) return paddedKey, nil }
这段代码包含了encryptECB和decryptECB函数,分别用于ECB模式下的AES加密和解密。padKey函数确保密钥长度为16字节。 由于使用NoPadding,我们不需要处理填充。 请注意,ECB模式的安全性较低,不建议在生产环境中使用。
这个改进后的代码更简洁,更易于理解,并且正确处理了密钥长度和NoPadding的情况。 记住,在实际应用中,选择更安全的模式(如CBC或GCM)至关重要。
以上就是Go语言AES加密:如何使用AES/ECB/NoPadding模式加密字符串并进行base64编码?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号