Skip to content

Instantly share code, notes, and snippets.

@angelodlfrtr
Created August 2, 2022 13:50
Show Gist options
  • Select an option

  • Save angelodlfrtr/4d4213f9a23c5092cb31da777f754605 to your computer and use it in GitHub Desktop.

Select an option

Save angelodlfrtr/4d4213f9a23c5092cb31da777f754605 to your computer and use it in GitHub Desktop.
aesencgo
package main
import (
"bufio"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"flag"
"io"
"io/ioutil"
"os"
)
// main read from stdin, encrypt and output to base64 to STDOUT
func main() {
encrypt := flag.Bool("e", true, "encrypt")
decrypt := flag.Bool("d", false, "decrypt")
key := flag.String("key", "", "key")
flag.Parse()
if !*encrypt && !*decrypt {
panic("must specify either -e or -d")
}
if *encrypt && *decrypt {
panic("cannot encrypt and decrypt at the same time")
}
if len(*key) == 0 {
flag.Usage()
}
// Read data to encrypt from stdin
stdin := bufio.NewReader(os.Stdin)
stdinBuf, err := ioutil.ReadAll(stdin)
if err != nil {
panic(err)
}
if *encrypt {
bufEnc, err := encryptAES(stdinBuf, []byte(*key))
if err != nil {
panic(err)
}
os.Stdout.Write(bufEnc)
}
if *decrypt {
bufClear, err := decryptAES(stdinBuf, []byte(*key))
if err != nil {
panic(err)
}
os.Stdout.Write(bufClear)
}
}
func encryptAES(plaindata []byte, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaindata, nil), nil
}
func decryptAES(cipherdata []byte, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(cipherdata) < nonceSize {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := cipherdata[:nonceSize], cipherdata[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment