【问题标题】:Unable to decrypt binary file无法解密二进制文件
【发布时间】:2018-12-02 20:35:51
【问题描述】:

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

已经尝试对纯文本文件做同样的事情,并且解密没有任何问题。

我在这里错过了什么?

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

【问题讨论】:

  • 您忽略了错误。更改代码以检查错误。
  • 据我所知,您甚至在读取文件之前就对字节进行了加密。读入字节后,您必须对其进行加密。

标签: go encryption public-key-encryption gnupg


【解决方案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
}

谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多