Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle p-224 signature #10

Merged
merged 4 commits into from
Jan 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 26 additions & 12 deletions internal/types/signature_algorithm.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"encoding/asn1"
"fmt"
"hash"
"math/big"
Expand Down Expand Up @@ -53,25 +52,40 @@ func GeneralVerify(publicKey interface{}, hash []byte, signature []byte, algo Al
}

func verifyECDSA(data, sig []byte, publicKey *ecdsa.PublicKey) error {
// Attempt to parse the signature as ASN.1 DER format
if _, err := asn1.Unmarshal(sig, new(asn1.RawValue)); err == nil {
if ecdsa.VerifyASN1(publicKey, data, sig) {
return nil
}
return errors.New("failed to verify ECDSA signature in ASN.1 format")
lenToIndex := map[int]int{
28: 14,
32: 16,
48: 24,
56: 28,
64: 32,
96: 48,
132: 66,
}

// Handle raw (r || s) signature format
if len(sig) != 64 {
return fmt.Errorf("ECDSA signature length is not 64, but %d, with key %s", len(sig), publicKey.Curve.Params().Name)
index, isLenSupported := lenToIndex[len(sig)]
if isLenSupported {
r := new(big.Int).SetBytes(sig[:index])
s := new(big.Int).SetBytes(sig[index:])
if ecdsa.Verify(publicKey, data, r, s) {
return nil
}
}

r, s := new(big.Int).SetBytes(sig[:32]), new(big.Int).SetBytes(sig[32:])
if ecdsa.Verify(publicKey, data, r, s) {
// Handle ASN.1 DER signature format
if ecdsa.VerifyASN1(publicKey, data, sig) {
return nil
}

return errors.New("failed to verify ECDSA signature in raw format")
if !isLenSupported {
return fmt.Errorf(
"unexpected ECDSA signature length, got %d bytes for %s curve",
len(sig),
publicKey.Curve.Params().Name,
)
}

return errors.New("failed to verify ECDSA signature")
}

func GeneralHash(algorithm HashAlgorithm) hash.Hash {
Expand Down
Loading