clash/transport/snell/cipher.go

57 lines
1.2 KiB
Go
Raw Normal View History

2019-10-09 18:46:23 +08:00
package snell
import (
"crypto/aes"
2019-10-09 18:46:23 +08:00
"crypto/cipher"
2022-05-24 20:28:18 +08:00
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
2019-10-09 18:46:23 +08:00
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/chacha20poly1305"
2019-10-09 18:46:23 +08:00
)
type snellCipher struct {
psk []byte
keySize int
2019-10-09 18:46:23 +08:00
makeAEAD func(key []byte) (cipher.AEAD, error)
}
func (sc *snellCipher) KeySize() int { return sc.keySize }
2019-10-09 18:46:23 +08:00
func (sc *snellCipher) SaltSize() int { return 16 }
func (sc *snellCipher) Encrypter(salt []byte) (cipher.AEAD, error) {
return sc.makeAEAD(snellKDF(sc.psk, salt, sc.KeySize()))
2019-10-09 18:46:23 +08:00
}
2021-10-10 23:44:09 +08:00
2019-10-09 18:46:23 +08:00
func (sc *snellCipher) Decrypter(salt []byte) (cipher.AEAD, error) {
return sc.makeAEAD(snellKDF(sc.psk, salt, sc.KeySize()))
}
func snellKDF(psk, salt []byte, keySize int) []byte {
// snell use a special kdf function
return argon2.IDKey(psk, salt, 3, 8, 1, 32)[:keySize]
}
func aesGCM(key []byte) (cipher.AEAD, error) {
blk, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCM(blk)
}
func NewAES128GCM(psk []byte) shadowaead.Cipher {
return &snellCipher{
psk: psk,
keySize: 16,
makeAEAD: aesGCM,
}
}
func NewChacha20Poly1305(psk []byte) shadowaead.Cipher {
return &snellCipher{
psk: psk,
keySize: 32,
makeAEAD: chacha20poly1305.New,
}
2019-10-09 18:46:23 +08:00
}