Skip to content

Instantly share code, notes, and snippets.

@zer0tonin zer0tonin/main.go
Last active Jun 22, 2019

Embed
What would you like to do?
AES-CBC application
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"os"
"github.com/gdamore/encoding"
)
func main() {
// don't hardcode encryption keys in real life pls
key, _ := hex.DecodeString("96744014bfa48166206212b1f8655b66811bf6718a31369c1956a2059d2ba0ba")
if os.Args[1] == "encrypt" {
encrypt(toASCII(os.Args[2]), key)
} else if os.Args[1] == "decrypt" {
iv, _ := hex.DecodeString(os.Args[2])
ciphertext, _ := hex.DecodeString(os.Args[3])
decrypt(iv, ciphertext, key)
}
}
func toASCII(plaintext string) []byte {
encoder := encoding.ASCII.NewEncoder()
result, _ := encoder.Bytes([]byte(plaintext))
return result
}
func encrypt(plaintext, key []byte) {
// generate unique IV
iv := make([]byte, aes.BlockSize)
io.ReadFull(rand.Reader, iv)
//instantiate block cipher
block, _ := aes.NewCipher(key)
mode := cipher.NewCBCEncrypter(block, iv)
// encrypt
ciphertext := make([]byte, len(plaintext))
mode.CryptBlocks(ciphertext, plaintext)
fmt.Printf("iv: %x\n", iv)
fmt.Printf("ciphertext: %x\n", ciphertext)
}
func decrypt(iv, ciphertext, key []byte) {
// instantiate block cipher
block, _ := aes.NewCipher(key)
mode := cipher.NewCBCDecrypter(block, iv)
// decrypt
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
fmt.Printf("plaintext: %s\n", plaintext)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.