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.

87 lines
2.0 KiB

  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package generate
  6. import (
  7. "crypto/rand"
  8. "encoding/base64"
  9. "io"
  10. "math/big"
  11. "time"
  12. "github.com/dgrijalva/jwt-go"
  13. )
  14. // GetRandomString generate random string by specify chars.
  15. func GetRandomString(n int) (string, error) {
  16. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  17. buffer := make([]byte, n)
  18. max := big.NewInt(int64(len(alphanum)))
  19. for i := 0; i < n; i++ {
  20. index, err := randomInt(max)
  21. if err != nil {
  22. return "", err
  23. }
  24. buffer[i] = alphanum[index]
  25. }
  26. return string(buffer), nil
  27. }
  28. // NewInternalToken generate a new value intended to be used by INTERNAL_TOKEN.
  29. func NewInternalToken() (string, error) {
  30. secretBytes := make([]byte, 32)
  31. _, err := io.ReadFull(rand.Reader, secretBytes)
  32. if err != nil {
  33. return "", err
  34. }
  35. secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)
  36. now := time.Now()
  37. var internalToken string
  38. internalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  39. "nbf": now.Unix(),
  40. }).SignedString([]byte(secretKey))
  41. if err != nil {
  42. return "", err
  43. }
  44. return internalToken, nil
  45. }
  46. // NewJwtSecret generate a new value intended to be used by LFS_JWT_SECRET.
  47. func NewJwtSecret() (string, error) {
  48. JWTSecretBytes := make([]byte, 32)
  49. _, err := io.ReadFull(rand.Reader, JWTSecretBytes)
  50. if err != nil {
  51. return "", err
  52. }
  53. return base64.RawURLEncoding.EncodeToString(JWTSecretBytes), nil
  54. }
  55. // NewSecretKey generate a new value intended to be used by SECRET_KEY.
  56. func NewSecretKey() (string, error) {
  57. secretKey, err := GetRandomString(64)
  58. if err != nil {
  59. return "", err
  60. }
  61. return secretKey, nil
  62. }
  63. func randomInt(max *big.Int) (int, error) {
  64. rand, err := rand.Int(rand.Reader, max)
  65. if err != nil {
  66. return 0, err
  67. }
  68. return int(rand.Int64()), nil
  69. }