-
Notifications
You must be signed in to change notification settings - Fork 16
/
adapter.go
60 lines (48 loc) · 1.28 KB
/
adapter.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
package public
import (
"crypto/x509"
"encoding/base64"
"github.com/deepvalue-network/software/libs/hash"
)
type adapter struct {
hashAdapter hash.Adapter
builder Builder
}
func createAdapter(hashAdapter hash.Adapter, builder Builder) Adapter {
out := adapter{
hashAdapter: hashAdapter,
builder: builder,
}
return &out
}
// FromBytes converts []byte to Key
func (app *adapter) FromBytes(input []byte) (Key, error) {
pubKey, err := x509.ParsePKCS1PublicKey(input)
if err != nil {
return nil, err
}
return app.builder.Create().WithKey(*pubKey).Now()
}
// FromEncoded converts an encoded string to Key
func (app *adapter) FromEncoded(encoded string) (Key, error) {
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return nil, err
}
return app.FromBytes(decoded)
}
// ToBytes converts Key to []byte
func (app *adapter) ToBytes(key Key) []byte {
pubKey := key.Key()
return x509.MarshalPKCS1PublicKey(&pubKey)
}
// ToEncoded converts a Key to an encoded string
func (app *adapter) ToEncoded(key Key) string {
bytes := app.ToBytes(key)
return base64.StdEncoding.EncodeToString(bytes)
}
// ToHash converts a Key to an hash
func (app *adapter) ToHash(key Key) (*hash.Hash, error) {
bytes := app.ToBytes(key)
return app.hashAdapter.FromBytes(bytes)
}