config.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package shadowsocks
  2. import (
  3. "crypto/cipher"
  4. "crypto/md5"
  5. "github.com/v2ray/v2ray-core/common/crypto"
  6. "github.com/v2ray/v2ray-core/common/protocol"
  7. )
  8. type Cipher interface {
  9. KeySize() int
  10. IVSize() int
  11. NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error)
  12. NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error)
  13. }
  14. type AesCfb struct {
  15. KeyBytes int
  16. }
  17. func (this *AesCfb) KeySize() int {
  18. return this.KeyBytes
  19. }
  20. func (this *AesCfb) IVSize() int {
  21. return 16
  22. }
  23. func (this *AesCfb) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  24. stream := crypto.NewAesEncryptionStream(key, iv)
  25. return stream, nil
  26. }
  27. func (this *AesCfb) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  28. stream := crypto.NewAesDecryptionStream(key, iv)
  29. return stream, nil
  30. }
  31. type ChaCha20 struct {
  32. IVBytes int
  33. }
  34. func (this *ChaCha20) KeySize() int {
  35. return 32
  36. }
  37. func (this *ChaCha20) IVSize() int {
  38. return this.IVBytes
  39. }
  40. func (this *ChaCha20) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  41. return crypto.NewChaCha20Stream(key, iv), nil
  42. }
  43. func (this *ChaCha20) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  44. return crypto.NewChaCha20Stream(key, iv), nil
  45. }
  46. type Config struct {
  47. Cipher Cipher
  48. Key []byte
  49. UDP bool
  50. Level protocol.UserLevel
  51. Email string
  52. }
  53. func PasswordToCipherKey(password string, keySize int) []byte {
  54. pwdBytes := []byte(password)
  55. key := make([]byte, 0, keySize)
  56. md5Sum := md5.Sum(pwdBytes)
  57. key = append(key, md5Sum[:]...)
  58. for len(key) < keySize {
  59. md5Hash := md5.New()
  60. md5Hash.Write(md5Sum[:])
  61. md5Hash.Write(pwdBytes)
  62. md5Hash.Sum(md5Sum[:0])
  63. key = append(key, md5Sum[:]...)
  64. }
  65. return key
  66. }