卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34158本站已运行391

使用 cipher.AEAD.Seal() 查看内存使用情况

使用 cipher.aead.seal() 查看内存使用情况

问题内容

我正在使用 Go 的 ChaCha20-Poly1305 实现来加密数据,但是当我加密一些大文件时,内存使用量高于我的预期。据我所知,Go 的 AEAD 密码实现意味着我们必须将整个数据保存在内存中才能创建哈希,但内存使用量是明文大小的两倍。

以下尝试加密 4 GiB 数据的小程序突出显示了这一点(在现实世界的程序中,keynonce 不应为空):

package main

import (
  "os"
  "fmt"
  "runtime"
  "golang.org/x/crypto/chacha20poly1305"
)

func main() {
  showMemUsage("START")

  plaintext := make([]byte, 4 * 1024 * 1024 * 1024) // 4 GiB

  showMemUsage("STAGE 1")

  key := make([]byte, chacha20poly1305.KeySize)
  if cipher, err := chacha20poly1305.New(key); err == nil {
    showMemUsage("STAGE 2")

    nonce := make([]byte, chacha20poly1305.NonceSize)
    cipher.Seal(plaintext[:0], nonce, plaintext, nil)
  }

  showMemUsage("END")
}

func showMemUsage(tag string) {
  var m runtime.MemStats

  runtime.ReadMemStats(&m)
  fmt.Fprintf(os.Stdout, "[%s] Alloc = %v MiB, TotalAlloc = %v MiBn", tag, m.Alloc / 1024 / 1024, m.TotalAlloc / 1024 / 1024)
}

根据crypto/cipher/gcm.go的源代码(AES-GCM和ChaCha20-Poly1305都使用)有以下注释:

// To reuse plaintext's storage for the encrypted output, use plaintext[:0]
// as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
Seal(dst, nonce, plaintext, additionalData []byte) []byte

这意味着我应该能够重新使用内存,我已经尝试这样做,但这对我的应用程序使用的内存量没有影响 - 在调用 Seal() 之后我们总是最终使用8 GiB 内存可以加密 4 GiB 数据?

[START] Alloc = 0 MiB, TotalAlloc = 0 MiB
[STAGE 1] Alloc = 4096 MiB, TotalAlloc = 4096 MiB
[STAGE 2] Alloc = 4096 MiB, TotalAlloc = 4096 MiB
[END] Alloc = 8192 MiB, TotalAlloc = 8192 MiB

如果它重复使用内存(如暗示的那样),那么除了 AEAD 密码向密文添加相对较小的哈希值之外,我不应该期望任何大幅增加?


正确答案


您忘记考虑附加到密文的身份验证标记。如果您在初始分配中为其腾出空间,则无需进一步分配:

package main

import (
        "fmt"
        "os"
        "runtime"

        "golang.org/x/crypto/chacha20poly1305"
)

func main() {
        showMemUsage("START")

        plaintext := make([]byte, 4<<30, 4<<30+chacha20poly1305.Overhead)

        showMemUsage("STAGE 1")

        key := make([]byte, chacha20poly1305.KeySize)
        if cipher, err := chacha20poly1305.New(key); err == nil {
                showMemUsage("STAGE 2")

                nonce := make([]byte, chacha20poly1305.NonceSize)
                cipher.Seal(plaintext[:0], nonce, plaintext, nil)
        }

        showMemUsage("END")
}

func showMemUsage(tag string) {
        var m runtime.MemStats

        runtime.ReadMemStats(&m)
        fmt.Fprintf(os.Stdout, "[%s] Alloc = %v MiB, TotalAlloc = %v MiBn", tag, m.Alloc>>20, m.TotalAlloc>>20)
}

// Output:
// [START] Alloc = 0 MiB, TotalAlloc = 0 MiB
// [STAGE 1] Alloc = 4096 MiB, TotalAlloc = 4096 MiB
// [STAGE 2] Alloc = 4096 MiB, TotalAlloc = 4096 MiB
// [END] Alloc = 4096 MiB, TotalAlloc = 4096 MiB
卓越飞翔博客
上一篇: 客户端范围不足 - Spotify API Golang
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏