storj/pkg/auth/signature.go
paul cannon c35b93766d
Unite all cryptographic signing and verifying (#1244)
this change removes the cryptopasta dependency.

a couple possible sources of problem with this change:

 * the encoding used for ECDSA signatures on SignedMessage has changed.
   the encoding employed by cryptopasta was workable, but not the same
   as the encoding used for such signatures in the rest of the world
   (most particularly, on ECDSA signatures in X.509 certificates). I
   think we'll be best served by using one ECDSA signature encoding from
   here on, but if we need to use the old encoding for backwards
   compatibility with existing nodes, that can be arranged.

 * since there's already a breaking change in SignedMessage, I changed
   it to send and receive public keys in raw PKIX format, instead of
   PEM. PEM just adds unhelpful overhead for this case.
2019-02-07 14:39:20 -06:00

56 lines
1.7 KiB
Go

// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package auth
import (
"storj.io/storj/pkg/identity"
"storj.io/storj/pkg/pb"
"storj.io/storj/pkg/pkcrypto"
)
// GenerateSignature creates signature from identity id
func GenerateSignature(data []byte, identity *identity.FullIdentity) ([]byte, error) {
return pkcrypto.HashAndSign(identity.Key, data)
}
// NewSignedMessage creates instance of signed message
func NewSignedMessage(signature []byte, identity *identity.FullIdentity) (*pb.SignedMessage, error) {
encodedKey, err := pkcrypto.PublicKeyToPKIX(identity.Leaf.PublicKey)
if err != nil {
return nil, err
}
return &pb.SignedMessage{
Data: identity.ID.Bytes(),
Signature: signature,
PublicKey: encodedKey,
}, nil
}
// SignedMessageVerifier checks if provided signed message can be verified
type SignedMessageVerifier func(signature *pb.SignedMessage) error
// NewSignedMessageVerifier creates default implementation of SignedMessageVerifier
func NewSignedMessageVerifier() SignedMessageVerifier {
return func(signedMessage *pb.SignedMessage) error {
if signedMessage == nil {
return Error.New("no message to verify")
}
if signedMessage.Signature == nil {
return Error.New("missing signature for verification")
}
if signedMessage.Data == nil {
return Error.New("missing data for verification")
}
if signedMessage.PublicKey == nil {
return Error.New("missing public key for verification")
}
k, err := pkcrypto.PublicKeyFromPKIX(signedMessage.GetPublicKey())
if err != nil {
return Error.Wrap(err)
}
return pkcrypto.HashAndVerifySignature(k, signedMessage.GetData(), signedMessage.GetSignature())
}
}