-
Notifications
You must be signed in to change notification settings - Fork 3
/
crypt.go
92 lines (77 loc) · 2.34 KB
/
crypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Copyright 2021 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package crypt
import (
"bytes"
"crypto/rand"
"math/big"
"golang.org/x/crypto/argon2"
"github.com/adobe/aquarium-fish/lib/log"
)
const (
Algo_Argon2 = "Argon2"
Argon2_Memory = 524288
Argon2_Operations = 4
Argon2_Time = 1
Argon2_Threads = 1
Argon2_SaltBytes = 8
Argon2_StrBytes = 128
rand_string_charset = "abcdefghijkmnopqrstuvwxyz" +
"ABCDEFGHJKLMNPQRSTUVWXYZ123456789" // Base58
)
type Hash struct {
Algo string
Salt []byte
Hash []byte
}
// Create random bytes of specified size
func RandBytes(size int) (data []byte) {
data = make([]byte, size)
if _, err := rand.Read(data); err != nil {
log.Error("Crypt: Unable to generate random bytes:", err)
}
return
}
// Create random string of specified size
func RandString(size int) string {
data := make([]byte, size)
charset_len := big.NewInt(int64(len(rand_string_charset)))
for i := range data {
charset_pos, err := rand.Int(rand.Reader, charset_len)
if err != nil {
log.Error("Crypt: Failed to generate random string:", err)
}
data[i] = rand_string_charset[charset_pos.Int64()]
}
return string(data)
}
// Generate a salted hash for the input string
func Generate(password string, salt []byte) (hash Hash) {
hash.Algo = Algo_Argon2
// Check salt and if not provided - use generator
if salt != nil {
hash.Salt = salt
} else {
hash.Salt = RandBytes(Argon2_SaltBytes)
}
// Create hash data
hash.Hash = argon2.IDKey([]byte(password), hash.Salt,
Argon2_Time, Argon2_Memory, Argon2_Threads, Argon2_StrBytes)
return
}
// Compare string to generated hash
func (hash *Hash) IsEqual(password string) bool {
return bytes.Compare(hash.Hash, Generate(password, hash.Salt).Hash) == 0
}
func (hash *Hash) IsEmpty() bool {
return hash.Algo == ""
}