github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/crypto/rsa/pkcs1v15_test.go (about)

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