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 关注
- 141 浏览
添加回答
举报