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): %sn", ciphertext) decrypted, err := decryptECB(ciphertext, key) if err != nil { log.Fatal(err) } fmt.Printf("Decrypted: %sn", 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)至關重要。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END