package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func main() {
key := []byte("0123456789abcdef")
plaintext := []byte("hello world.....hello world.....hello world.....")
fmt.Printf("plaintext: %v\n", string(plaintext))
aes_basic(key, plaintext)
aes_cbc(key, plaintext)
plaintext = []byte("hello world.....hello world.....hello worl")
fmt.Printf("plaintext: %v\n", string(plaintext))
aes_ctr(key, plaintext)
}
func aes_basic(key []byte, plaintext []byte) {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println("Error creating AES cipher block:", err)
return
}
if len(plaintext)%aes.BlockSize != 0 {
fmt.Println("Plaintext length must be a multiple of the block size")
return
}
ciphertext := make([]byte, len(plaintext))
for offset := 0; offset < len(plaintext); offset += aes.BlockSize {
block.Encrypt(ciphertext[offset:offset+aes.BlockSize], plaintext[offset:offset+aes.BlockSize])
}
fmt.Printf("ECB encrypted: %x\n", ciphertext)
}
func aes_cbc(key []byte, plaintext []byte) {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println("Error creating AES cipher block:", err)
return
}
if len(plaintext)%aes.BlockSize != 0 {
fmt.Println("Plaintext length must be a multiple of the block size")
return
}
encrypted := make([]byte, len(plaintext))
iv := make([]byte, aes.BlockSize)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(encrypted, plaintext)
fmt.Printf("CBC encrypted: %x\n", encrypted)
}
func aes_ctr(key []byte, plaintext []byte) {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println("Error creating AES cipher:", err)
return
}
iv := make([]byte, 16)
stream := cipher.NewCTR(block, iv)
encrypted := make([]byte, len(plaintext))
stream.XORKeyStream(encrypted, plaintext)
fmt.Printf("CTR encrypted: %x\n", encrypted)
}