config.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. }
  52. func PasswordToCipherKey(password string, keySize int) []byte {
  53. pwdBytes := []byte(password)
  54. key := make([]byte, 0, keySize)
  55. md5Sum := md5.Sum(pwdBytes)
  56. key = append(key, md5Sum[:]...)
  57. for len(key) < keySize {
  58. md5Hash := md5.New()
  59. md5Hash.Write(md5Sum[:])
  60. md5Hash.Write(pwdBytes)
  61. md5Hash.Sum(md5Sum[:0])
  62. key = append(key, md5Sum[:]...)
  63. }
  64. return key
  65. }