config.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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, err := crypto.NewAesEncryptionStream(key, iv)
  25. if err != nil {
  26. return nil, err
  27. }
  28. return stream, nil
  29. }
  30. func (this *AesCfb) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  31. stream, err := crypto.NewAesDecryptionStream(key, iv)
  32. if err != nil {
  33. return nil, err
  34. }
  35. return stream, nil
  36. }
  37. type ChaCha20 struct {
  38. IVBytes int
  39. }
  40. func (this *ChaCha20) KeySize() int {
  41. return 32
  42. }
  43. func (this *ChaCha20) IVSize() int {
  44. return this.IVBytes
  45. }
  46. func (this *ChaCha20) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  47. return crypto.NewChaCha20Stream(key, iv), nil
  48. }
  49. func (this *ChaCha20) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  50. return crypto.NewChaCha20Stream(key, iv), nil
  51. }
  52. type Config struct {
  53. Cipher Cipher
  54. Key []byte
  55. UDP bool
  56. Level protocol.UserLevel
  57. }
  58. func PasswordToCipherKey(password string, keySize int) []byte {
  59. pwdBytes := []byte(password)
  60. key := make([]byte, 0, keySize)
  61. md5Sum := md5.Sum(pwdBytes)
  62. key = append(key, md5Sum[:]...)
  63. for len(key) < keySize {
  64. md5Hash := md5.New()
  65. md5Hash.Write(md5Sum[:])
  66. md5Hash.Write(pwdBytes)
  67. md5Hash.Sum(md5Sum[:0])
  68. key = append(key, md5Sum[:]...)
  69. }
  70. return key
  71. }