golang实现aes-256-gcm加密/解密

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/hex"
    "fmt"
    "io"
)

//NewGCMEncrypter aes-256-gcm 加密
func NewGCMEncrypter(aesKey string, v []byte) (string, string, error) {
    // The key argument should be the AES key, either 16 or 32 bytes
    // to select AES-128 or AES-256.
    // key := []byte("AES256Key-32Characters1234567890")
    // plaintext := []byte("exampleplaintext")
    key := []byte(aesKey)
    plaintext := v

    block, err := aes.NewCipher(key)
    if err != nil {
        return "", "", err
    }

    // 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 {
        return "", "", err
    }

    aesgcm, err := cipher.NewGCM(block)
    if err != nil {
        return "", "", err
    }

    ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)

    return fmt.Sprintf("%x", nonce), fmt.Sprintf("%x", ciphertext), nil

}

//NewGCMDecrypter aes-256-gcm 解密
func NewGCMDecrypter(aesKey, nonceV, ciphertextV string) ([]byte, error) {
    // The key argument should be the AES key, either 16 or 32 bytes
    // to select AES-128 or AES-256.
    key := []byte(aesKey)
    nonce, _ := hex.DecodeString(nonceV)

    ciphertext, _ := hex.DecodeString(ciphertextV)

    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    aesgcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
    if err != nil {
        return nil, err
    }

    // fmt.Printf("%s\n", plaintext)
    return plaintext, err
    // Output: exampleplaintext
}

func main() {
    plaintext := []byte("exampleplaintext")
    v1, v2, err := NewGCMEncrypter("AES256Key-32Characters1234567890", plaintext)
    fmt.Println(v1, v2, err)

    v3, err := NewGCMDecrypter("AES256Key-32Characters1234567890", v1, v2)
    fmt.Println(string(v3), err)
}

添加新评论