-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath_hash.go
98 lines (80 loc) · 2.48 KB
/
path_hash.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
93
94
95
96
97
98
package saltyhash
import (
"context"
"encoding/base64"
"encoding/hex"
"fmt"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
const (
pathHashHelpSyn = `Generate a hash sum in hex format for input data`
pathHashHelpDesc = `Generates a hash sum of the given algorithm in hex format against the given input data.`
)
func (b *backend) pathHash() *framework.Path {
return &framework.Path{
Pattern: "hash/" +
framework.GenericNameRegex("role_name") +
"/" +
framework.GenericNameRegex("algorithm"),
Fields: map[string]*framework.FieldSchema{
"input": {
Type: framework.TypeString,
Description: "The base64-encoded input data",
},
"role_name": {
Type: framework.TypeString,
Description: "Name of the role",
},
"algorithm": {
Type: framework.TypeString,
Description: `Algorithm to use (POST URL parameter). Valid values are:
* sha1
* sha2-256
* sha2-512
* sha3-256
* sha3-512`,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathHashWrite,
},
},
HelpSynopsis: pathHashHelpSyn,
HelpDescription: pathHashHelpDesc,
}
}
func (b *backend) pathHashWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var err error
err = validateFieldSet(data)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
roleName := data.Get("role_name").(string)
inputB64 := data.Get("input").(string)
algorithm := data.Get("algorithm").(string)
role, err := b.getRole(ctx, req.Storage, roleName)
if err != nil || role == nil {
return logical.ErrorResponse(fmt.Sprintf("unable to find role %s: %s", roleName, err)), logical.ErrInvalidRequest
}
hf, err := hashFunction(algorithm)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
salt, _ := base64.StdEncoding.DecodeString(role.Salt)
input, err := base64.StdEncoding.DecodeString(inputB64)
if len(input) == 0 || err != nil {
return logical.ErrorResponse(fmt.Sprintf("input either empty or contains invalid base64: %s", err)), logical.ErrInvalidRequest
}
input = saltSecret(input, salt, role.Mode)
_, err = hf.Write(input)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("couldn't hash data: %s", err)), logical.ErrInvalidRequest
}
return &logical.Response{
Data: map[string]interface{}{
"sum": hex.EncodeToString(hf.Sum(nil)),
},
}, nil
}