encoding.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package util
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "crypto/rand"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "fmt"
  10. "hash"
  11. )
  12. // source: https://github.com/gogits/gogs/blob/9ee80e3e5426821f03a4e99fad34418f5c736413/modules/base/tool.go#L58
  13. func GetRandomString(n int, alphabets ...byte) string {
  14. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  15. var bytes = make([]byte, n)
  16. rand.Read(bytes)
  17. for i, b := range bytes {
  18. if len(alphabets) == 0 {
  19. bytes[i] = alphanum[b%byte(len(alphanum))]
  20. } else {
  21. bytes[i] = alphabets[b%byte(len(alphabets))]
  22. }
  23. }
  24. return string(bytes)
  25. }
  26. func EncodePassword(password string, salt string) string {
  27. newPasswd := PBKDF2([]byte(password), []byte(salt), 10000, 50, sha256.New)
  28. return fmt.Sprintf("%x", newPasswd)
  29. }
  30. // Encode string to md5 hex value.
  31. func EncodeMd5(str string) string {
  32. m := md5.New()
  33. m.Write([]byte(str))
  34. return hex.EncodeToString(m.Sum(nil))
  35. }
  36. // http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
  37. func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  38. prf := hmac.New(h, password)
  39. hashLen := prf.Size()
  40. numBlocks := (keyLen + hashLen - 1) / hashLen
  41. var buf [4]byte
  42. dk := make([]byte, 0, numBlocks*hashLen)
  43. U := make([]byte, hashLen)
  44. for block := 1; block <= numBlocks; block++ {
  45. // N.B.: || means concatenation, ^ means XOR
  46. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  47. // U_1 = PRF(password, salt || uint(i))
  48. prf.Reset()
  49. prf.Write(salt)
  50. buf[0] = byte(block >> 24)
  51. buf[1] = byte(block >> 16)
  52. buf[2] = byte(block >> 8)
  53. buf[3] = byte(block)
  54. prf.Write(buf[:4])
  55. dk = prf.Sum(dk)
  56. T := dk[len(dk)-hashLen:]
  57. copy(U, T)
  58. // U_n = PRF(password, U_(n-1))
  59. for n := 2; n <= iter; n++ {
  60. prf.Reset()
  61. prf.Write(U)
  62. U = U[:0]
  63. U = prf.Sum(U)
  64. for x := range U {
  65. T[x] ^= U[x]
  66. }
  67. }
  68. }
  69. return dk[:keyLen]
  70. }
  71. func GetBasicAuthHeader(user string, password string) string {
  72. var userAndPass = user + ":" + password
  73. return "Basic " + base64.StdEncoding.EncodeToString([]byte(userAndPass))
  74. }