Skip to content

Instantly share code, notes, and snippets.

@andrew-wilkes
Created March 7, 2021 12:00
Show Gist options
  • Save andrew-wilkes/3ffdc7d6157ffee6a7683d8f2bd6aee2 to your computer and use it in GitHub Desktop.
Save andrew-wilkes/3ffdc7d6157ffee6a7683d8f2bd6aee2 to your computer and use it in GitHub Desktop.
File decryption using go
package main
# This decrypts a file that was encrypted with encryptor where the file name was appended with .enc
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"io/ioutil"
"os"
"strings"
)
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 {
plaintext := decrypt(data, key)
writeToFile(plaintext, strings.Replace(fn, ".enc", "", 1))
}
}
func decrypt(ciphertext []byte, keystring string) string {
// Key
key := []byte(keystring)
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// Before even testing the decryption,
// if the text is too small, then it is incorrect
if len(ciphertext) < aes.BlockSize {
panic("Text is too short")
}
// Get the 16 byte IV
iv := ciphertext[:aes.BlockSize]
// Remove the IV from the ciphertext
ciphertext = ciphertext[aes.BlockSize:]
// Return a decrypted stream
stream := cipher.NewCFBDecrypter(block, iv)
// Decrypt bytes from ciphertext
stream.XORKeyStream(ciphertext, ciphertext)
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