Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

secret.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package mtglib
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "fmt"
  7. "strings"
  8. )
  9. const SecretKeyLength = 16
  10. type Secret struct {
  11. Key []byte
  12. Host string
  13. }
  14. func (s Secret) MarshalText() ([]byte, error) {
  15. if s.Key == nil {
  16. return nil, nil
  17. }
  18. return []byte(s.String()), nil
  19. }
  20. func (s *Secret) UnmarshalText(data []byte) error {
  21. text := string(data)
  22. if text == "" {
  23. return ErrSecretEmpty
  24. }
  25. var (
  26. decoded []byte
  27. err error
  28. )
  29. if strings.HasPrefix(text, "ee") {
  30. decoded, err = hex.DecodeString(strings.TrimPrefix(text, "ee"))
  31. }
  32. if err != nil || len(decoded) <= SecretKeyLength {
  33. decoded, err = base64.RawURLEncoding.DecodeString(text)
  34. }
  35. if err != nil {
  36. return fmt.Errorf("incorrect secret format: %w", err)
  37. }
  38. if len(decoded) <= SecretKeyLength {
  39. return fmt.Errorf("secret has incorrect length %d", len(text))
  40. }
  41. s.Key = decoded[:SecretKeyLength]
  42. s.Host = string(decoded[SecretKeyLength:])
  43. return nil
  44. }
  45. func (s Secret) String() string {
  46. return s.Base64()
  47. }
  48. func (s Secret) Base64() string {
  49. return base64.RawURLEncoding.EncodeToString(s.makeBytes())
  50. }
  51. func (s Secret) Hex() string {
  52. return hex.EncodeToString(s.makeBytes())
  53. }
  54. func (s *Secret) makeBytes() []byte {
  55. data := append([]byte{238}, s.Key...) // hex 'ee' = 238
  56. data = append(data, s.Host...)
  57. return data
  58. }
  59. func GenerateSecret(hostname string) Secret {
  60. s := Secret{
  61. Key: make([]byte, SecretKeyLength),
  62. Host: hostname,
  63. }
  64. if _, err := rand.Read(s.Key); err != nil {
  65. panic(err)
  66. }
  67. return s
  68. }