Golang加密:加密文件没有带有IV前缀。

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

Golang crypto: encrypted file not prefixed with IV

问题

我正在使用cipher.NewOFB中的IV,但我的加密文件从未以其为前缀。我按照golang官方文档上的示例(https://golang.org/pkg/crypto/cipher/)进行操作,但似乎无法弄清楚为什么前缀没有被考虑进去。

有人能看出问题在哪里吗?

func generateRandomIV(length int) []byte {
    iv := make([]byte, aes.BlockSize)

    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    return iv
}


func encryptFile(filename, keystring string) error {
    readFile, err := os.Open(filename)
    iv := generateRandomIV(aes.BlockSize)

    outFile, err := os.OpenFile(filename+".enc", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    if err != nil {
        panic(err)
    }

    defer readFile.Close()
    defer outFile.Close()

    key := []byte(keystring)

    block, err := aes.NewCipher(key)

    if err != nil {
        panic(err)
    }

    fmt.Println("IV:", iv)
    writer := &cipher.StreamWriter{S: cipher.NewOFB(block, iv), W: outFile}

    if _, err := io.Copy(writer, readFile); err != nil {
        return err
    }

    return nil
}
英文:

I am using an IV in cipher.NewOFB, but my encrypted file never gets prefixed with it. I followed the golang examples at https://golang.org/pkg/crypto/cipher/, but can't seem to figure out why the prefix isn't being considered.

Does anyone see what the problem is?

func generateRandomIV(length int) []byte {
	iv := make([]byte, aes.BlockSize)

	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}

	return iv
}


func encryptFile(filename, keystring string) error {
	readFile, err := os.Open(filename)
	iv := generateRandomIV(aes.BlockSize)

	outFile, err := os.OpenFile(filename+".enc", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		panic(err)
	}

	defer readFile.Close()
	defer outFile.Close()

	key := []byte(keystring)

	block, err := aes.NewCipher(key)

	if err != nil {
		panic(err)
	}

	fmt.Println("IV:", iv)
	writer := &cipher.StreamWriter{S: cipher.NewOFB(block, iv), W: outFile}

	if _, err := io.Copy(writer, readFile); err != nil {
		return err
	}

	return nil
}

答案1

得分: 2

将IV前缀添加到密文中,或者预先共享IV。如果你添加了前缀,解密时需要将其移除并应用。

如何共享IV不是加密标准的一部分,而是开发者的选择。在密文中添加前缀是常见的做法,但并非必需或唯一的方式,不过这是一个不错的选择。

英文:

Add the IV prefix yourself or pre-share the IV. If you prefix it you will have the remove it and apply it on decryption.

How an IV is shared is not part of the encryption standard, it is a developer choice. Prefixing the IV is common but not required or the only way, it is however a good choice.

huangapple
  • 本文由 发表于 2016年9月1日 05:34:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/39259363.html
匿名

发表评论

匿名网友

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

确定