當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO NewGCM用法及代碼示例

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)
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 NewGCM。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。