github.com/chwjbn/xclash@v0.2.0/transport/snell/cipher.go (about)

     1  package snell
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  
     7  	"github.com/Dreamacro/go-shadowsocks2/shadowaead"
     8  	"golang.org/x/crypto/argon2"
     9  	"golang.org/x/crypto/chacha20poly1305"
    10  )
    11  
    12  type snellCipher struct {
    13  	psk      []byte
    14  	keySize  int
    15  	makeAEAD func(key []byte) (cipher.AEAD, error)
    16  }
    17  
    18  func (sc *snellCipher) KeySize() int  { return sc.keySize }
    19  func (sc *snellCipher) SaltSize() int { return 16 }
    20  func (sc *snellCipher) Encrypter(salt []byte) (cipher.AEAD, error) {
    21  	return sc.makeAEAD(snellKDF(sc.psk, salt, sc.KeySize()))
    22  }
    23  
    24  func (sc *snellCipher) Decrypter(salt []byte) (cipher.AEAD, error) {
    25  	return sc.makeAEAD(snellKDF(sc.psk, salt, sc.KeySize()))
    26  }
    27  
    28  func snellKDF(psk, salt []byte, keySize int) []byte {
    29  	// snell use a special kdf function
    30  	return argon2.IDKey(psk, salt, 3, 8, 1, 32)[:keySize]
    31  }
    32  
    33  func aesGCM(key []byte) (cipher.AEAD, error) {
    34  	blk, err := aes.NewCipher(key)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  	return cipher.NewGCM(blk)
    39  }
    40  
    41  func NewAES128GCM(psk []byte) shadowaead.Cipher {
    42  	return &snellCipher{
    43  		psk:      psk,
    44  		keySize:  16,
    45  		makeAEAD: aesGCM,
    46  	}
    47  }
    48  
    49  func NewChacha20Poly1305(psk []byte) shadowaead.Cipher {
    50  	return &snellCipher{
    51  		psk:      psk,
    52  		keySize:  32,
    53  		makeAEAD: chacha20poly1305.New,
    54  	}
    55  }