使用AES加密了一个文件,但无法使用OpenSSL解密它(坏的魔数)。

huangapple go评论86阅读模式
英文:

Encrypted a file with AES but can't decrypt it with OpenSSL (bad magic number)

问题

我已经使用以下代码对文件进行了加密:

block, err := aes.NewCipher([]byte("TESTPASSWORD1234TESTPASSWORD1234"))
if err != nil {
    panic(err)
}

bReader, err := os.Open("doc.docx")
if err != nil {
    panic(err)
}

var iv [aes.BlockSize]byte
stream := cipher.NewOFB(block, iv[:])

var out bytes.Buffer

writer := &cipher.StreamWriter{S: stream, W: &out}
if _, err := io.Copy(writer, bReader); err != nil {
    panic(err)
}

if os.WriteFile("doc-encrypted.docx", out.Bytes(), 0644) != nil {
    panic(err)
}

当我尝试使用以下命令解密时:

openssl enc -in doc-encrypted.docx -out doc-decryted.docx -d -aes-256-ofb

它显示错误信息bad magic number

英文:

I have encrypted a file using this code.

	block, err := aes.NewCipher([]byte("TESTPASSWORD1234TESTPASSWORD1234"))
	if err != nil {
		panic(err)
	}

	bReader, err := os.Open("doc.docx")
	if err != nil {
		panic(err)
	}

	var iv [aes.BlockSize]byte
	stream := cipher.NewOFB(block, iv[:])

	var out bytes.Buffer

	writer := &cipher.StreamWriter{S: stream, W: &out}
	if _, err := io.Copy(writer, bReader); err != nil {
		panic(err)
	}

	if os.WriteFile("doc-encrypted.docx", out.Bytes(), 0644) != nil {
		panic(err)
	}

and when I try to decrypt it using this command

openssl enc -in doc-encrypted.docx -out doc-decryted.docx -d -aes-256-ofb

it gives the error bad magic number

答案1

得分: 1

您的OpenSSL语句缺少密钥和初始化向量(IV)的规范。为了解密,需要使用以下OpenSSL语句:

openssl enc -in doc-encrypted.docx -out doc-decryted.docx -d -aes-256-ofb -K 5445535450415353574f5244313233345445535450415353574f524431323334 -iv 00000000000000000000000000000000

-K选项指定十六进制编码的密钥,-iv指定十六进制编码的IV,参见enc

通过这个更改,使用Go代码生成的密文可以使用OpenSSL语句进行解密。

请记住,使用静态IV是不安全的。通常,每次加密都会生成一个随机IV。这个IV不是秘密的,并且通常与密文连接在一起:iv|ciphertext,以便在解密过程中使用。请参阅NewOFB的文档示例(不包含文件I/O)。

英文:

Your OpenSSL statement is missing the specification of key and IV. For decryption, the following OpenSSL statement is required:

openssl enc -in doc-encrypted.docx -out doc-decryted.docx -d -aes-256-ofb -K 5445535450415353574f5244313233345445535450415353574f524431323334 -iv 00000000000000000000000000000000

The -K option specifies the hex encoded key, and -iv specifies the hex encoded IV, s. enc.

With this change, the ciphertext generated with the Go code can be decrypted with the OpenSSL statement.


Keep in mind that the use of a static IV is insecure. Typically, a random IV is generated for each encryption. This is not secret and is usually concatenated with the ciphertext: iv|ciphertext so that it is available during decryption. See the documentation for NewOFB for an example (without file I/O).

huangapple
  • 本文由 发表于 2022年8月10日 13:23:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/73300984.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定