diff options
Diffstat (limited to 'internal/cryptoutil/cryptoutil.go')
| -rw-r--r-- | internal/cryptoutil/cryptoutil.go | 26 |
1 files changed, 18 insertions, 8 deletions
diff --git a/internal/cryptoutil/cryptoutil.go b/internal/cryptoutil/cryptoutil.go index b269803..0429b02 100644 --- a/internal/cryptoutil/cryptoutil.go +++ b/internal/cryptoutil/cryptoutil.go @@ -9,8 +9,10 @@ import ( "crypto/rand" "crypto/sha512" "crypto/subtle" + "encoding/binary" "encoding/hex" "errors" + "io" ) const ( @@ -101,23 +103,31 @@ func (h PasswordHash) CheckPassword(password string) (RawKey, error) { return key, nil } -// Sign generates an HMAC-SHA512 signature and appends it to msg. -func (k HMACKey) Sign(msg []byte) SignedMessage { +func (k HMACKey) mac(out, msg []byte, info string) []byte { mac := hmac.New(sha512.New, k) + buf := make([]byte, 0, binary.MaxVarintLen64) + mac.Write(binary.AppendUvarint(buf, uint64(len(info)))) + io.WriteString(mac, info) mac.Write(msg) - return mac.Sum(msg) + return mac.Sum(out) +} + +// Sign generates an HMAC-SHA512 signature and appends it to msg. The info and +// additionalData are also authenticated, but are not included in the returned +// signed message. +func (k HMACKey) Sign(msg []byte, info string) SignedMessage { + return k.mac(msg, msg, info) } // Verify checks whether the given message has a valid signature, and returns -// the raw message if it does. -func (k HMACKey) Verify(msg SignedMessage) ([]byte, bool) { +// the raw message if it does. The additionalData must match the data passed +// to Sign. +func (k HMACKey) Verify(msg SignedMessage, info string) ([]byte, bool) { if len(msg) < certSize { return nil, false } msg, sig := msg[:len(msg)-certSize], msg[len(msg)-certSize:] - mac := hmac.New(sha512.New, k) - mac.Write(msg) - if !hmac.Equal(sig, mac.Sum(nil)) { + if !hmac.Equal(sig, k.mac(nil, msg, info)) { return nil, false } return msg, true |
