To read and write data to encrypted files or streams in Go, you can use the crypto/cipher
package along with the io
package. Here's an example that illustrates how to do it:
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"os"
)
key := make([]byte, 32) // 32 bytes for AES-256
if _, err := rand.Read(key); err != nil {
panic(err)
}
iv := make([]byte, aes.BlockSize)
if _, err := rand.Read(iv); err != nil {
panic(err)
}
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
file, err := os.Open("path/to/file")
if err != nil {
panic(err)
}
defer file.Close()
cipherWriter := cipher.StreamWriter{
S: cipher.NewCTR(block, iv),
W: file,
}
Now you can write encrypted data to the file using the cipherWriter.Write()
method.
cipherReader := &cipher.StreamReader{
S: cipher.NewCTR(block, iv),
R: file,
}
Now you can read the encrypted data from the file using the cipherReader.Read()
method.
Note that you might need to handle the file I/O operations and error handling appropriately as per your requirement.
This example demonstrates how to read and write data to an encrypted file using the AES encryption algorithm in Golang. You can extend this approach to streams or other encryption algorithms as needed.