|
| 1 | +package crypto |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "crypto/subtle" |
| 6 | + "encoding/base64" |
| 7 | + "fmt" |
| 8 | + "golang.org/x/crypto/argon2" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +const hashFormat = "$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s" |
| 13 | + |
| 14 | +type PasswordConfig struct { |
| 15 | + time uint32 |
| 16 | + memory uint32 |
| 17 | + threads uint8 |
| 18 | + keyLen uint32 |
| 19 | +} |
| 20 | + |
| 21 | +func (c PasswordConfig) DefaultConfig() *PasswordConfig { |
| 22 | + return &PasswordConfig{ |
| 23 | + time: 1, |
| 24 | + memory: 64 * 1024, |
| 25 | + threads: 4, |
| 26 | + keyLen: 32, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func GenerateHash(config *PasswordConfig, s string) (string, error) { |
| 31 | + salt := make([]byte, 16) |
| 32 | + if _, err := rand.Read(salt); err != nil { |
| 33 | + return "", err |
| 34 | + } |
| 35 | + |
| 36 | + hash := argon2.IDKey([]byte(s), salt, config.time, config.memory, config.threads, config.keyLen) |
| 37 | + |
| 38 | + saltB64 := base64.RawStdEncoding.EncodeToString(salt) |
| 39 | + hashB64 := base64.RawStdEncoding.EncodeToString(hash) |
| 40 | + |
| 41 | + finalHash := fmt.Sprintf(hashFormat, argon2.Version, config.memory, config.time, config.threads, saltB64, hashB64) |
| 42 | + |
| 43 | + return finalHash, nil |
| 44 | +} |
| 45 | + |
| 46 | +func Validate(s, hash string) (bool, error) { |
| 47 | + |
| 48 | + hashParts := strings.Split(hash, "$") |
| 49 | + |
| 50 | + config := &PasswordConfig{} |
| 51 | + |
| 52 | + _, err := fmt.Sscanf(hashParts[3], "m=%d,t=%d,p=%d", &config.memory, &config.time, &config.threads) |
| 53 | + if err != nil { |
| 54 | + return false, err |
| 55 | + } |
| 56 | + |
| 57 | + salt, err := base64.RawStdEncoding.DecodeString(hashParts[4]) |
| 58 | + if err != nil { |
| 59 | + return false, err |
| 60 | + } |
| 61 | + |
| 62 | + decodedHash, err := base64.RawStdEncoding.DecodeString(hashParts[5]) |
| 63 | + |
| 64 | + config.keyLen = uint32(len(decodedHash)) |
| 65 | + |
| 66 | + comparisonHash := argon2.IDKey([]byte(s), salt, config.time, config.memory, config.threads, config.keyLen) |
| 67 | + |
| 68 | + return subtle.ConstantTimeCompare(decodedHash, comparisonHash) == 1, nil |
| 69 | +} |
0 commit comments