To encrypt and decrypt files in Go, you can use the Golang crypto/aes
package. Here's an example of how you can encrypt and decrypt files using AES encryption:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
"io/ioutil"
"os"
)
// EncryptFile encrypts a file with AES encryption algorithm
func EncryptFile(key []byte, inputFile, outputFile string) error {
// Read the input file
plaintext, err := ioutil.ReadFile(inputFile)
if err != nil {
return err
}
// Generate a new AES cipher block from the provided key
block, err := aes.NewCipher(key)
if err != nil {
return err
}
// Generate a new random IV (initialization vector)
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return err
}
// Create a new AES-GCM cipher with the generated key and IV
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return err
}
// Encrypt the plaintext using AES-GCM and append the IV to the ciphertext
ciphertext := aesgcm.Seal(nil, iv, plaintext, nil)
ciphertext = append(iv, ciphertext...)
// Write the ciphertext to the output file
return ioutil.WriteFile(outputFile, ciphertext, 0644)
}
// DecryptFile decrypts a file encrypted with AES encryption algorithm
func DecryptFile(key []byte, inputFile, outputFile string) error {
// Read the input file
ciphertext, err := ioutil.ReadFile(inputFile)
if err != nil {
return err
}
// Generate a new AES cipher block from the provided key
block, err := aes.NewCipher(key)
if err != nil {
return err
}
// Check if the ciphertext length is valid
if len(ciphertext) < aes.BlockSize {
return errors.New("invalid ciphertext")
}
// Extract the IV from the beginning of the ciphertext
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
// Create a new AES-GCM cipher with the generated key and IV
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return err
}
// Decrypt the ciphertext using AES-GCM
plaintext, err := aesgcm.Open(nil, iv, ciphertext, nil)
if err != nil {
return err
}
// Write the decrypted plaintext to the output file
return ioutil.WriteFile(outputFile, plaintext, 0644)
}
func main() {
key := []byte("16-byte secret key") // Change this to your own secret key
inputFile := "input.txt"
encryptedFile := "encrypted.txt"
decryptedFile := "decrypted.txt"
err := EncryptFile(key, inputFile, encryptedFile)
if err != nil {
panic(err)
}
println("File encrypted successfully.")
err = DecryptFile(key, encryptedFile, decryptedFile)
if err != nil {
panic(err)
}
println("File decrypted successfully.")
}
In this example, change the key
variable to your own 16-byte secret key. Then, run the program to encrypt and decrypt the input.txt
file. The encrypted file will be saved as encrypted.txt
, and the decrypted file will be saved as decrypted.txt
.