github.com/imannamdari/v2ray-core/v5@v5.0.5/common/crypto/aes.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  
     7  	"github.com/imannamdari/v2ray-core/v5/common"
     8  )
     9  
    10  // NewAesDecryptionStream creates a new AES encryption stream based on given key and IV.
    11  // Caller must ensure the length of key and IV is either 16, 24 or 32 bytes.
    12  func NewAesDecryptionStream(key []byte, iv []byte) cipher.Stream {
    13  	return NewAesStreamMethod(key, iv, cipher.NewCFBDecrypter)
    14  }
    15  
    16  // NewAesEncryptionStream creates a new AES description stream based on given key and IV.
    17  // Caller must ensure the length of key and IV is either 16, 24 or 32 bytes.
    18  func NewAesEncryptionStream(key []byte, iv []byte) cipher.Stream {
    19  	return NewAesStreamMethod(key, iv, cipher.NewCFBEncrypter)
    20  }
    21  
    22  func NewAesStreamMethod(key []byte, iv []byte, f func(cipher.Block, []byte) cipher.Stream) cipher.Stream {
    23  	aesBlock, err := aes.NewCipher(key)
    24  	common.Must(err)
    25  	return f(aesBlock, iv)
    26  }
    27  
    28  // NewAesCTRStream creates a stream cipher based on AES-CTR.
    29  func NewAesCTRStream(key []byte, iv []byte) cipher.Stream {
    30  	return NewAesStreamMethod(key, iv, cipher.NewCTR)
    31  }
    32  
    33  // NewAesGcm creates a AEAD cipher based on AES-GCM.
    34  func NewAesGcm(key []byte) cipher.AEAD {
    35  	block, err := aes.NewCipher(key)
    36  	common.Must(err)
    37  	aead, err := cipher.NewGCM(block)
    38  	common.Must(err)
    39  	return aead
    40  }