Initial commit

This commit is contained in:
Hayden 2022-08-29 18:30:36 -08:00
commit 29f583e936
135 changed files with 18463 additions and 0 deletions

View file

@ -0,0 +1,13 @@
package hasher
import "golang.org/x/crypto/bcrypt"
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

View file

@ -0,0 +1,40 @@
package hasher
import "testing"
func TestHashPassword(t *testing.T) {
t.Parallel()
type args struct {
password string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "letters_and_numbers",
args: args{
password: "password123456788",
},
},
{
name: "letters_number_and_special",
args: args{
password: "!2afj3214pofajip3142j;fa",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := HashPassword(tt.args.password)
if (err != nil) != tt.wantErr {
t.Errorf("HashPassword() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !CheckPasswordHash(tt.args.password, got) {
t.Errorf("CheckPasswordHash() failed to validate password=%v against hash=%v", tt.args.password, got)
}
})
}
}

View file

@ -0,0 +1,30 @@
package hasher
import (
"crypto/rand"
"crypto/sha256"
"encoding/base32"
)
type Token struct {
Raw string
Hash []byte
}
func GenerateToken() Token {
randomBytes := make([]byte, 16)
rand.Read(randomBytes)
plainText := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(randomBytes)
hash := HashToken(plainText)
return Token{
Raw: plainText,
Hash: hash,
}
}
func HashToken(plainTextToken string) []byte {
hash := sha256.Sum256([]byte(plainTextToken))
return hash[:]
}

View file

@ -0,0 +1,44 @@
package hasher
import (
"testing"
"github.com/stretchr/testify/assert"
)
const ITERATIONS = 200
func Test_NewToken(t *testing.T) {
t.Parallel()
tokens := make([]Token, ITERATIONS)
for i := 0; i < ITERATIONS; i++ {
tokens[i] = GenerateToken()
}
// Check if they are unique
for i := 0; i < 5; i++ {
for j := i + 1; j < 5; j++ {
if tokens[i].Raw == tokens[j].Raw {
t.Errorf("NewToken() failed to generate unique tokens")
}
}
}
}
func Test_HashToken_CheckTokenHash(t *testing.T) {
t.Parallel()
for i := 0; i < ITERATIONS; i++ {
token := GenerateToken()
// Check raw text is reltively random
for j := 0; j < 5; j++ {
assert.NotEqual(t, token.Raw, GenerateToken().Raw)
}
// Check token length is less than 32 characters
assert.Less(t, len(token.Raw), 32)
// Check hash is the same
assert.Equal(t, token.Hash, HashToken(token.Raw))
}
}