Skip to content

Commit

Permalink
Refactor raw ECDSA handling
Browse files Browse the repository at this point in the history
  • Loading branch information
J3imip committed Jan 6, 2025
1 parent 32c6100 commit 9896f64
Showing 1 changed file with 23 additions and 21 deletions.
44 changes: 23 additions & 21 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,37 +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) {
lenToIndex := map[int]int{
28: 14,
32: 16,
48: 24,
56: 28,
64: 32,
96: 48,
132: 66,
}

// Handle raw (r || s) signature format
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
}
return errors.New("failed to verify ECDSA signature in ASN.1 format")
}

// Handle raw (r || s) signature format
var index int
switch len(sig) {
case 132:
index = 66
case 64:
index = 32
case 56:
index = 28
default:
// Handle ASN.1 DER signature format
if ecdsa.VerifyASN1(publicKey, data, sig) {
return nil
}

if !isLenSupported {
return fmt.Errorf(
"unexpected ECDSA signature length, got %d bytes for %s curve",
len(sig),
publicKey.Curve.Params().Name,
)
}

r, s := new(big.Int).SetBytes(sig[:index]), new(big.Int).SetBytes(sig[index:])
if ecdsa.Verify(publicKey, data, r, s) {
return nil
}

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

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

0 comments on commit 9896f64

Please sign in to comment.