Last active
September 13, 2022 01:37
-
-
Save zer0tonin/9bce5ff763132594880dc251a68ae735 to your computer and use it in GitHub Desktop.
AES-CBC application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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