Search code examples
goencryptionaes

Encrypt before writing image to disk


Given the following code:

import (
    "image"
    "image/color"
    "image/png"
    "os"
)

var img = image.NewRGBA(image.Rect(0, 0, 100, 100))
var col color.Color

func main() {
    col = color.RGBA{255, 0, 0, 255} // Red
    HLine(10, 20, 80)
    col = color.RGBA{0, 255, 0, 255} // Green
    Rect(10, 10, 80, 50)

    f, err := os.Create("draw.png")
    if err != nil {
        panic(err)
    }
    defer f.Close()
    png.Encode(f, img)
}

How to encrypt the image with AES before it is written to the disk? Unfortunately, png.Encode() is not returning an encoded file but is directly writing the file. If it was returning a file, the approach would be clear to me. But so...I'm stucked.


Solution

  • png.Encode takes an io.Writer, a standard Go interface, and writes into it. So it's not directly writing into a file.

    First step: pass a bytes.Buffer to png.Encode, then you'll have the PNG image encoded as a byte slice in the buffer.

    Second step: use the aes module to encrypt the byte buffer. See the example in the official docs: https://pkg.go.dev/crypto/cipher#example-NewCBCEncrypter or check out this post.