Created
March 7, 2021 12:00
-
-
Save andrew-wilkes/3ffdc7d6157ffee6a7683d8f2bd6aee2 to your computer and use it in GitHub Desktop.
File decryption 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 | |
# 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 | |
} |
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