config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package shadowsocks
  2. import (
  3. "crypto/cipher"
  4. "crypto/md5"
  5. "v2ray.com/core/common/crypto"
  6. "v2ray.com/core/common/protocol"
  7. )
  8. func (this *Account) GetCipher() Cipher {
  9. switch this.CipherType {
  10. case CipherType_AES_128_CFB:
  11. return &AesCfb{KeyBytes: 16}
  12. case CipherType_AES_256_CFB:
  13. return &AesCfb{KeyBytes: 32}
  14. case CipherType_CHACHA20:
  15. return &ChaCha20{IVBytes: 8}
  16. case CipherType_CHACHA20_IEFT:
  17. return &ChaCha20{IVBytes: 12}
  18. }
  19. panic("Failed to create Cipher. Should not happen.")
  20. }
  21. func (this *Account) Equals(another protocol.Account) bool {
  22. if account, ok := another.(*Account); ok {
  23. return account.Password == this.Password
  24. }
  25. return false
  26. }
  27. func (this *Account) AsAccount() (protocol.Account, error) {
  28. return this, nil
  29. }
  30. func (this *Account) GetCipherKey(size int) []byte {
  31. return PasswordToCipherKey(this.Password, size)
  32. }
  33. type Cipher interface {
  34. KeySize() int
  35. IVSize() int
  36. NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error)
  37. NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error)
  38. }
  39. type AesCfb struct {
  40. KeyBytes int
  41. }
  42. func (this *AesCfb) KeySize() int {
  43. return this.KeyBytes
  44. }
  45. func (this *AesCfb) IVSize() int {
  46. return 16
  47. }
  48. func (this *AesCfb) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  49. stream := crypto.NewAesEncryptionStream(key, iv)
  50. return stream, nil
  51. }
  52. func (this *AesCfb) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  53. stream := crypto.NewAesDecryptionStream(key, iv)
  54. return stream, nil
  55. }
  56. type ChaCha20 struct {
  57. IVBytes int
  58. }
  59. func (this *ChaCha20) KeySize() int {
  60. return 32
  61. }
  62. func (this *ChaCha20) IVSize() int {
  63. return this.IVBytes
  64. }
  65. func (this *ChaCha20) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  66. return crypto.NewChaCha20Stream(key, iv), nil
  67. }
  68. func (this *ChaCha20) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) {
  69. return crypto.NewChaCha20Stream(key, iv), nil
  70. }
  71. func PasswordToCipherKey(password string, keySize int) []byte {
  72. pwdBytes := []byte(password)
  73. key := make([]byte, 0, keySize)
  74. md5Sum := md5.Sum(pwdBytes)
  75. key = append(key, md5Sum[:]...)
  76. for len(key) < keySize {
  77. md5Hash := md5.New()
  78. md5Hash.Write(md5Sum[:])
  79. md5Hash.Write(pwdBytes)
  80. md5Hash.Sum(md5Sum[:0])
  81. key = append(key, md5Sum[:]...)
  82. }
  83. return key
  84. }