Skip to content

Instantly share code, notes, and snippets.

@adamenger
Created January 28, 2022 16:27
Show Gist options
  • Save adamenger/c1acc4a43d52bc2d6b0d38b9ec3b8d62 to your computer and use it in GitHub Desktop.
Save adamenger/c1acc4a43d52bc2d6b0d38b9ec3b8d62 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"github.com/urfave/cli/v2"
"io"
"io/ioutil"
"log"
"os"
)
func GenerateKey() []byte {
token := make([]byte, 16)
rand.Read(token)
return token
}
func EncryptFile(c *cli.Context) error {
key := GenerateKey()
fmt.Println(string(key))
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
// Create file to encrypt
filename := fmt.Sprintf("%s/Desktop/%s", homeDir, c.String("filename"))
dat, err := os.ReadFile(filename)
if err != nil {
return err
}
block, err := aes.NewCipher(key)
if err != nil {
return err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return err
}
ciphertext := gcm.Seal(nonce, nonce, dat, nil)
// Save back to file
encryptedFilePath := fmt.Sprintf("%s.bin", filename)
err = ioutil.WriteFile(encryptedFilePath, ciphertext, 0777)
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment