1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package rsa_test
6
7import (
8	"bytes"
9	"crypto"
10	"crypto/rand"
11	. "crypto/rsa"
12	"crypto/sha1"
13	"crypto/sha256"
14	"crypto/x509"
15	"encoding/base64"
16	"encoding/hex"
17	"encoding/pem"
18	"io"
19	"testing"
20	"testing/quick"
21)
22
23func decodeBase64(in string) []byte {
24	out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
25	n, err := base64.StdEncoding.Decode(out, []byte(in))
26	if err != nil {
27		return nil
28	}
29	return out[0:n]
30}
31
32type DecryptPKCS1v15Test struct {
33	in, out string
34}
35
36// These test vectors were generated with `openssl rsautl -pkcs -encrypt`
37var decryptPKCS1v15Tests = []DecryptPKCS1v15Test{
38	{
39		"gIcUIoVkD6ATMBk/u/nlCZCCWRKdkfjCgFdo35VpRXLduiKXhNz1XupLLzTXAybEq15juc+EgY5o0DHv/nt3yg==",
40		"x",
41	},
42	{
43		"Y7TOCSqofGhkRb+jaVRLzK8xw2cSo1IVES19utzv6hwvx+M8kFsoWQm5DzBeJCZTCVDPkTpavUuEbgp8hnUGDw==",
44		"testing.",
45	},
46	{
47		"arReP9DJtEVyV2Dg3dDp4c/PSk1O6lxkoJ8HcFupoRorBZG+7+1fDAwT1olNddFnQMjmkb8vxwmNMoTAT/BFjQ==",
48		"testing.\n",
49	},
50	{
51		"WtaBXIoGC54+vH0NH0CHHE+dRDOsMc/6BrfFu2lEqcKL9+uDuWaf+Xj9mrbQCjjZcpQuX733zyok/jsnqe/Ftw==",
52		"01234567890123456789012345678901234567890123456789012",
53	},
54}
55
56func TestDecryptPKCS1v15(t *testing.T) {
57	decryptionFuncs := []func([]byte) ([]byte, error){
58		func(ciphertext []byte) (plaintext []byte, err error) {
59			return DecryptPKCS1v15(nil, rsaPrivateKey, ciphertext)
60		},
61		func(ciphertext []byte) (plaintext []byte, err error) {
62			return rsaPrivateKey.Decrypt(nil, ciphertext, nil)
63		},
64	}
65
66	for _, decryptFunc := range decryptionFuncs {
67		for i, test := range decryptPKCS1v15Tests {
68			out, err := decryptFunc(decodeBase64(test.in))
69			if err != nil {
70				t.Errorf("#%d error decrypting: %v", i, err)
71			}
72			want := []byte(test.out)
73			if !bytes.Equal(out, want) {
74				t.Errorf("#%d got:%#v want:%#v", i, out, want)
75			}
76		}
77	}
78}
79
80func TestEncryptPKCS1v15(t *testing.T) {
81	random := rand.Reader
82	k := (rsaPrivateKey.N.BitLen() + 7) / 8
83
84	tryEncryptDecrypt := func(in []byte, blind bool) bool {
85		if len(in) > k-11 {
86			in = in[0 : k-11]
87		}
88
89		ciphertext, err := EncryptPKCS1v15(random, &rsaPrivateKey.PublicKey, in)
90		if err != nil {
91			t.Errorf("error encrypting: %s", err)
92			return false
93		}
94
95		var rand io.Reader
96		if !blind {
97			rand = nil
98		} else {
99			rand = random
100		}
101		plaintext, err := DecryptPKCS1v15(rand, rsaPrivateKey, ciphertext)
102		if err != nil {
103			t.Errorf("error decrypting: %s", err)
104			return false
105		}
106
107		if !bytes.Equal(plaintext, in) {
108			t.Errorf("output mismatch: %#v %#v", plaintext, in)
109			return false
110		}
111		return true
112	}
113
114	config := new(quick.Config)
115	if testing.Short() {
116		config.MaxCount = 10
117	}
118	quick.Check(tryEncryptDecrypt, config)
119}
120
121// These test vectors were generated with `openssl rsautl -pkcs -encrypt`
122var decryptPKCS1v15SessionKeyTests = []DecryptPKCS1v15Test{
123	{
124		"e6ukkae6Gykq0fKzYwULpZehX+UPXYzMoB5mHQUDEiclRbOTqas4Y0E6nwns1BBpdvEJcilhl5zsox/6DtGsYg==",
125		"1234",
126	},
127	{
128		"Dtis4uk/q/LQGGqGk97P59K03hkCIVFMEFZRgVWOAAhxgYpCRG0MX2adptt92l67IqMki6iVQyyt0TtX3IdtEw==",
129		"FAIL",
130	},
131	{
132		"LIyFyCYCptPxrvTxpol8F3M7ZivlMsf53zs0vHRAv+rDIh2YsHS69ePMoPMe3TkOMZ3NupiL3takPxIs1sK+dw==",
133		"abcd",
134	},
135	{
136		"bafnobel46bKy76JzqU/RIVOH0uAYvzUtauKmIidKgM0sMlvobYVAVQPeUQ/oTGjbIZ1v/6Gyi5AO4DtHruGdw==",
137		"FAIL",
138	},
139}
140
141func TestEncryptPKCS1v15SessionKey(t *testing.T) {
142	for i, test := range decryptPKCS1v15SessionKeyTests {
143		key := []byte("FAIL")
144		err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, decodeBase64(test.in), key)
145		if err != nil {
146			t.Errorf("#%d error decrypting", i)
147		}
148		want := []byte(test.out)
149		if !bytes.Equal(key, want) {
150			t.Errorf("#%d got:%#v want:%#v", i, key, want)
151		}
152	}
153}
154
155func TestEncryptPKCS1v15DecrypterSessionKey(t *testing.T) {
156	for i, test := range decryptPKCS1v15SessionKeyTests {
157		plaintext, err := rsaPrivateKey.Decrypt(rand.Reader, decodeBase64(test.in), &PKCS1v15DecryptOptions{SessionKeyLen: 4})
158		if err != nil {
159			t.Fatalf("#%d: error decrypting: %s", i, err)
160		}
161		if len(plaintext) != 4 {
162			t.Fatalf("#%d: incorrect length plaintext: got %d, want 4", i, len(plaintext))
163		}
164
165		if test.out != "FAIL" && !bytes.Equal(plaintext, []byte(test.out)) {
166			t.Errorf("#%d: incorrect plaintext: got %x, want %x", i, plaintext, test.out)
167		}
168	}
169}
170
171func TestNonZeroRandomBytes(t *testing.T) {
172	random := rand.Reader
173
174	b := make([]byte, 512)
175	err := NonZeroRandomBytes(b, random)
176	if err != nil {
177		t.Errorf("returned error: %s", err)
178	}
179	for _, b := range b {
180		if b == 0 {
181			t.Errorf("Zero octet found")
182			return
183		}
184	}
185}
186
187type signPKCS1v15Test struct {
188	in, out string
189}
190
191// These vectors have been tested with
192//
193//	`openssl rsautl -verify -inkey pk -in signature | hexdump -C`
194var signPKCS1v15Tests = []signPKCS1v15Test{
195	{"Test.\n", "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e336ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"},
196}
197
198func TestSignPKCS1v15(t *testing.T) {
199	for i, test := range signPKCS1v15Tests {
200		h := sha1.New()
201		h.Write([]byte(test.in))
202		digest := h.Sum(nil)
203
204		s, err := SignPKCS1v15(nil, rsaPrivateKey, crypto.SHA1, digest)
205		if err != nil {
206			t.Errorf("#%d %s", i, err)
207		}
208
209		expected, _ := hex.DecodeString(test.out)
210		if !bytes.Equal(s, expected) {
211			t.Errorf("#%d got: %x want: %x", i, s, expected)
212		}
213	}
214}
215
216func TestVerifyPKCS1v15(t *testing.T) {
217	for i, test := range signPKCS1v15Tests {
218		h := sha1.New()
219		h.Write([]byte(test.in))
220		digest := h.Sum(nil)
221
222		sig, _ := hex.DecodeString(test.out)
223
224		err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.SHA1, digest, sig)
225		if err != nil {
226			t.Errorf("#%d %s", i, err)
227		}
228	}
229}
230
231func TestOverlongMessagePKCS1v15(t *testing.T) {
232	ciphertext := decodeBase64("fjOVdirUzFoLlukv80dBllMLjXythIf22feqPrNo0YoIjzyzyoMFiLjAc/Y4krkeZ11XFThIrEvw\nkRiZcCq5ng==")
233	_, err := DecryptPKCS1v15(nil, rsaPrivateKey, ciphertext)
234	if err == nil {
235		t.Error("RSA decrypted a message that was too long.")
236	}
237}
238
239func TestUnpaddedSignature(t *testing.T) {
240	msg := []byte("Thu Dec 19 18:06:16 EST 2013\n")
241	// This base64 value was generated with:
242	// % echo Thu Dec 19 18:06:16 EST 2013 > /tmp/msg
243	// % openssl rsautl -sign -inkey key -out /tmp/sig -in /tmp/msg
244	//
245	// Where "key" contains the RSA private key given at the bottom of this
246	// file.
247	expectedSig := decodeBase64("pX4DR8azytjdQ1rtUiC040FjkepuQut5q2ZFX1pTjBrOVKNjgsCDyiJDGZTCNoh9qpXYbhl7iEym30BWWwuiZg==")
248
249	sig, err := SignPKCS1v15(nil, rsaPrivateKey, crypto.Hash(0), msg)
250	if err != nil {
251		t.Fatalf("SignPKCS1v15 failed: %s", err)
252	}
253	if !bytes.Equal(sig, expectedSig) {
254		t.Fatalf("signature is not expected value: got %x, want %x", sig, expectedSig)
255	}
256	if err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.Hash(0), msg, sig); err != nil {
257		t.Fatalf("signature failed to verify: %s", err)
258	}
259}
260
261func TestShortSessionKey(t *testing.T) {
262	// This tests that attempting to decrypt a session key where the
263	// ciphertext is too small doesn't run outside the array bounds.
264	ciphertext, err := EncryptPKCS1v15(rand.Reader, &rsaPrivateKey.PublicKey, []byte{1})
265	if err != nil {
266		t.Fatalf("Failed to encrypt short message: %s", err)
267	}
268
269	var key [32]byte
270	if err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, ciphertext, key[:]); err != nil {
271		t.Fatalf("Failed to decrypt short message: %s", err)
272	}
273
274	for _, v := range key {
275		if v != 0 {
276			t.Fatal("key was modified when ciphertext was invalid")
277		}
278	}
279}
280
281var rsaPrivateKey = parseKey(testingKey(`-----BEGIN RSA TESTING KEY-----
282MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0
283fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu
284/ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu
285RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/
286EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A
287IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS
288tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V
289-----END RSA TESTING KEY-----`))
290
291func parsePublicKey(s string) *PublicKey {
292	p, _ := pem.Decode([]byte(s))
293	k, err := x509.ParsePKCS1PublicKey(p.Bytes)
294	if err != nil {
295		panic(err)
296	}
297	return k
298}
299
300func TestShortPKCS1v15Signature(t *testing.T) {
301	pub := parsePublicKey(`-----BEGIN RSA PUBLIC KEY-----
302MEgCQQCd9BVzo775lkohasxjnefF1nCMcNoibqIWEVDe/K7M2GSoO4zlSQB+gkix
303O3AnTcdHB51iaZpWfxPSnew8yfulAgMBAAE=
304-----END RSA PUBLIC KEY-----`)
305	sig, err := hex.DecodeString("193a310d0dcf64094c6e3a00c8219b80ded70535473acff72c08e1222974bb24a93a535b1dc4c59fc0e65775df7ba2007dd20e9193f4c4025a18a7070aee93")
306	if err != nil {
307		t.Fatalf("failed to decode signature: %s", err)
308	}
309
310	h := sha256.Sum256([]byte("hello"))
311	err = VerifyPKCS1v15(pub, crypto.SHA256, h[:], sig)
312	if err == nil {
313		t.Fatal("VerifyPKCS1v15 accepted a truncated signature")
314	}
315}
316