无法解密二进制文件

时间:2018-06-23 17:43:17

标签: go encryption public-key-encryption gnupg

我一直在尝试使用GPG公钥和go的docx库对openpgp文件进行加密。它可以加密文档,但是我无法使用私钥对其进行解密。

已经尝试对纯文本文件执行相同的操作,并且解密工作没有任何问题。

我在这里想念什么?

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)
}

1 个答案:

答案 0 :(得分:1)

对不起,慢慢来,看来Encode函数接受FileHints结构,因此通过传递from可以解决问题

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

有关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
}

谢谢。