bottin/ssha.go

59 lines
1.3 KiB
Go
Raw Normal View History

2020-01-19 11:49:49 +00:00
package main
import (
"bytes"
2020-02-01 10:32:50 +00:00
"crypto/rand"
2020-01-19 11:49:49 +00:00
"crypto/sha1"
"encoding/base64"
"fmt"
2020-02-01 10:32:50 +00:00
"log"
"strings"
2020-01-19 11:49:49 +00:00
)
// Encode encodes the []byte of raw password
func SSHAEncode(rawPassPhrase []byte) string {
hash := makeSSHAHash(rawPassPhrase, makeSalt())
b64 := base64.StdEncoding.EncodeToString(hash)
return fmt.Sprintf("{ssha}%s", b64)
}
// Matches matches the encoded password and the raw password
func SSHAMatches(encodedPassPhrase string, rawPassPhrase []byte) bool {
2020-02-01 10:32:50 +00:00
if !strings.EqualFold(encodedPassPhrase[:6], "{ssha}") {
2020-01-19 11:49:49 +00:00
return false
}
bhash, err := base64.StdEncoding.DecodeString(encodedPassPhrase[6:])
if err != nil {
return false
}
salt := bhash[20:]
newssha := makeSSHAHash(rawPassPhrase, salt)
if bytes.Compare(newssha, bhash) != 0 {
return false
}
return true
}
// makeSalt make a 32 byte array containing random bytes.
func makeSalt() []byte {
sbytes := make([]byte, 32)
2020-01-27 16:01:32 +00:00
_, err := rand.Read(sbytes)
if err != nil {
log.Panicf("Could not read random bytes: %s", err)
}
2020-01-19 11:49:49 +00:00
return sbytes
}
// 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.
func makeSSHAHash(passphrase, salt []byte) []byte {
sha := sha1.New()
sha.Write(passphrase)
sha.Write(salt)
h := sha.Sum(nil)
return append(h, salt...)
}