A cloud-native LDAP server backed by a Consul datastore
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.

60 lines
1.3 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "fmt"
  8. "strings"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. // Encode encodes the []byte of raw password
  12. func SSHAEncode(rawPassPhrase []byte) string {
  13. hash := makeSSHAHash(rawPassPhrase, makeSalt())
  14. b64 := base64.StdEncoding.EncodeToString(hash)
  15. return fmt.Sprintf("{ssha}%s", b64)
  16. }
  17. // Matches matches the encoded password and the raw password
  18. func SSHAMatches(encodedPassPhrase string, rawPassPhrase []byte) bool {
  19. if !strings.EqualFold(encodedPassPhrase[:6], "{ssha}") {
  20. return false
  21. }
  22. bhash, err := base64.StdEncoding.DecodeString(encodedPassPhrase[6:])
  23. if err != nil {
  24. return false
  25. }
  26. salt := bhash[20:]
  27. newssha := makeSSHAHash(rawPassPhrase, salt)
  28. if bytes.Compare(newssha, bhash) != 0 {
  29. return false
  30. }
  31. return true
  32. }
  33. // makeSalt make a 32 byte array containing random bytes.
  34. func makeSalt() []byte {
  35. sbytes := make([]byte, 32)
  36. _, err := rand.Read(sbytes)
  37. if err != nil {
  38. log.Panicf("Could not read random bytes: %s", err)
  39. }
  40. return sbytes
  41. }
  42. // makeSSHAHash make hasing using SHA-1 with salt. This is not the final output though. You need to append {SSHA} string with base64 of this hash.
  43. func makeSSHAHash(passphrase, salt []byte) []byte {
  44. sha := sha1.New()
  45. sha.Write(passphrase)
  46. sha.Write(salt)
  47. h := sha.Sum(nil)
  48. return append(h, salt...)
  49. }