xref: /aosp_15_r20/external/tink/go/internal/signature/rsassapkcs1_signer_verifier_test.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17package signature_test
18
19import (
20	"crypto/rand"
21	"crypto/rsa"
22	"fmt"
23	"math/big"
24	"testing"
25
26	internal "github.com/google/tink/go/internal/signature"
27	"github.com/google/tink/go/subtle/random"
28	"github.com/google/tink/go/subtle"
29	"github.com/google/tink/go/testutil"
30)
31
32func TestRSASSAPKCS1SignVerify(t *testing.T) {
33	data := random.GetRandomBytes(20)
34	hash := "SHA256"
35	privKey, err := rsa.GenerateKey(rand.Reader, 2048)
36	if err != nil {
37		t.Fatalf("rsa.GenerateKey(rand.Reader, 2048) err = %v, want nil", err)
38	}
39	signer, err := internal.New_RSA_SSA_PKCS1_Signer(hash, privKey)
40	if err != nil {
41		t.Fatalf("New_RSA_SSA_PKCS1_Signer() err = %v, want nil", err)
42	}
43	verifier, err := internal.New_RSA_SSA_PKCS1_Verifier(hash, &privKey.PublicKey)
44	if err != nil {
45		t.Fatalf("New_RSA_SSA_PKCS1_Verifier() err = %v, want nil", err)
46	}
47	signature, err := signer.Sign(data)
48	if err != nil {
49		t.Fatalf("Sign() err = %v, want nil", err)
50	}
51	if err := verifier.Verify(signature, data); err != nil {
52		t.Fatalf("Verify() err = %v, want nil", err)
53	}
54}
55
56func TestRSASSAPKCS1ModifySignatureFails(t *testing.T) {
57	data := random.GetRandomBytes(20)
58	hash := "SHA256"
59	privKey, err := rsa.GenerateKey(rand.Reader, 2048)
60	if err != nil {
61		t.Fatalf("rsa.GenerateKey(rand.Reader, 2048) err = %v, want nil", err)
62	}
63	signer, err := internal.New_RSA_SSA_PKCS1_Signer(hash, privKey)
64	if err != nil {
65		t.Fatalf("New_RSA_SSA_PKCS1_Signer() err = %v, want nil", err)
66	}
67	signature, err := signer.Sign(data)
68	if err != nil {
69		t.Fatalf("Sign() err = %v, want nil", err)
70	}
71	verifier, err := internal.New_RSA_SSA_PKCS1_Verifier(hash, &privKey.PublicKey)
72	if err != nil {
73		t.Fatalf("New_RSA_SSA_PKCS1_Verifier() err = %v, want nil", err)
74	}
75	appendSig := append(signature, 0x01)
76	if err := verifier.Verify(appendSig, data); err == nil {
77		t.Fatalf("Verify() err = nil, want error")
78	}
79	truncSig := signature[:len(signature)-2]
80	if err := verifier.Verify(truncSig, data); err == nil {
81		t.Fatalf("Verify() err = nil, want error")
82	}
83	signature[0] = byte(uint8(signature[0] + 1))
84	if err := verifier.Verify(truncSig, data); err == nil {
85		t.Fatalf("Verify() err = nil, want error")
86	}
87}
88
89func TestNewRSASSAPKCS1SignerVerifierInvalidInput(t *testing.T) {
90	validPrivKey, err := rsa.GenerateKey(rand.Reader, 2048)
91	if err != nil {
92		t.Fatalf("rsa.GenerateKey(rand.Reader, 2048) err = %v, want nil", err)
93	}
94	rsaShortModulusKey, err := rsa.GenerateKey(rand.Reader, 1024)
95	if err != nil {
96		t.Fatalf("decoding rsa short modulus: %v", err)
97	}
98	testCases := []struct {
99		name    string
100		hash    string
101		privKey *rsa.PrivateKey
102	}{
103		{
104			name:    "weak signature hash algorithm",
105			hash:    "SHA1",
106			privKey: validPrivKey,
107		},
108		{
109			name: "invalid public key exponent",
110			hash: "SHA256",
111			privKey: &rsa.PrivateKey{
112				D:           validPrivKey.D,
113				Primes:      validPrivKey.Primes,
114				Precomputed: validPrivKey.Precomputed,
115				PublicKey: rsa.PublicKey{
116					N: validPrivKey.PublicKey.N,
117					E: 3,
118				},
119			},
120		},
121		{
122			name:    "small modulus size",
123			hash:    "SHA256",
124			privKey: rsaShortModulusKey,
125		},
126	}
127	for _, tc := range testCases {
128		t.Run(tc.name, func(t *testing.T) {
129			if _, err := internal.New_RSA_SSA_PKCS1_Signer(tc.hash, tc.privKey); err == nil {
130				t.Errorf("New_RSA_SSA_PKCS1_Signer() err = nil, want error")
131			}
132			if _, err := internal.New_RSA_SSA_PKCS1_Verifier(tc.hash, &tc.privKey.PublicKey); err == nil {
133				t.Errorf("New_RSA_SSA_PKCS1_Verifier() err = nil, want error")
134			}
135		})
136	}
137}
138
139type rsaSSAPKCS1Suite struct {
140	testutil.WycheproofSuite
141	TestGroups []*rsaSSAPKCS1Group `json:"testGroups"`
142}
143
144type rsaSSAPKCS1Group struct {
145	testutil.WycheproofGroup
146	SHA   string             `json:"sha"`
147	E     testutil.HexBytes  `json:"e"`
148	N     testutil.HexBytes  `json:"n"`
149	Type  string             `json:"type"`
150	Tests []*rsaSSAPKCS1Case `json:"tests"`
151}
152
153type rsaSSAPKCS1Case struct {
154	testutil.WycheproofCase
155	Message   testutil.HexBytes `json:"msg"`
156	Signature testutil.HexBytes `json:"sig"`
157}
158
159func TestRSASSAPKCS1WycheproofCases(t *testing.T) {
160	testutil.SkipTestIfTestSrcDirIsNotSet(t)
161
162	testsRan := 0
163	for _, v := range []string{
164		"rsa_signature_2048_sha256_test.json",
165		"rsa_signature_3072_sha512_test.json",
166		"rsa_signature_4096_sha512_test.json",
167	} {
168		suite := &rsaSSAPKCS1Suite{}
169		if err := testutil.PopulateSuite(suite, v); err != nil {
170			t.Fatalf("testutil.PopulateSuite() err = %v, want nil", err)
171		}
172		for _, group := range suite.TestGroups {
173			hash := subtle.ConvertHashName(group.SHA)
174			if hash == "" {
175				t.Fatalf("invalid hash name")
176			}
177			publicKey := &rsa.PublicKey{
178				E: int(new(big.Int).SetBytes(group.E).Uint64()),
179				N: new(big.Int).SetBytes(group.N),
180			}
181			if publicKey.E != 65537 {
182				// golang "crypto/rsa" only supports 65537 as an exponent.
183				if _, err := internal.New_RSA_SSA_PKCS1_Verifier(hash, publicKey); err == nil {
184					t.Errorf("NewRSASSAPKCS1Verifier() err = nil, want error")
185				}
186				continue
187			}
188			verifier, err := internal.New_RSA_SSA_PKCS1_Verifier(hash, publicKey)
189			if err != nil {
190				t.Fatalf("NewRSASSAPKCS1Verifier() err = %v, want nil", err)
191			}
192			for _, test := range group.Tests {
193				caseName := fmt.Sprintf("%s: %s-%s:Case-%d", v, group.Type, group.SHA, test.CaseID)
194				t.Run(caseName, func(t *testing.T) {
195					testsRan++
196					err := verifier.Verify(test.Signature, test.Message)
197					switch test.Result {
198					case "valid":
199						if err != nil {
200							t.Errorf("Verify() err = %v, want nil", err)
201						}
202					case "invalid":
203						if err == nil {
204							t.Errorf("Verify() err = nil, want error")
205						}
206					case "acceptable":
207						// TODO(b/230489047): Inspect flags to appropriately handle acceptable test cases.
208					default:
209						t.Errorf("unsupported test result: %q", test.Result)
210					}
211				})
212			}
213		}
214	}
215	if testsRan != 716 {
216		t.Errorf("testsRan = %d, want = %d", testsRan, 716)
217	}
218}
219