首頁 > 後端開發 > Golang > 主體

使用 cipher.AEAD.Seal() 查看記憶體使用情況

WBOY
發布: 2024-02-06 10:03:03
轉載
963 人瀏覽過

使用 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 MiB\n", 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 MiB\n", 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
登入後複製

以上是使用 cipher.AEAD.Seal() 查看記憶體使用情況的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!