Created
March 7, 2021 11:56
-
-
Save andrew-wilkes/bf6f6e8855339cbd12e35c64bedd49c1 to your computer and use it in GitHub Desktop.
File encryption using go
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" | |
"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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is based off https://gist.github.com/josephspurrier/12cc5ed76d2228a41ceb