passwordlogic.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package logic
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/base64"
  6. "fmt"
  7. "net/http"
  8. "dag-jupyter/internal/svc"
  9. "dag-jupyter/internal/types"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. "golang.org/x/crypto/argon2"
  12. )
  13. type PasswordLogic struct {
  14. logx.Logger
  15. ctx context.Context
  16. svcCtx *svc.ServiceContext
  17. }
  18. func NewPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordLogic {
  19. return &PasswordLogic{
  20. Logger: logx.WithContext(ctx),
  21. ctx: ctx,
  22. svcCtx: svcCtx,
  23. }
  24. }
  25. func generateRandomBytes(n uint32) ([]byte, error) {
  26. b := make([]byte, n)
  27. _, err := rand.Read(b)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return b, nil
  32. }
  33. type params struct {
  34. memory uint32
  35. iterations uint32
  36. parallelism uint8
  37. saltLength uint32
  38. keyLength uint32
  39. }
  40. func generateFromPassword(password string, p *params) (encodedHash string, err error) {
  41. salt, err := generateRandomBytes(p.saltLength)
  42. if err != nil {
  43. return "", err
  44. }
  45. hash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
  46. // Base64 encode the salt and hashed password.
  47. b64Salt := base64.RawStdEncoding.EncodeToString(salt)
  48. b64Hash := base64.RawStdEncoding.EncodeToString(hash)
  49. // Return a string using the standard encoded hash representation.
  50. encodedHash = fmt.Sprintf("argon2:$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, p.memory, p.iterations, p.parallelism, b64Salt, b64Hash)
  51. return encodedHash, nil
  52. }
  53. func (l *PasswordLogic) Password(req *types.PasswordRequest) (resp *types.Response, err error) {
  54. p := &params{
  55. memory: 10240,
  56. iterations: 10,
  57. parallelism: 8,
  58. saltLength: 16,
  59. keyLength: 32,
  60. }
  61. // Pass the plaintext password and parameters to our generateFromPassword
  62. // helper function.
  63. hash, err := generateFromPassword(req.Password, p)
  64. if err != nil {
  65. return &types.Response{Data: err, Code: http.StatusInternalServerError}, err
  66. }
  67. return &types.Response{Data: hash, Code: http.StatusOK}, nil
  68. }