Search code examples
goencryptionpublic-key-encryptiongnupg

Unable to decrypt binary file


I've been trying to encrypt docx file using GPG public key and go's openpgp library. It encrypts document but then I am unable to decrypt it using my private key.

Already tried to do the same with plain text file and decryption worked without any problems.

What am I missing here?

package main

import (
    "golang.org/x/crypto/openpgp"
    "bytes"
    "io/ioutil"
    "fmt"
    "os"
)

func main() {
    entitylist, _ := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(...))

    buf := new(bytes.Buffer)
    w, _ := openpgp.Encrypt(buf, entitylist, nil, nil, nil)
    b, _ := ioutil.ReadFile("in.docx")

    w.Write(b)
    w.Close()

    bts, _ := ioutil.ReadAll(buf)
    ioutil.WriteFile("out.gpg", bts, os.ModePerm)
}

Solution

  • Sorry guys to take your time it appears that Encode function accepts FileHints struct so passing with binary from solves the problem

    w, _ := openpgp.Encrypt(buf, entitylist, nil, &openpgp.FileHints{IsBinary: true}, nil)
    

    More details on FileHints

    // FileHints contains metadata about encrypted files. This metadata is, itself,
    // encrypted.
    type FileHints struct {
        // IsBinary can be set to hint that the contents are binary data.
        IsBinary bool
        // FileName hints at the name of the file that should be written. It's
        // truncated to 255 bytes if longer. It may be empty to suggest that the
        // file should not be written to disk. It may be equal to "_CONSOLE" to
        // suggest the data should not be written to disk.
        FileName string
        // ModTime contains the modification time of the file, or the zero time if not applicable.
        ModTime time.Time
    }
    

    Thanks.