Skip to content

Instantly share code, notes, and snippets.

@zer0tonin
Last active September 13, 2022 01:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zer0tonin/9bce5ff763132594880dc251a68ae735 to your computer and use it in GitHub Desktop.
Save zer0tonin/9bce5ff763132594880dc251a68ae735 to your computer and use it in GitHub Desktop.
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