github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/jls/aes_gcm_256.go (about)

     1  package jls
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"errors"
     7  )
     8  
     9  const ivLen = 32 // bytes
    10  
    11  func Encrypt(nonce []byte, plaintext []byte, key []byte) ([]byte, error) {
    12  	if len(nonce) != ivLen {
    13  		return nil, errors.New("wrong nonce len")
    14  	}
    15  
    16  	c, err := aes.NewCipher(key)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  
    21  	gcm, err := cipher.NewGCMWithNonceSize(c, ivLen)
    22  
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  
    27  	cipertextAndMac := gcm.Seal(nonce, nonce, plaintext, nil)
    28  	return cipertextAndMac[ivLen:], nil
    29  }
    30  
    31  func Decrypt(nonce []byte, cipherTextAndMac []byte, key []byte) ([]byte, error) {
    32  	if len(nonce) != ivLen {
    33  		return nil, errors.New("wrong nonce len")
    34  	}
    35  
    36  	c, err := aes.NewCipher(key)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	gcm, err := cipher.NewGCMWithNonceSize(c, ivLen)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	nonceSize := gcm.NonceSize()
    47  	if len(nonce) < nonceSize {
    48  		return nil, errors.New("ciphertext too short")
    49  	}
    50  	nonceAndPlainText, err := gcm.Open(nonce, nonce, cipherTextAndMac, nil)
    51  
    52  	if err != nil {
    53  		return nonceAndPlainText, err
    54  	}
    55  
    56  	if len(nonceAndPlainText) <= ivLen {
    57  		return nonceAndPlainText, errors.New("wrong res len")
    58  	}
    59  
    60  	return nonceAndPlainText[ivLen:], err
    61  }