Skip to content

Instantly share code, notes, and snippets.

@andrew-wilkes
Created March 7, 2021 11:56
Show Gist options
  • Save andrew-wilkes/bf6f6e8855339cbd12e35c64bedd49c1 to your computer and use it in GitHub Desktop.
Save andrew-wilkes/bf6f6e8855339cbd12e35c64bedd49c1 to your computer and use it in GitHub Desktop.
File encryption using go
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
args := os.Args[1:]
if len(args) != 2 {
panic("Missing arguments for filename and key")
}
fn := args[0]
key := args[1]
if data, err := readFromFile(fn); err != nil {
fmt.Println("File not found")
} else {
enctext := encrypt(data, key)
writeToFile(enctext, fn+".enc")
}
}
func encrypt(plaintext []byte, keystring string) string {
// Key (16/24/32 bytes)
key := []byte(keystring)
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// Empty array of 16 + plaintext length
// Include the IV at the beginning
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
// Slice of first 16 bytes
iv := ciphertext[:aes.BlockSize]
// Write 16 rand bytes to fill iv
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
// Return an encrypted stream
stream := cipher.NewCFBEncrypter(block, iv)
// Encrypt bytes from plaintext to ciphertext
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return string(ciphertext)
}
func writeToFile(data, file string) {
ioutil.WriteFile(file, []byte(data), 777)
}
func readFromFile(file string) ([]byte, error) {
data, err := ioutil.ReadFile(file)
return data, err
}
@andrew-wilkes
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment