2 回答

TA貢獻1843條經驗 獲得超7個贊
您希望加密流如下所示:
func encrypt(in []byte, key []byte) (out []byte, err error) {
c, err := aes.NewCipher(key)
if err != nil {
return
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return
}
out = gcm.Seal(nonce, nonce, in, nil) // include the nonce in the preable of 'out'
return
}
根據 aes,您的輸入長度應為 16、24 或 32 個字節。新密碼文檔。key
上述函數中的加密字節將包括前綴(長度為 16、24 或 32 個字節) - 因此可以在解密階段輕松提取,如下所示:outnonce
// `in` here is ciphertext
nonce, ciphertext := in[:ns], in[ns:]
其中計算如下:ns
c, err := aes.NewCipher(key)
if err != nil {
return
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return
}
ns := gcm.NonceSize()
if len(in) < ns {
err = fmt.Errorf("missing nonce - input shorter than %d bytes", ns)
return
}
編輯:
如果您使用默認密碼設置進行加密(見上文):go
gcm, err := cipher.NewGCM(c)
從源中,標記字節大小將為 。16
注意:如果是密碼。使用新GCM標簽大小 - 然后大小顯然會有所不同(基本上在字節之間的任何地方)12
16
因此,讓我們假設標簽大小為 ,掌握此知識,并且知道完整的有效負載安排是:16
IV/nonce + raw_ciphertext + auth_tag
解密的一側是有效載荷的最后16個字節;并且raw_ciphertext是 up 之后的所有字節,直到 開始的位置。auth_tag
Ruby
IV/nonce
auth_tag

TA貢獻1809條經驗 獲得超8個贊
aesgcm.Seal自動將 GCM 標記附加到密文的末尾。您可以在源代碼中看到它:
var tag [gcmTagSize]byte
g.auth(tag[:], out[:len(plaintext)], data, &tagMask)
copy(out[len(plaintext):], tag[:]) // <---------------- here
所以你已經完成了,你不需要其他任何東西。 已返回末尾附加了 auth 標記的密文。gcm.Seal
同樣,您也不需要提取 的 auth 標記,它也會自動執行此操作:gcm.Open
tag := ciphertext[len(ciphertext)-g.tagSize:] // <---------------- here
ciphertext = ciphertext[:len(ciphertext)-g.tagSize]
因此,在解密過程中,您所要做的就是提取IV(nonce)并將其余部分作為密文傳遞。
- 2 回答
- 0 關注
- 173 瀏覽
添加回答
舉報