...

Source file src/github.com/ProtonMail/go-crypto/openpgp/packet/private_key_test.go

Documentation: github.com/ProtonMail/go-crypto/openpgp/packet

     1  // Copyright 2011 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 packet
     6  
     7  import (
     8  	"bytes"
     9  	"crypto"
    10  	"crypto/dsa"
    11  	"crypto/elliptic"
    12  	"crypto/rand"
    13  	"crypto/rsa"
    14  	"crypto/x509"
    15  	"encoding/hex"
    16  	"hash"
    17  	"math/big"
    18  	mathrand "math/rand"
    19  	"testing"
    20  	"time"
    21  
    22  	"github.com/ProtonMail/go-crypto/openpgp/ecdsa"
    23  	"github.com/ProtonMail/go-crypto/openpgp/eddsa"
    24  	"github.com/ProtonMail/go-crypto/openpgp/elgamal"
    25  	"github.com/ProtonMail/go-crypto/openpgp/internal/ecc"
    26  	"github.com/ProtonMail/go-crypto/openpgp/s2k"
    27  )
    28  
    29  const maxMessageLength = 1 << 10
    30  
    31  var privateKeyTests = []struct {
    32  	privateKeyHex string
    33  	creationTime  time.Time
    34  }{
    35  	{
    36  		privKeyRSAHex,
    37  		time.Unix(0x4cc349a8, 0),
    38  	},
    39  	{
    40  		privKeyElGamalHex,
    41  		time.Unix(0x4df9ee1a, 0),
    42  	},
    43  }
    44  
    45  func TestExternalPrivateKeyRead(t *testing.T) {
    46  	for i, test := range privateKeyTests {
    47  		packet, err := Read(readerFromHex(test.privateKeyHex))
    48  		if err != nil {
    49  			t.Errorf("#%d: failed to parse: %s", i, err)
    50  			continue
    51  		}
    52  
    53  		privKey := packet.(*PrivateKey)
    54  
    55  		if !privKey.Encrypted {
    56  			t.Errorf("#%d: private key isn't encrypted", i)
    57  			continue
    58  		}
    59  
    60  		err = privKey.Decrypt([]byte("wrong password"))
    61  		if err == nil {
    62  			t.Errorf("#%d: decrypted with incorrect key", i)
    63  			continue
    64  		}
    65  
    66  		err = privKey.Decrypt([]byte("testing"))
    67  		if err != nil {
    68  			t.Errorf("#%d: failed to decrypt: %s", i, err)
    69  			continue
    70  		}
    71  
    72  		if !privKey.CreationTime.Equal(test.creationTime) || privKey.Encrypted {
    73  			t.Errorf("#%d: bad result, got: %#v", i, privKey)
    74  		}
    75  	}
    76  }
    77  
    78  // En/decryption of private keys provided externally, with random passwords
    79  func TestExternalPrivateKeyEncryptDecryptRandomizeSlow(t *testing.T) {
    80  	for i, test := range privateKeyTests {
    81  		packet, err := Read(readerFromHex(test.privateKeyHex))
    82  		if err != nil {
    83  			t.Errorf("#%d: failed to parse: %s", i, err)
    84  			continue
    85  		}
    86  
    87  		privKey := packet.(*PrivateKey)
    88  
    89  		if !privKey.Encrypted {
    90  			t.Errorf("#%d: private key isn't encrypted", i)
    91  			continue
    92  		}
    93  
    94  		// Decrypt with the correct password
    95  		err = privKey.Decrypt([]byte("testing"))
    96  		if err != nil {
    97  			t.Errorf("#%d: failed to decrypt: %s", i, err)
    98  			continue
    99  		}
   100  
   101  		// Encrypt with another (possibly empty) password
   102  		randomPassword := make([]byte, mathrand.Intn(30))
   103  		rand.Read(randomPassword)
   104  		err = privKey.Encrypt(randomPassword)
   105  		if err != nil {
   106  			t.Errorf("#%d: failed to encrypt: %s", i, err)
   107  			continue
   108  		}
   109  
   110  		// Try to decrypt with incorrect password
   111  		incorrect := make([]byte, 1+mathrand.Intn(30))
   112  		for rand.Read(incorrect); bytes.Equal(incorrect, randomPassword); {
   113  			rand.Read(incorrect)
   114  		}
   115  		err = privKey.Decrypt(incorrect)
   116  		if err == nil {
   117  			t.Errorf("#%d: decrypted with incorrect password\nPassword is:%vDecrypted with:%v", i, randomPassword, incorrect)
   118  			continue
   119  		}
   120  
   121  		// Try to decrypt with old password
   122  		err = privKey.Decrypt([]byte("testing"))
   123  		if err == nil {
   124  			t.Errorf("#%d: decrypted with old password", i)
   125  			continue
   126  		}
   127  
   128  		// Decrypt with correct password
   129  		err = privKey.Decrypt(randomPassword)
   130  		if err != nil {
   131  			t.Errorf("#%d: failed to decrypt: %s", i, err)
   132  			continue
   133  		}
   134  
   135  		if !privKey.CreationTime.Equal(test.creationTime) || privKey.Encrypted {
   136  			t.Errorf("#%d: bad result, got: %#v", i, privKey)
   137  		}
   138  	}
   139  }
   140  
   141  func TestExternalPrivateKeyEncryptDecryptArgon2(t *testing.T) {
   142  	config := &Config{
   143  		S2KConfig: &s2k.Config{S2KMode: s2k.Argon2S2K},
   144  	}
   145  	for i, test := range privateKeyTests {
   146  		packet, err := Read(readerFromHex(test.privateKeyHex))
   147  		if err != nil {
   148  			t.Errorf("#%d: failed to parse: %s", i, err)
   149  			continue
   150  		}
   151  
   152  		privKey := packet.(*PrivateKey)
   153  
   154  		if !privKey.Encrypted {
   155  			t.Errorf("#%d: private key isn't encrypted", i)
   156  			continue
   157  		}
   158  
   159  		// Decrypt with the correct password
   160  		err = privKey.Decrypt([]byte("testing"))
   161  		if err != nil {
   162  			t.Errorf("#%d: failed to decrypt: %s", i, err)
   163  			continue
   164  		}
   165  
   166  		// Encrypt with another (possibly empty) password
   167  		randomPassword := make([]byte, mathrand.Intn(30))
   168  		rand.Read(randomPassword)
   169  		err = privKey.EncryptWithConfig(randomPassword, config)
   170  		if err != nil {
   171  			t.Errorf("#%d: failed to encrypt: %s", i, err)
   172  			continue
   173  		}
   174  
   175  		// Try to decrypt with incorrect password
   176  		incorrect := make([]byte, 1+mathrand.Intn(30))
   177  		for rand.Read(incorrect); bytes.Equal(incorrect, randomPassword); {
   178  			rand.Read(incorrect)
   179  		}
   180  		err = privKey.Decrypt(incorrect)
   181  		if err == nil {
   182  			t.Errorf("#%d: decrypted with incorrect password\nPassword is:%vDecrypted with:%v", i, randomPassword, incorrect)
   183  			continue
   184  		}
   185  
   186  		// Try to decrypt with old password
   187  		err = privKey.Decrypt([]byte("testing"))
   188  		if err == nil {
   189  			t.Errorf("#%d: decrypted with old password", i)
   190  			continue
   191  		}
   192  
   193  		// Decrypt with correct password
   194  		err = privKey.Decrypt(randomPassword)
   195  		if err != nil {
   196  			t.Errorf("#%d: failed to decrypt: %s", i, err)
   197  			continue
   198  		}
   199  
   200  		if !privKey.CreationTime.Equal(test.creationTime) || privKey.Encrypted {
   201  			t.Errorf("#%d: bad result, got: %#v", i, privKey)
   202  		}
   203  	}
   204  }
   205  
   206  func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
   207  	h := hashFunc.New()
   208  	if _, err := h.Write(msg); err != nil {
   209  		return nil, err
   210  	}
   211  	return h, nil
   212  }
   213  
   214  func TestExternalRSAPrivateKey(t *testing.T) {
   215  	privKeyDER, _ := hex.DecodeString(pkcs1PrivKeyHex)
   216  	rsaPriv, err := x509.ParsePKCS1PrivateKey(privKeyDER)
   217  	if err != nil {
   218  		t.Fatal(err)
   219  	}
   220  
   221  	var buf bytes.Buffer
   222  	xrsaPriv := &rsa.PrivateKey{
   223  		PublicKey: rsa.PublicKey{
   224  			E: rsaPriv.PublicKey.E,
   225  			N: rsaPriv.PublicKey.N,
   226  		},
   227  		D:      rsaPriv.D,
   228  		Primes: rsaPriv.Primes,
   229  	}
   230  	xrsaPriv.Precompute()
   231  	if err := NewRSAPrivateKey(time.Now(), xrsaPriv).Serialize(&buf); err != nil {
   232  		t.Fatal(err)
   233  	}
   234  
   235  	p, err := Read(&buf)
   236  	if err != nil {
   237  		t.Fatal(err)
   238  	}
   239  
   240  	priv, ok := p.(*PrivateKey)
   241  	if !ok {
   242  		t.Fatal("didn't parse private key")
   243  	}
   244  
   245  	sig := &Signature{
   246  		Version:    4,
   247  		PubKeyAlgo: PubKeyAlgoRSA,
   248  		Hash:       crypto.SHA256,
   249  	}
   250  	for j := 0; j < 256; j++ {
   251  		msg := make([]byte, maxMessageLength)
   252  		rand.Read(msg)
   253  
   254  		h, err := populateHash(sig.Hash, msg)
   255  		if err != nil {
   256  			t.Fatal(err)
   257  		}
   258  		if err := sig.Sign(h, priv, nil); err != nil {
   259  			t.Fatal(err)
   260  		}
   261  
   262  		if h, err = populateHash(sig.Hash, msg); err != nil {
   263  			t.Fatal(err)
   264  		}
   265  		if err := priv.VerifySignature(h, sig); err != nil {
   266  			t.Fatal(err)
   267  		}
   268  	}
   269  }
   270  
   271  func TestECDSAPrivateKeysRandomizeFast(t *testing.T) {
   272  	ecdsaPriv, err := ecdsa.GenerateKey(rand.Reader, ecc.NewGenericCurve(elliptic.P256()))
   273  	if err != nil {
   274  		t.Fatal(err)
   275  	}
   276  
   277  	var buf bytes.Buffer
   278  	if err := NewECDSAPrivateKey(time.Now(), ecdsaPriv).Serialize(&buf); err != nil {
   279  		t.Fatal(err)
   280  	}
   281  
   282  	p, err := Read(&buf)
   283  	if err != nil {
   284  		t.Fatal(err)
   285  	}
   286  
   287  	priv, ok := p.(*PrivateKey)
   288  	if !ok {
   289  		t.Fatal("didn't parse private key")
   290  	}
   291  
   292  	sig := &Signature{
   293  		Version:    4,
   294  		PubKeyAlgo: PubKeyAlgoECDSA,
   295  		Hash:       crypto.SHA256,
   296  	}
   297  	msg := make([]byte, mathrand.Intn(maxMessageLength))
   298  	rand.Read(msg)
   299  
   300  	h, err := populateHash(sig.Hash, msg)
   301  	if err != nil {
   302  		t.Fatal(err)
   303  	}
   304  	if err := sig.Sign(h, priv, nil); err != nil {
   305  		t.Fatal(err)
   306  	}
   307  
   308  	if h, err = populateHash(sig.Hash, msg); err != nil {
   309  		t.Fatal(err)
   310  	}
   311  	if err := priv.VerifySignature(h, sig); err != nil {
   312  		t.Fatal(err)
   313  	}
   314  }
   315  
   316  func TestRSASignerPrivateKeysRandomizeSlow(t *testing.T) {
   317  	// Generate random key
   318  	rsaPriv, err := rsa.GenerateKey(rand.Reader, 1024)
   319  	if err != nil {
   320  		t.Fatal(err)
   321  	}
   322  
   323  	priv := NewSignerPrivateKey(time.Now(), rsaPriv)
   324  
   325  	sig := &Signature{
   326  		Version:    4,
   327  		PubKeyAlgo: PubKeyAlgoRSA,
   328  		Hash:       crypto.SHA256,
   329  	}
   330  
   331  	// Sign random message
   332  	msg := make([]byte, maxMessageLength)
   333  	h, err := populateHash(sig.Hash, msg)
   334  
   335  	if err != nil {
   336  		t.Fatal(err)
   337  	}
   338  	if err := sig.Sign(h, priv, nil); err != nil {
   339  		t.Fatal(err)
   340  	}
   341  
   342  	if h, err = populateHash(sig.Hash, msg); err != nil {
   343  		t.Fatal(err)
   344  	}
   345  
   346  	// Verify signature
   347  	if err := priv.VerifySignature(h, sig); err != nil {
   348  		t.Fatal(err)
   349  	}
   350  
   351  	// Try to verify signature with wrong key
   352  	incorrectRsaPriv, err := rsa.GenerateKey(rand.Reader, 1024)
   353  	if err != nil {
   354  		t.Fatal(err)
   355  	}
   356  	incorrectPriv := NewSignerPrivateKey(time.Now(), incorrectRsaPriv)
   357  	if err = incorrectPriv.VerifySignature(h, sig); err == nil {
   358  		t.Fatalf(
   359  			"Verified signature with incorrect key.\nCorrect key:  \n%v\nIncorrect key:\n%v\nSignature:%v",
   360  			priv, incorrectPriv, sig)
   361  	}
   362  }
   363  
   364  func TestECDSASignerPrivateKeysRandomizeFast(t *testing.T) {
   365  	ecdsaPriv, err := ecdsa.GenerateKey(rand.Reader, ecc.NewGenericCurve(elliptic.P256()))
   366  	if err != nil {
   367  		t.Fatal(err)
   368  	}
   369  
   370  	priv := NewSignerPrivateKey(time.Now(), ecdsaPriv)
   371  
   372  	if priv.PubKeyAlgo != PubKeyAlgoECDSA {
   373  		t.Fatal("NewSignerPrivateKey should have made an ECSDA private key")
   374  	}
   375  
   376  	sig := &Signature{
   377  		Version:    4,
   378  		PubKeyAlgo: PubKeyAlgoECDSA,
   379  		Hash:       crypto.SHA256,
   380  	}
   381  	msg := make([]byte, mathrand.Intn(maxMessageLength))
   382  	rand.Read(msg)
   383  
   384  	h, err := populateHash(sig.Hash, msg)
   385  	if err != nil {
   386  		t.Fatal(err)
   387  	}
   388  	if err := sig.Sign(h, priv, nil); err != nil {
   389  		t.Fatal(err)
   390  	}
   391  
   392  	if h, err = populateHash(sig.Hash, msg); err != nil {
   393  		t.Fatal(err)
   394  	}
   395  	if err := priv.VerifySignature(h, sig); err != nil {
   396  		t.Fatal(err)
   397  	}
   398  }
   399  
   400  func TestEdDSASignerPrivateKeyRandomizeFast(t *testing.T) {
   401  	eddsaPriv, err := eddsa.GenerateKey(rand.Reader, ecc.NewEd25519())
   402  	if err != nil {
   403  		t.Fatal(err)
   404  	}
   405  
   406  	priv := NewSignerPrivateKey(time.Now(), eddsaPriv)
   407  
   408  	if priv.PubKeyAlgo != PubKeyAlgoEdDSA {
   409  		t.Fatal("NewSignerPrivateKey should have made a EdDSA private key")
   410  	}
   411  
   412  	sig := &Signature{
   413  		Version:    4,
   414  		PubKeyAlgo: PubKeyAlgoEdDSA,
   415  		Hash:       crypto.SHA256,
   416  	}
   417  	msg := make([]byte, maxMessageLength)
   418  	rand.Read(msg)
   419  
   420  	h, err := populateHash(sig.Hash, msg)
   421  	if err != nil {
   422  		t.Fatal(err)
   423  	}
   424  	if err := sig.Sign(h, priv, nil); err != nil {
   425  		t.Fatal(err)
   426  	}
   427  	if h, err = populateHash(sig.Hash, msg); err != nil {
   428  		t.Fatal(err)
   429  	}
   430  	if err := priv.VerifySignature(h, sig); err != nil {
   431  		t.Fatal(err)
   432  	}
   433  }
   434  
   435  // Tests correctness when encrypting an EdDSA private key with a password.
   436  func TestEncryptDecryptEdDSAPrivateKeyRandomizeFast(t *testing.T) {
   437  	password := make([]byte, 20)
   438  	_, err := rand.Read(password)
   439  	if err != nil {
   440  		panic(err)
   441  	}
   442  	primaryKey, err := eddsa.GenerateKey(rand.Reader, ecc.NewEd25519())
   443  	if err != nil {
   444  		panic(err)
   445  	}
   446  	privKey := *NewEdDSAPrivateKey(time.Now(), primaryKey)
   447  
   448  	copiedSecret := make([]byte, len(primaryKey.D))
   449  	copy(copiedSecret, privKey.PrivateKey.(*eddsa.PrivateKey).D)
   450  
   451  	// Encrypt private key with random passphrase
   452  	privKey.Encrypt(password)
   453  	// Decrypt and check correctness
   454  	privKey.Decrypt(password)
   455  
   456  	decryptedSecret := privKey.PrivateKey.(*eddsa.PrivateKey).D
   457  	if !bytes.Equal(decryptedSecret, copiedSecret) {
   458  		t.Fatalf("Private key was not correctly decrypted:\ngot:\n%v\nwant:\n%v", decryptedSecret, copiedSecret)
   459  	}
   460  }
   461  
   462  func TestIssue11505(t *testing.T) {
   463  	// parsing a rsa private key with p or q == 1 used to panic due to a divide by zero
   464  	_, _ = Read(readerFromHex("9c3004303030300100000011303030000000000000010130303030303030303030303030303030303030303030303030303030303030303030303030303030303030"))
   465  }
   466  
   467  func TestDSAValidation(t *testing.T) {
   468  	var priv dsa.PrivateKey
   469  	params := &priv.Parameters
   470  	err := dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160)
   471  	if err != nil {
   472  		t.Fatalf("could not generate test params: %s", err)
   473  	}
   474  	err = dsa.GenerateKey(&priv, rand.Reader)
   475  	if err != nil {
   476  		t.Fatalf("could not generate test key: %s", err)
   477  	}
   478  	if err = validateDSAParameters(&priv); err != nil {
   479  		t.Fatalf("valid key marked as invalid: %s", err)
   480  	}
   481  	// g = 1
   482  	g := *priv.G
   483  	priv.G = big.NewInt(1)
   484  	if err = validateDSAParameters(&priv); err == nil {
   485  		t.Fatalf("failed to detect invalid key (g)")
   486  	}
   487  	priv.G = &g
   488  	// corrupt q
   489  	q := *priv.Q
   490  	priv.Q.Sub(priv.Q, big.NewInt(1))
   491  	if err = validateDSAParameters(&priv); err == nil {
   492  		t.Fatalf("failed to detect invalid key (q)")
   493  	}
   494  	priv.Q = &q
   495  	// corrupt y
   496  	y := *priv.Y
   497  	priv.Y.Sub(priv.Y, big.NewInt(1))
   498  	if err = validateDSAParameters(&priv); err == nil {
   499  		t.Fatalf("failed to detect invalid key (y)")
   500  	}
   501  	priv.Y = &y
   502  }
   503  
   504  func TestElGamalValidation(t *testing.T) {
   505  	// we generate dsa key and then reuse values for elgamal
   506  	var dsaPriv dsa.PrivateKey
   507  	params := &dsaPriv.Parameters
   508  	err := dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160)
   509  	if err != nil {
   510  		t.Fatalf("could not generate test params: %s", err)
   511  	}
   512  	err = dsa.GenerateKey(&dsaPriv, rand.Reader)
   513  	if err != nil {
   514  		t.Fatalf("could not generate test key: %s", err)
   515  	}
   516  	// this elgamal key is technically not valid since g has order q < p-1
   517  	// but q is large enough and tests should pass
   518  	var priv elgamal.PrivateKey
   519  	priv.G = dsaPriv.G
   520  	priv.P = dsaPriv.P
   521  	priv.X = dsaPriv.X
   522  	priv.Y = dsaPriv.Y
   523  	if err = validateElGamalParameters(&priv); err != nil {
   524  		t.Fatalf("valid key marked as invalid: %s", err)
   525  	}
   526  	// g = 1
   527  	g := *priv.G
   528  	priv.G = big.NewInt(1)
   529  	if err = validateElGamalParameters(&priv); err == nil {
   530  		t.Fatalf("failed to detect invalid key (g)")
   531  	}
   532  	// g of order 2: g**(p-1)/2
   533  	pSub1 := new(big.Int).Sub(priv.P, big.NewInt(1))
   534  	pSub1Div2 := new(big.Int).Rsh(pSub1, 1)
   535  	priv.G = new(big.Int).Exp(&g, pSub1Div2, priv.P)
   536  	if err = validateElGamalParameters(&priv); err == nil {
   537  		t.Fatalf("failed to detect invalid key (g small order)")
   538  	}
   539  	priv.G = &g
   540  	// corrupt y
   541  	y := *priv.Y
   542  	priv.Y.Sub(priv.Y, big.NewInt(1))
   543  	if err = validateElGamalParameters(&priv); err == nil {
   544  		t.Fatalf("failed to detect invalid key (y)")
   545  	}
   546  	priv.Y = &y
   547  }
   548  

View as plain text