Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "crypto/aes"
- "crypto/cipher"
- "crypto/rand"
- "encoding/base64"
- "flag"
- "fmt"
- "io"
- )
- func main() {
- k := flag.String("key", "", "AES-256 compatible encryption/decryption key")
- t := flag.String("text", "", "The text that should be encrypted/decrypted")
- d := flag.Bool("decrypt", false, "Should I decrypt or encrypt (default)")
- flag.Parse()
- if k == nil || t == nil || d == nil {
- panic("One of the flags is nil")
- }
- key := []byte(*k)
- text := []byte(*t)
- if len(key) < 32 {
- panic("Key too short, needs at least 32 bytes")
- }
- c, err := aes.NewCipher(key)
- if err != nil {
- panic(err)
- }
- gcm, err := cipher.NewGCM(c)
- if err != nil {
- panic(err)
- }
- if *d { // decrypt
- ns := gcm.NonceSize()
- text, err := base64.StdEncoding.DecodeString(*t)
- if err != nil {
- panic(err)
- }
- if len(text) < ns {
- panic("Invalid text, too short for decryption")
- }
- nonce, ciphertext := text[:ns], text[ns:]
- plain, err := gcm.Open(nil, nonce, ciphertext, nil)
- if err != nil {
- panic(err)
- }
- fmt.Println(string(plain))
- } else { // encrypt
- nonce := make([]byte, gcm.NonceSize())
- if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
- panic(err)
- }
- fmt.Println(base64.StdEncoding.EncodeToString(gcm.Seal(nonce, nonce, text, nil)))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement