GO语言"crypto/cipher"包中"NewGCM"函数的用法及代码示例。
用法:
func NewGCM(cipher Block)(AEAD, error)
NewGCM 返回给定的 128 位分组密码,以标准随机数长度包装在伽罗瓦计数器模式中。
一般来说,这种 GCM 实现执行的 GHASH 操作不是constant-time。一个例外是当底层块由 aes NewCipher 在硬件支持 AES 的系统上创建时。有关详细信息,请参阅 crypto/aes 包文档。
示例(解密):
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
)
func main() {
// Load your secret key from a safe place and reuse it across multiple
// Seal/Open calls. (Obviously don't use this example key for anything
// real.) If you want to convert a passphrase to a key, use a suitable
// package like bcrypt or scrypt.
// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
ciphertext, _ := hex.DecodeString("c3aaa29f002ca75870806e44086700f62ce4d43e902b3888e23ceff797a7a471")
nonce, _ := hex.DecodeString("64a9433eae7ccceee2fc0eda")
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
fmt.Printf("%s\n", plaintext)
}
输出:
exampleplaintext
示例(加密):
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
func main() {
// Load your secret key from a safe place and reuse it across multiple
// Seal/Open calls. (Obviously don't use this example key for anything
// real.) If you want to convert a passphrase to a key, use a suitable
// package like bcrypt or scrypt.
// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
plaintext := []byte("exampleplaintext")
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Printf("%x\n", ciphertext)
}
相关用法
- GO NewFromFiles用法及代码示例
- GO NewReader用法及代码示例
- GO NewCBCDecrypter用法及代码示例
- GO NewCFBDecrypter用法及代码示例
- GO NewCFBEncrypter用法及代码示例
- GO NewReplacer用法及代码示例
- GO New用法及代码示例
- GO NewTripleDESCipher用法及代码示例
- GO NewWriter用法及代码示例
- GO NewCBCEncrypter用法及代码示例
- GO NewOFB用法及代码示例
- GO NewTLSServer用法及代码示例
- GO NewTicker用法及代码示例
- GO NewCTR用法及代码示例
- GO NewEncoder用法及代码示例
- GO NumError用法及代码示例
- GO NotifyContext用法及代码示例
- GO Node用法及代码示例
- GO Notify用法及代码示例
- GO NotFoundHandler用法及代码示例
注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 NewGCM。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。