-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
public_key.go
63 lines (51 loc) · 1.14 KB
/
public_key.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
package crypto
import (
"database/sql/driver"
"encoding/hex"
"encoding/json"
"fmt"
)
// PublicKey defines a type which can be used for JSON and SQL.
type PublicKey []byte
// PublicKeyFromHex generates a public key from a hex string
func PublicKeyFromHex(hexStr string) (*PublicKey, error) {
result, err := hex.DecodeString(hexStr)
if err != nil {
return nil, err
}
pubKey := PublicKey(result)
return &pubKey, err
}
func (k PublicKey) String() string {
return hex.EncodeToString(k)
}
func (k PublicKey) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(k))
}
func (k *PublicKey) UnmarshalJSON(in []byte) error {
var hexStr string
if err := json.Unmarshal(in, &hexStr); err != nil {
return err
}
result, err := hex.DecodeString(hexStr)
if err != nil {
return err
}
*k = PublicKey(result)
return nil
}
func (k *PublicKey) Scan(value interface{}) error {
switch v := value.(type) {
case nil:
*k = nil
return nil
case []byte:
*k = v
return nil
default:
return fmt.Errorf("invalid public key bytes got %T wanted []byte", v)
}
}
func (k PublicKey) Value() (driver.Value, error) {
return []byte(k), nil
}