Skip to content

Commit

Permalink
test bad ecdsa crypto signer
Browse files Browse the repository at this point in the history
Signed-off-by: Shiwei Zhang <shizh@microsoft.com>
  • Loading branch information
shizhMSFT committed Aug 19, 2022
1 parent f20fe3b commit 9274c19
Showing 1 changed file with 77 additions and 3 deletions.
80 changes: 77 additions & 3 deletions ecdsa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/asn1"
"errors"
"io"
"math/big"
"reflect"
"testing"
Expand Down Expand Up @@ -212,9 +215,6 @@ func testSignVerify(t *testing.T, alg Algorithm, key crypto.Signer, isCryptoSign
// sign / verify round trip
// see also conformance_test.go for strict tests.
content := []byte("hello world")
if err != nil {
t.Fatalf("Algorithm.computeHash() error = %v", err)
}
sig, err := signer.Sign(rand.Reader, content)
if err != nil {
t.Fatalf("Sign() error = %v", err)
Expand All @@ -229,6 +229,80 @@ func testSignVerify(t *testing.T, alg Algorithm, key crypto.Signer, isCryptoSign
}
}

type ecdsaBadCryptoSigner struct {
crypto.Signer
signature []byte
err error
}

func (s *ecdsaBadCryptoSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
return s.signature, s.err
}

func Test_ecdsaBadCryptoSigner_SignFailure(t *testing.T) {
badSigner := &ecdsaBadCryptoSigner{
Signer: generateTestECDSAKey(t),
err: errors.New("sign failure"),
}
testSignFailure(t, AlgorithmES256, badSigner)
}

func Test_ecdsaBadCryptoSigner_BadSignature(t *testing.T) {
key := generateTestECDSAKey(t)

// nil signature
badSigner := &ecdsaBadCryptoSigner{
Signer: key,
signature: nil,
}
testSignFailure(t, AlgorithmES256, badSigner)

// malformed signature: bad r
sig, err := asn1.Marshal(struct {
R, S *big.Int
}{
R: big.NewInt(-1),
S: big.NewInt(1),
})
if err != nil {
t.Fatalf("asn1.Marshal() error = %v", err)
}
badSigner = &ecdsaBadCryptoSigner{
Signer: key,
signature: sig,
}
testSignFailure(t, AlgorithmES256, badSigner)

// malformed signature: bad s
sig, err = asn1.Marshal(struct {
R, S *big.Int
}{
R: big.NewInt(1),
S: big.NewInt(-1),
})
if err != nil {
t.Fatalf("asn1.Marshal() error = %v", err)
}
badSigner = &ecdsaBadCryptoSigner{
Signer: key,
signature: sig,
}
testSignFailure(t, AlgorithmES256, badSigner)
}

func testSignFailure(t *testing.T, alg Algorithm, key crypto.Signer) {
signer, err := NewSigner(alg, key)
if err != nil {
t.Fatalf("NewSigner() error = %v", err)
}

content := []byte("hello world")
_, err = signer.Sign(rand.Reader, content)
if err == nil {
t.Fatalf("Sign() error = nil, wantErr true")
}
}

func Test_ecdsaVerifier_Verify_Success(t *testing.T) {
// generate key
alg := AlgorithmES256
Expand Down

0 comments on commit 9274c19

Please sign in to comment.