...

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

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

     1  package openpgp
     2  
     3  import (
     4  	"bytes"
     5  	"crypto"
     6  	"crypto/dsa"
     7  	"crypto/rand"
     8  	"crypto/rsa"
     9  	"fmt"
    10  	"math/big"
    11  	"strconv"
    12  	"strings"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/ProtonMail/go-crypto/openpgp/armor"
    17  	"github.com/ProtonMail/go-crypto/openpgp/ecdh"
    18  	"github.com/ProtonMail/go-crypto/openpgp/ecdsa"
    19  	"github.com/ProtonMail/go-crypto/openpgp/eddsa"
    20  	"github.com/ProtonMail/go-crypto/openpgp/elgamal"
    21  	"github.com/ProtonMail/go-crypto/openpgp/errors"
    22  	"github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
    23  	"github.com/ProtonMail/go-crypto/openpgp/packet"
    24  	"github.com/ProtonMail/go-crypto/openpgp/s2k"
    25  )
    26  
    27  var hashes = []crypto.Hash{
    28  	crypto.SHA1,
    29  	crypto.SHA224,
    30  	crypto.SHA256,
    31  	crypto.SHA384,
    32  	crypto.SHA512,
    33  	crypto.SHA3_256,
    34  	crypto.SHA3_512,
    35  }
    36  
    37  var ciphers = []packet.CipherFunction{
    38  	packet.Cipher3DES,
    39  	packet.CipherCAST5,
    40  	packet.CipherAES128,
    41  	packet.CipherAES192,
    42  	packet.CipherAES256,
    43  }
    44  
    45  var aeadModes = []packet.AEADMode{
    46  	packet.AEADModeOCB,
    47  	packet.AEADModeEAX,
    48  	packet.AEADModeGCM,
    49  }
    50  
    51  func TestKeyExpiry(t *testing.T) {
    52  	kring, err := ReadKeyRing(readerFromHex(expiringKeyHex))
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	entity := kring[0]
    57  
    58  	const timeFormat = "2006-01-02"
    59  	time1, _ := time.Parse(timeFormat, "2013-07-02")
    60  
    61  	// The expiringKeyHex key is structured as:
    62  	//
    63  	// pub  1024R/5E237D8C  created: 2013-07-01                      expires: 2013-07-31  usage: SC
    64  	// sub  1024R/1ABB25A0  created: 2013-07-01 23:11:07 +0200 CEST  expires: 2013-07-08  usage: E
    65  	// sub  1024R/96A672F5  created: 2013-07-01 23:11:23 +0200 CEST  expires: 2013-07-31  usage: E
    66  	//
    67  	// So this should select the newest, non-expired encryption key.
    68  	key, ok := entity.EncryptionKey(time1)
    69  	if !ok {
    70  		t.Fatal("No encryption key found")
    71  	}
    72  	if id, expected := key.PublicKey.KeyIdShortString(), "CD3D39FF"; id != expected {
    73  		t.Errorf("Expected key %s at time %s, but got key %s", expected, time1.Format(timeFormat), id)
    74  	}
    75  
    76  	// Once the first encryption subkey has expired, the second should be
    77  	// selected.
    78  	time2, _ := time.Parse(timeFormat, "2013-07-09")
    79  	key, _ = entity.EncryptionKey(time2)
    80  	if id, expected := key.PublicKey.KeyIdShortString(), "CD3D39FF"; id != expected {
    81  		t.Errorf("Expected key %s at time %s, but got key %s", expected, time2.Format(timeFormat), id)
    82  	}
    83  
    84  	// Once all the keys have expired, nothing should be returned.
    85  	time3, _ := time.Parse(timeFormat, "2013-08-01")
    86  	if key, ok := entity.EncryptionKey(time3); ok {
    87  		t.Errorf("Expected no key at time %s, but got key %s", time3.Format(timeFormat), key.PublicKey.KeyIdShortString())
    88  	}
    89  }
    90  
    91  // https://tests.sequoia-pgp.org/#Certificate_expiration
    92  // P _ U f
    93  func TestExpiringPrimaryUIDKey(t *testing.T) {
    94  	// P _ U f
    95  	kring, err := ReadArmoredKeyRing(bytes.NewBufferString((expiringPrimaryUIDKey)))
    96  	if err != nil {
    97  		t.Fatal(err)
    98  	}
    99  	entity := kring[0]
   100  
   101  	const timeFormat string = "2006-01-02"
   102  	const expectedKeyID string = "015E7330"
   103  
   104  	// Before the primary UID has expired, the primary key should be returned.
   105  	time1, err := time.Parse(timeFormat, "2022-02-05")
   106  	if err != nil {
   107  		t.Fatal(err)
   108  	}
   109  	key, found := entity.SigningKey(time1)
   110  	if !found {
   111  		t.Errorf("Signing subkey %s not found at time %s", expectedKeyID, time1.Format(timeFormat))
   112  	} else if observedKeyID := key.PublicKey.KeyIdShortString(); observedKeyID != expectedKeyID {
   113  		t.Errorf("Expected key %s at time %s, but got key %s", expectedKeyID, time1.Format(timeFormat), observedKeyID)
   114  	}
   115  
   116  	// After the primary UID has expired, nothing should be returned.
   117  	time2, err := time.Parse(timeFormat, "2022-02-06")
   118  	if err != nil {
   119  		t.Fatal(err)
   120  	}
   121  	if key, ok := entity.SigningKey(time2); ok {
   122  		t.Errorf("Expected no key at time %s, but got key %s", time2.Format(timeFormat), key.PublicKey.KeyIdShortString())
   123  	}
   124  }
   125  
   126  func TestReturnNewestUnexpiredSigningSubkey(t *testing.T) {
   127  	// Make a master key.
   128  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
   129  	if err != nil {
   130  		t.Fatal(err)
   131  	}
   132  
   133  	// First signing subkey does not expire.
   134  	err = entity.AddSigningSubkey(nil)
   135  	if err != nil {
   136  		t.Fatal(err)
   137  	}
   138  	// Get the first signing subkey (added after the default encryption subkey).
   139  	subkey1 := entity.Subkeys[1]
   140  
   141  	// Second signing subkey expires in a day.
   142  	err = entity.AddSigningSubkey(&packet.Config{
   143  		Time: func() time.Time {
   144  			return time.Now().Add(1 * time.Second)
   145  		},
   146  		KeyLifetimeSecs: 24 * 60 * 60,
   147  	})
   148  	if err != nil {
   149  		t.Fatal(err)
   150  	}
   151  	// Get the second signing subkey.
   152  	subkey2 := entity.Subkeys[2]
   153  
   154  	// Before second signing subkey has expired, it should be returned.
   155  	time1 := time.Now().Add(2 * time.Second)
   156  	expected := subkey2.PublicKey.KeyIdShortString()
   157  	subkey, found := entity.SigningKey(time1)
   158  	if !found {
   159  		t.Errorf("Signing subkey %s not found at time %s", expected, time1.Format(time.UnixDate))
   160  	}
   161  	observed := subkey.PublicKey.KeyIdShortString()
   162  	if observed != expected {
   163  		t.Errorf("Expected key %s at time %s, but got key %s", expected, time1.Format(time.UnixDate), observed)
   164  	}
   165  
   166  	// After the second signing subkey has expired, the first one should be returned.
   167  	time2 := time1.AddDate(0, 0, 2)
   168  	expected = subkey1.PublicKey.KeyIdShortString()
   169  	subkey, found = entity.SigningKey(time2)
   170  	if !found {
   171  		t.Errorf("Signing subkey %s not found at time %s", expected, time2.Format(time.UnixDate))
   172  	}
   173  	observed = subkey.PublicKey.KeyIdShortString()
   174  	if observed != expected {
   175  		t.Errorf("Expected key %s at time %s, but got key %s", expected, time2.Format(time.UnixDate), observed)
   176  	}
   177  }
   178  
   179  func TestSignatureExpiry(t *testing.T) {
   180  	// Make a master key, and attach it to a keyring.
   181  	var keyring EntityList
   182  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
   183  	if err != nil {
   184  		t.Fatal(err)
   185  	}
   186  	keyring = append(keyring, entity)
   187  
   188  	// Make a signature that never expires.
   189  	var signatureWriter1 bytes.Buffer
   190  	const input string = "Hello, world!"
   191  	message := strings.NewReader(input)
   192  	err = ArmoredDetachSign(&signatureWriter1, entity, message, nil)
   193  	if err != nil {
   194  		t.Fatal(err)
   195  	}
   196  
   197  	// Make a signature that expires in a day.
   198  	var signatureWriter2 bytes.Buffer
   199  	message = strings.NewReader(input)
   200  	err = ArmoredDetachSign(&signatureWriter2, entity, message, &packet.Config{
   201  		SigLifetimeSecs: 24 * 60 * 60,
   202  	})
   203  	if err != nil {
   204  		t.Fatal(err)
   205  	}
   206  
   207  	// Make a time that is day after tomorrow.
   208  	futureTime := func() time.Time {
   209  		return time.Now().AddDate(0, 0, 2)
   210  	}
   211  
   212  	// Make a signature that was created in the future.
   213  	var signatureWriter3 bytes.Buffer
   214  	message = strings.NewReader(input)
   215  	err = ArmoredDetachSign(&signatureWriter3, entity, message, &packet.Config{
   216  		Time: futureTime,
   217  	})
   218  	if err != nil {
   219  		t.Fatal(err)
   220  	}
   221  
   222  	// Check that the first signature has not expired day after tomorrow.
   223  	message = strings.NewReader(input)
   224  	signatureReader1 := strings.NewReader(signatureWriter1.String())
   225  	_, err = CheckArmoredDetachedSignature(keyring, message, signatureReader1, &packet.Config{
   226  		Time: futureTime,
   227  	})
   228  	if err != nil {
   229  		t.Fatal(err)
   230  	}
   231  
   232  	// Check that the second signature has expired day after tomorrow.
   233  	message = strings.NewReader(input)
   234  	signatureReader2 := strings.NewReader(signatureWriter2.String())
   235  	const expectedErr string = "openpgp: signature expired"
   236  	_, observedErr := CheckArmoredDetachedSignature(keyring, message, signatureReader2, &packet.Config{
   237  		Time: futureTime,
   238  	})
   239  	if observedErr.Error() != expectedErr {
   240  		t.Errorf("Expected error '%s', but got error '%s'", expectedErr, observedErr)
   241  	}
   242  
   243  	// Check that the third signature is also considered expired even now.
   244  	message = strings.NewReader(input)
   245  	signatureReader3 := strings.NewReader(signatureWriter3.String())
   246  	_, observedErr = CheckArmoredDetachedSignature(keyring, message, signatureReader3, nil)
   247  	if observedErr.Error() != expectedErr {
   248  		t.Errorf("Expected error '%s', but got error '%s'", expectedErr, observedErr)
   249  	}
   250  }
   251  
   252  func TestMissingCrossSignature(t *testing.T) {
   253  	// This public key has a signing subkey, but the subkey does not
   254  	// contain a cross-signature.
   255  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(missingCrossSignatureKey))
   256  	if len(keys) != 0 {
   257  		t.Errorf("Accepted key with missing cross signature")
   258  	}
   259  	if err == nil {
   260  		t.Fatal("Failed to detect error in keyring with missing cross signature")
   261  	}
   262  	structural, ok := err.(errors.StructuralError)
   263  	if !ok {
   264  		t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
   265  	}
   266  	const expectedMsg = "signing subkey is missing cross-signature"
   267  	if !strings.Contains(string(structural), expectedMsg) {
   268  		t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
   269  	}
   270  }
   271  
   272  func TestInvalidCrossSignature(t *testing.T) {
   273  	// This public key has a signing subkey, and the subkey has an
   274  	// embedded cross-signature. However, the cross-signature does
   275  	// not correctly validate over the primary and subkey.
   276  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(invalidCrossSignatureKey))
   277  	if len(keys) != 0 {
   278  		t.Errorf("Accepted key with invalid cross signature")
   279  	}
   280  	if err == nil {
   281  		t.Fatal("Failed to detect error in keyring with an invalid cross signature")
   282  	}
   283  	structural, ok := err.(errors.StructuralError)
   284  	if !ok {
   285  		t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
   286  	}
   287  	const expectedMsg = "subkey signature invalid"
   288  	if !strings.Contains(string(structural), expectedMsg) {
   289  		t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
   290  	}
   291  }
   292  
   293  func TestGoodCrossSignature(t *testing.T) {
   294  	// This public key has a signing subkey, and the subkey has an
   295  	// embedded cross-signature which correctly validates over the
   296  	// primary and subkey.
   297  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(goodCrossSignatureKey))
   298  	if err != nil {
   299  		t.Fatal(err)
   300  	}
   301  	if len(keys) != 1 {
   302  		t.Errorf("Failed to accept key with good cross signature, %d", len(keys))
   303  	}
   304  	if len(keys[0].Subkeys) != 1 {
   305  		t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
   306  	}
   307  }
   308  
   309  func TestRevokedUserID(t *testing.T) {
   310  	// This key contains 2 UIDs, one of which is revoked and has no valid self-signature:
   311  	// [ultimate] (1)  Golang Gopher <no-reply@golang.com>
   312  	// [ revoked] (2)  Golang Gopher <revoked@golang.com>
   313  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(revokedUserIDKey))
   314  	if err != nil {
   315  		t.Fatal(err)
   316  	}
   317  
   318  	if len(keys) != 1 {
   319  		t.Fatal("Failed to read key with a revoked user id")
   320  	}
   321  
   322  	identities := keys[0].Identities
   323  
   324  	if numIdentities, numExpected := len(identities), 2; numIdentities != numExpected {
   325  		t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
   326  	}
   327  
   328  	firstIdentity, found := identities["Golang Gopher <no-reply@golang.com>"]
   329  	if !found {
   330  		t.Errorf("missing first identity")
   331  	}
   332  
   333  	secondIdentity, found := identities["Golang Gopher <revoked@golang.com>"]
   334  	if !found {
   335  		t.Errorf("missing second identity")
   336  	}
   337  
   338  	if firstIdentity.Revoked(time.Now()) {
   339  		t.Errorf("expected first identity not to be revoked")
   340  	}
   341  
   342  	if !secondIdentity.Revoked(time.Now()) {
   343  		t.Errorf("expected second identity to be revoked")
   344  	}
   345  
   346  	const timeFormat = "2006-01-02"
   347  	time1, _ := time.Parse(timeFormat, "2020-01-01")
   348  
   349  	if _, found := keys[0].SigningKey(time1); !found {
   350  		t.Errorf("Expected SigningKey to return a signing key when one User IDs is revoked")
   351  	}
   352  
   353  	if _, found := keys[0].EncryptionKey(time1); !found {
   354  		t.Errorf("Expected EncryptionKey to return an encryption key when one User IDs is revoked")
   355  	}
   356  }
   357  
   358  func TestFirstUserIDRevoked(t *testing.T) {
   359  	// Same test as above, but with the User IDs reversed:
   360  	// [ revoked] (1)  Golang Gopher <revoked@golang.com>
   361  	// [ultimate] (2)  Golang Gopher <no-reply@golang.com>
   362  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithFirstUserIDRevoked))
   363  	if err != nil {
   364  		t.Fatal(err)
   365  	}
   366  
   367  	if len(keys) != 1 {
   368  		t.Fatal("Failed to read key with a revoked user id")
   369  	}
   370  
   371  	identities := keys[0].Identities
   372  
   373  	if numIdentities, numExpected := len(identities), 2; numIdentities != numExpected {
   374  		t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
   375  	}
   376  
   377  	firstIdentity, found := identities["Golang Gopher <revoked@golang.com>"]
   378  	if !found {
   379  		t.Errorf("missing first identity")
   380  	}
   381  
   382  	secondIdentity, found := identities["Golang Gopher <no-reply@golang.com>"]
   383  	if !found {
   384  		t.Errorf("missing second identity")
   385  	}
   386  
   387  	if !firstIdentity.Revoked(time.Now()) {
   388  		t.Errorf("expected first identity to be revoked")
   389  	}
   390  
   391  	if secondIdentity.Revoked(time.Now()) {
   392  		t.Errorf("expected second identity not to be revoked")
   393  	}
   394  
   395  	const timeFormat = "2006-01-02"
   396  	time1, _ := time.Parse(timeFormat, "2020-01-01")
   397  
   398  	if _, found := keys[0].SigningKey(time1); !found {
   399  		t.Errorf("Expected SigningKey to return a signing key when first User IDs is revoked")
   400  	}
   401  
   402  	if _, found := keys[0].EncryptionKey(time1); !found {
   403  		t.Errorf("Expected EncryptionKey to return an encryption key when first User IDs is revoked")
   404  	}
   405  }
   406  
   407  func TestOnlyUserIDRevoked(t *testing.T) {
   408  	// This key contains 1 UID which is revoked (but also has a self-signature)
   409  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithOnlyUserIDRevoked))
   410  	if err != nil {
   411  		t.Fatal(err)
   412  	}
   413  
   414  	if len(keys) != 1 {
   415  		t.Fatal("Failed to read key with a revoked user id")
   416  	}
   417  
   418  	identities := keys[0].Identities
   419  
   420  	if numIdentities, numExpected := len(identities), 1; numIdentities != numExpected {
   421  		t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
   422  	}
   423  
   424  	identity, found := identities["Revoked Primary User ID <revoked@key.com>"]
   425  	if !found {
   426  		t.Errorf("missing identity")
   427  	}
   428  
   429  	if !identity.Revoked(time.Now()) {
   430  		t.Errorf("expected identity to be revoked")
   431  	}
   432  
   433  	if _, found := keys[0].SigningKey(time.Now()); found {
   434  		t.Errorf("Expected SigningKey not to return a signing key when the only User IDs is revoked")
   435  	}
   436  
   437  	if _, found := keys[0].EncryptionKey(time.Now()); found {
   438  		t.Errorf("Expected EncryptionKey not to return an encryption key when the only User IDs is revoked")
   439  	}
   440  }
   441  
   442  func TestDummyPrivateKey(t *testing.T) {
   443  	// This public key has a signing subkey, but has a dummy placeholder
   444  	// instead of the real private key. It's used in scenarios where the
   445  	// main private key is withheld and only signing is allowed (e.g. build
   446  	// servers).
   447  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(onlySubkeyNoPrivateKey))
   448  	if err != nil {
   449  		t.Fatal(err)
   450  	}
   451  	if len(keys) != 1 {
   452  		t.Errorf("Failed to accept key with dummy private key, %d", len(keys))
   453  	}
   454  	if !keys[0].PrivateKey.Dummy() {
   455  		t.Errorf("Primary private key should be marked as a dummy key")
   456  	}
   457  	if len(keys[0].Subkeys) != 1 {
   458  		t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
   459  	}
   460  
   461  	// Test serialization of stub private key via entity.SerializePrivate().
   462  	var buf bytes.Buffer
   463  	w, err := armor.Encode(&buf, PrivateKeyType, nil)
   464  	if err != nil {
   465  		t.Errorf("Failed top initialise armored key writer")
   466  	}
   467  	err = keys[0].SerializePrivateWithoutSigning(w, nil)
   468  	if err != nil {
   469  		t.Errorf("Failed to serialize entity")
   470  	}
   471  	if w.Close() != nil {
   472  		t.Errorf("Failed to close writer for armored key")
   473  	}
   474  
   475  	keys, err = ReadArmoredKeyRing(bytes.NewBufferString(buf.String()))
   476  	if err != nil {
   477  		t.Fatal(err)
   478  	}
   479  	if len(keys) != 1 {
   480  		t.Errorf("Failed to accept key with dummy private key, %d", len(keys))
   481  	}
   482  	if !keys[0].PrivateKey.Dummy() {
   483  		t.Errorf("Primary private key should be marked as a dummy key after serialisation")
   484  	}
   485  	if len(keys[0].Subkeys) != 1 {
   486  		t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
   487  	}
   488  }
   489  
   490  // TestExternallyRevokableKey attempts to load and parse a key with a third party revocation permission.
   491  func TestExternallyRevocableKey(t *testing.T) {
   492  	kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
   493  	if err != nil {
   494  		t.Fatal(err)
   495  	}
   496  
   497  	// The 0xA42704B92866382A key can be revoked by 0xBE3893CB843D0FE70C
   498  	// according to this signature that appears within the key:
   499  	// :signature packet: algo 1, keyid A42704B92866382A
   500  	//    version 4, created 1396409682, md5len 0, sigclass 0x1f
   501  	//    digest algo 2, begin of digest a9 84
   502  	//    hashed subpkt 2 len 4 (sig created 2014-04-02)
   503  	//    hashed subpkt 12 len 22 (revocation key: c=80 a=1 f=CE094AA433F7040BB2DDF0BE3893CB843D0FE70C)
   504  	//    hashed subpkt 7 len 1 (not revocable)
   505  	//    subpkt 16 len 8 (issuer key ID A42704B92866382A)
   506  	//    data: [1024 bits]
   507  
   508  	id := uint64(0xA42704B92866382A)
   509  	keys := kring.KeysById(id)
   510  	if len(keys) != 1 {
   511  		t.Errorf("Expected to find key id %X, but got %d matches", id, len(keys))
   512  	}
   513  }
   514  
   515  func TestKeyRevocation(t *testing.T) {
   516  	kring, err := ReadKeyRing(readerFromHex(revokedKeyHex))
   517  	if err != nil {
   518  		t.Fatal(err)
   519  	}
   520  
   521  	if len(kring) != 1 {
   522  		t.Fatal("Failed to read key with a sub key")
   523  	}
   524  
   525  	// revokedKeyHex contains these keys:
   526  	// pub   1024R/9A34F7C0 2014-03-25 [revoked: 2014-03-25]
   527  	// sub   1024R/1BA3CD60 2014-03-25 [revoked: 2014-03-25]
   528  	ids := []uint64{0xA401D9F09A34F7C0, 0x5CD3BE0A1BA3CD60}
   529  
   530  	for _, id := range ids {
   531  		keys := kring.KeysById(id)
   532  		if len(keys) != 1 {
   533  			t.Errorf("Expected KeysById to find revoked key %X, but got %d matches", id, len(keys))
   534  		}
   535  		keys = kring.KeysByIdUsage(id, 0)
   536  		if len(keys) != 1 {
   537  			t.Errorf("Expected KeysByIdUsage to find revoked key %X, but got %d matches", id, len(keys))
   538  		}
   539  	}
   540  
   541  	signingkey, found := kring[0].SigningKey(time.Now())
   542  	if found {
   543  		t.Errorf("Expected SigningKey not to return a signing key for a revoked key, got %X", signingkey.PublicKey.KeyId)
   544  	}
   545  
   546  	encryptionkey, found := kring[0].EncryptionKey(time.Now())
   547  	if found {
   548  		t.Errorf("Expected EncryptionKey not to return an encryption key for a revoked key, got %X", encryptionkey.PublicKey.KeyId)
   549  	}
   550  }
   551  
   552  func TestKeyWithRevokedSubKey(t *testing.T) {
   553  	// This key contains a revoked sub key:
   554  	//  pub   rsa1024/0x4CBD826C39074E38 2018-06-14 [SC]
   555  	//        Key fingerprint = 3F95 169F 3FFA 7D3F 2B47  6F0C 4CBD 826C 3907 4E38
   556  	//  uid   Golang Gopher <no-reply@golang.com>
   557  	//  sub   rsa1024/0x945DB1AF61D85727 2018-06-14 [S] [revoked: 2018-06-14]
   558  
   559  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKey))
   560  	if err != nil {
   561  		t.Fatal(err)
   562  	}
   563  
   564  	if len(keys) != 1 {
   565  		t.Fatal("Failed to read key with a sub key")
   566  	}
   567  
   568  	identity := keys[0].Identities["Golang Gopher <no-reply@golang.com>"]
   569  	// Test for an issue where Subkey Binding Signatures (RFC 4880 5.2.1) were added to the identity
   570  	// preceding the Subkey Packet if the Subkey Packet was followed by more than one signature.
   571  	// For example, the current key has the following layout:
   572  	//    PUBKEY UID SELFSIG SUBKEY REV SELFSIG
   573  	// The last SELFSIG would be added to the UID's signatures. This is wrong.
   574  	if numSigs, numExpected := len(identity.Signatures), 1; numSigs != numExpected {
   575  		t.Fatalf("got %d signatures, expected %d", numSigs, numExpected)
   576  	}
   577  
   578  	if numSubKeys, numExpected := len(keys[0].Subkeys), 1; numSubKeys != numExpected {
   579  		t.Fatalf("got %d subkeys, expected %d", numSubKeys, numExpected)
   580  	}
   581  
   582  	subKey := keys[0].Subkeys[0]
   583  	if subKey.Sig == nil {
   584  		t.Fatalf("subkey signature is nil")
   585  	}
   586  
   587  }
   588  
   589  func TestSubkeyRevocation(t *testing.T) {
   590  	kring, err := ReadKeyRing(readerFromHex(revokedSubkeyHex))
   591  	if err != nil {
   592  		t.Fatal(err)
   593  	}
   594  
   595  	if len(kring) != 1 {
   596  		t.Fatal("Failed to read key with a sub key")
   597  	}
   598  
   599  	// revokedSubkeyHex contains these keys:
   600  	// pub   1024R/4EF7E4BECCDE97F0 2014-03-25
   601  	// sub   1024R/D63636E2B96AE423 2014-03-25
   602  	// sub   1024D/DBCE4EE19529437F 2014-03-25
   603  	// sub   1024R/677815E371C2FD23 2014-03-25 [revoked: 2014-03-25]
   604  	validKeys := []uint64{0x4EF7E4BECCDE97F0, 0xD63636E2B96AE423, 0xDBCE4EE19529437F}
   605  	encryptionKey := uint64(0xD63636E2B96AE423)
   606  	revokedKey := uint64(0x677815E371C2FD23)
   607  
   608  	for _, id := range validKeys {
   609  		keys := kring.KeysById(id)
   610  		if len(keys) != 1 {
   611  			t.Errorf("Expected KeysById to find key %X, but got %d matches", id, len(keys))
   612  		}
   613  		keys = kring.KeysByIdUsage(id, 0)
   614  		if len(keys) != 1 {
   615  			t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", id, len(keys))
   616  		}
   617  		if id == encryptionKey {
   618  			key, found := kring[0].EncryptionKey(time.Now())
   619  			if !found || key.PublicKey.KeyId != id {
   620  				t.Errorf("Expected EncryptionKey to find key %X", id)
   621  			}
   622  		} else {
   623  			_, found := kring[0].SigningKeyById(time.Now(), id)
   624  			if !found {
   625  				t.Errorf("Expected SigningKeyById to find key %X", id)
   626  			}
   627  		}
   628  	}
   629  
   630  	keys := kring.KeysById(revokedKey)
   631  	if len(keys) != 1 {
   632  		t.Errorf("Expected KeysById to find key %X, but got %d matches", revokedKey, len(keys))
   633  	}
   634  
   635  	keys = kring.KeysByIdUsage(revokedKey, 0)
   636  	if len(keys) != 1 {
   637  		t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", revokedKey, len(keys))
   638  	}
   639  
   640  	signingkey, found := kring[0].SigningKeyById(time.Now(), revokedKey)
   641  	if found {
   642  		t.Errorf("Expected SigningKeyById not to return an encryption key for a revoked key, got %X", signingkey.PublicKey.KeyId)
   643  	}
   644  }
   645  
   646  func TestKeyWithSubKeyAndBadSelfSigOrder(t *testing.T) {
   647  	// This key was altered so that the self signatures following the
   648  	// subkey are in a sub-optimal order.
   649  	//
   650  	// Note: Should someone have to create a similar key again, look into
   651  	//       gpgsplit, gpg --dearmor, and gpg --enarmor.
   652  	//
   653  	// The packet ordering is the following:
   654  	//    PUBKEY UID UIDSELFSIG SUBKEY SELFSIG1 SELFSIG2
   655  	//
   656  	// Where:
   657  	//    SELFSIG1 expires on 2018-06-14 and was created first
   658  	//    SELFSIG2 does not expire and was created after SELFSIG1
   659  	//
   660  	// Test for RFC 4880 5.2.3.3:
   661  	// > An implementation that encounters multiple self-signatures on the
   662  	// > same object may resolve the ambiguity in any way it sees fit, but it
   663  	// > is RECOMMENDED that priority be given to the most recent self-
   664  	// > signature.
   665  	//
   666  	// This means that we should keep SELFSIG2.
   667  
   668  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKeyAndBadSelfSigOrder))
   669  	if err != nil {
   670  		t.Fatal(err)
   671  	}
   672  
   673  	if len(keys) != 1 {
   674  		t.Fatal("Failed to read key with a sub key and a bad selfsig packet order")
   675  	}
   676  
   677  	key := keys[0]
   678  
   679  	if numKeys, expected := len(key.Subkeys), 1; numKeys != expected {
   680  		t.Fatalf("Read %d subkeys, expected %d", numKeys, expected)
   681  	}
   682  
   683  	subKey := key.Subkeys[0]
   684  
   685  	if lifetime := subKey.Sig.KeyLifetimeSecs; lifetime != nil {
   686  		t.Errorf("The signature has a key lifetime (%d), but it should be nil", *lifetime)
   687  	}
   688  
   689  }
   690  
   691  func TestKeyUsage(t *testing.T) {
   692  	kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
   693  	if err != nil {
   694  		t.Fatal(err)
   695  	}
   696  
   697  	// subkeyUsageHex contains these keys:
   698  	// pub  1024R/2866382A  created: 2014-04-01  expires: never       usage: SC
   699  	// sub  1024R/936C9153  created: 2014-04-01  expires: never       usage: E
   700  	// sub  1024R/64D5F5BB  created: 2014-04-02  expires: never       usage: E
   701  	// sub  1024D/BC0BA992  created: 2014-04-02  expires: never       usage: S
   702  	certifiers := []uint64{0xA42704B92866382A}
   703  	signers := []uint64{0xA42704B92866382A, 0x42CE2C64BC0BA992}
   704  	encrypters := []uint64{0x09C0C7D9936C9153, 0xC104E98664D5F5BB}
   705  
   706  	for _, id := range certifiers {
   707  		keys := kring.KeysByIdUsage(id, packet.KeyFlagCertify)
   708  		if len(keys) == 1 {
   709  			if keys[0].PublicKey.KeyId != id {
   710  				t.Errorf("Expected to find certifier key id %X, but got %X", id, keys[0].PublicKey.KeyId)
   711  			}
   712  		} else {
   713  			t.Errorf("Expected one match for certifier key id %X, but got %d matches", id, len(keys))
   714  		}
   715  	}
   716  
   717  	for _, id := range signers {
   718  		keys := kring.KeysByIdUsage(id, packet.KeyFlagSign)
   719  		if len(keys) == 1 {
   720  			if keys[0].PublicKey.KeyId != id {
   721  				t.Errorf("Expected to find signing key id %X, but got %X", id, keys[0].PublicKey.KeyId)
   722  			}
   723  		} else {
   724  			t.Errorf("Expected one match for signing key id %X, but got %d matches", id, len(keys))
   725  		}
   726  
   727  		// This keyring contains no encryption keys that are also good for signing.
   728  		keys = kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
   729  		if len(keys) != 0 {
   730  			t.Errorf("Unexpected match for encryption key id %X", id)
   731  		}
   732  	}
   733  
   734  	for _, id := range encrypters {
   735  		keys := kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
   736  		if len(keys) == 1 {
   737  			if keys[0].PublicKey.KeyId != id {
   738  				t.Errorf("Expected to find encryption key id %X, but got %X", id, keys[0].PublicKey.KeyId)
   739  			}
   740  		} else {
   741  			t.Errorf("Expected one match for encryption key id %X, but got %d matches", id, len(keys))
   742  		}
   743  
   744  		// This keyring contains no encryption keys that are also good for signing.
   745  		keys = kring.KeysByIdUsage(id, packet.KeyFlagSign)
   746  		if len(keys) != 0 {
   747  			t.Errorf("Unexpected match for signing key id %X", id)
   748  		}
   749  	}
   750  }
   751  
   752  func TestIdVerification(t *testing.T) {
   753  	kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
   754  	if err != nil {
   755  		t.Fatal(err)
   756  	}
   757  	if err := kring[1].PrivateKey.Decrypt([]byte("passphrase")); err != nil {
   758  		t.Fatal(err)
   759  	}
   760  
   761  	const signedIdentity = "Test Key 1 (RSA)"
   762  	const signerIdentity = "Test Key 2 (RSA, encrypted private key)"
   763  	config := &packet.Config{SigLifetimeSecs: 128, SigningIdentity: signerIdentity}
   764  	if err := kring[0].SignIdentity(signedIdentity, kring[1], config); err != nil {
   765  		t.Fatal(err)
   766  	}
   767  
   768  	ident, ok := kring[0].Identities[signedIdentity]
   769  	if !ok {
   770  		t.Fatal("signed identity missing from key after signing")
   771  	}
   772  
   773  	checked := false
   774  	for _, sig := range ident.Signatures {
   775  		if sig.IssuerKeyId == nil || *sig.IssuerKeyId != kring[1].PrimaryKey.KeyId {
   776  			continue
   777  		}
   778  
   779  		if err := kring[1].PrimaryKey.VerifyUserIdSignature(signedIdentity, kring[0].PrimaryKey, sig); err != nil {
   780  			t.Fatalf("error verifying new identity signature: %s", err)
   781  		}
   782  
   783  		if sig.SignerUserId == nil || *sig.SignerUserId != signerIdentity {
   784  			t.Fatalf("wrong or nil signer identity")
   785  		}
   786  
   787  		if sig.SigExpired(time.Now()) {
   788  			t.Fatalf("signature is expired")
   789  		}
   790  
   791  		if !sig.SigExpired(time.Now().Add(129 * time.Second)) {
   792  			t.Fatalf("signature has invalid expiration")
   793  		}
   794  
   795  		checked = true
   796  		break
   797  	}
   798  
   799  	if !checked {
   800  		t.Fatal("didn't find identity signature in Entity")
   801  	}
   802  }
   803  
   804  func TestNewEntityWithDefaultHash(t *testing.T) {
   805  	for _, hash := range hashes {
   806  		c := &packet.Config{
   807  			DefaultHash: hash,
   808  		}
   809  		entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", c)
   810  		if hash == crypto.SHA1 {
   811  			if err == nil {
   812  				t.Fatal("should fail on SHA1 key creation")
   813  			}
   814  			continue
   815  		}
   816  
   817  		if err != nil {
   818  			t.Fatal(err)
   819  		}
   820  
   821  		for _, identity := range entity.Identities {
   822  			prefs := identity.SelfSignature.PreferredHash
   823  			if len(prefs) == 0 {
   824  				t.Fatal("didn't find a preferred hash list in self signature")
   825  			}
   826  			ph := hashToHashId(c.DefaultHash)
   827  			if prefs[0] != ph {
   828  				t.Fatalf("Expected preferred hash to be %d, got %d", ph, prefs[0])
   829  			}
   830  		}
   831  	}
   832  }
   833  
   834  func TestNewEntityNilConfigPreferredHash(t *testing.T) {
   835  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
   836  	if err != nil {
   837  		t.Fatal(err)
   838  	}
   839  
   840  	for _, identity := range entity.Identities {
   841  		prefs := identity.SelfSignature.PreferredHash
   842  		if len(prefs) != 1 {
   843  			t.Fatal("expected preferred hashes list to be [SHA256]")
   844  		}
   845  	}
   846  }
   847  
   848  func TestNewEntityCorrectName(t *testing.T) {
   849  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
   850  	if err != nil {
   851  		t.Fatal(err)
   852  	}
   853  	if len(entity.Identities) != 1 {
   854  		t.Fatalf("len(entity.Identities) = %d, want 1", len(entity.Identities))
   855  	}
   856  	var got string
   857  	for _, i := range entity.Identities {
   858  		got = i.Name
   859  	}
   860  	want := "Golang Gopher (Test Key) <no-reply@golang.com>"
   861  	if got != want {
   862  		t.Fatalf("Identity.Name = %q, want %q", got, want)
   863  	}
   864  }
   865  
   866  func TestNewEntityWithDefaultCipher(t *testing.T) {
   867  	for _, cipher := range ciphers {
   868  		c := &packet.Config{
   869  			DefaultCipher: cipher,
   870  		}
   871  		entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", c)
   872  		if err != nil {
   873  			t.Fatal(err)
   874  		}
   875  
   876  		for _, identity := range entity.Identities {
   877  			prefs := identity.SelfSignature.PreferredSymmetric
   878  			if len(prefs) == 0 {
   879  				t.Fatal("didn't find a preferred cipher list")
   880  			}
   881  			if prefs[0] != uint8(c.DefaultCipher) {
   882  				t.Fatalf("Expected preferred cipher to be %d, got %d", uint8(c.DefaultCipher), prefs[0])
   883  			}
   884  		}
   885  	}
   886  }
   887  
   888  func TestNewEntityNilConfigPreferredSymmetric(t *testing.T) {
   889  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
   890  	if err != nil {
   891  		t.Fatal(err)
   892  	}
   893  
   894  	for _, identity := range entity.Identities {
   895  		prefs := identity.SelfSignature.PreferredSymmetric
   896  		if len(prefs) != 1 || prefs[0] != algorithm.AES128.Id() {
   897  			t.Fatal("expected preferred ciphers list to be [AES128]")
   898  		}
   899  	}
   900  }
   901  
   902  func TestNewEntityWithDefaultAead(t *testing.T) {
   903  	for _, aeadMode := range aeadModes {
   904  		cfg := &packet.Config{
   905  			AEADConfig: &packet.AEADConfig{
   906  				DefaultMode: aeadMode,
   907  			},
   908  		}
   909  		entity, err := NewEntity("Botvinnik", "1.e4", "tal@chess.com", cfg)
   910  		if err != nil {
   911  			t.Fatal(err)
   912  		}
   913  
   914  		for _, identity := range entity.Identities {
   915  			if len(identity.SelfSignature.PreferredCipherSuites) == 0 {
   916  				t.Fatal("didn't find a preferred mode in self signature")
   917  			}
   918  			cipher := identity.SelfSignature.PreferredCipherSuites[0][0]
   919  			if cipher != uint8(cfg.Cipher()) {
   920  				t.Fatalf("Expected preferred cipher to be %d, got %d",
   921  					uint8(cfg.Cipher()),
   922  					identity.SelfSignature.PreferredCipherSuites[0][0])
   923  			}
   924  			mode := identity.SelfSignature.PreferredCipherSuites[0][1]
   925  			if mode != uint8(cfg.AEAD().DefaultMode) {
   926  				t.Fatalf("Expected preferred mode to be %d, got %d",
   927  					uint8(cfg.AEAD().DefaultMode),
   928  					identity.SelfSignature.PreferredCipherSuites[0][1])
   929  			}
   930  		}
   931  	}
   932  }
   933  
   934  func TestNewEntityPublicSerialization(t *testing.T) {
   935  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
   936  	if err != nil {
   937  		t.Fatal(err)
   938  	}
   939  	serializedEntity := bytes.NewBuffer(nil)
   940  	err = entity.Serialize(serializedEntity)
   941  	if err != nil {
   942  		t.Fatal(err)
   943  	}
   944  
   945  	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
   946  	if err != nil {
   947  		t.Fatal(err)
   948  	}
   949  }
   950  
   951  func TestNewEntityPrivateSerialization(t *testing.T) {
   952  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
   953  	if err != nil {
   954  		t.Fatal(err)
   955  	}
   956  	serializedEntity := bytes.NewBuffer(nil)
   957  	err = entity.SerializePrivateWithoutSigning(serializedEntity, nil)
   958  	if err != nil {
   959  		t.Fatal(err)
   960  	}
   961  
   962  	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
   963  	if err != nil {
   964  		t.Fatal(err)
   965  	}
   966  }
   967  
   968  func TestNotationPacket(t *testing.T) {
   969  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithNotation))
   970  	if err != nil {
   971  		t.Fatal(err)
   972  	}
   973  
   974  	assertNotationPackets(t, keys)
   975  
   976  	serializedEntity := bytes.NewBuffer(nil)
   977  	err = keys[0].SerializePrivate(serializedEntity, nil)
   978  	if err != nil {
   979  		t.Fatal(err)
   980  	}
   981  
   982  	keys, err = ReadKeyRing(serializedEntity)
   983  	if err != nil {
   984  		t.Fatal(err)
   985  	}
   986  
   987  	assertNotationPackets(t, keys)
   988  }
   989  
   990  func assertNotationPackets(t *testing.T, keys EntityList) {
   991  	if len(keys) != 1 {
   992  		t.Errorf("Failed to accept key, %d", len(keys))
   993  	}
   994  
   995  	identity := keys[0].Identities["Test <test@example.com>"]
   996  
   997  	if numSigs, numExpected := len(identity.Signatures), 1; numSigs != numExpected {
   998  		t.Fatalf("got %d signatures, expected %d", numSigs, numExpected)
   999  	}
  1000  
  1001  	notations := identity.Signatures[0].Notations
  1002  	if numNotations, numExpected := len(notations), 2; numNotations != numExpected {
  1003  		t.Fatalf("got %d Notation Data subpackets, expected %d", numNotations, numExpected)
  1004  	}
  1005  
  1006  	if notations[0].IsHumanReadable != true {
  1007  		t.Fatalf("got false, expected true")
  1008  	}
  1009  
  1010  	if notations[0].Name != "text@example.com" {
  1011  		t.Fatalf("got %s, expected text@example.com", notations[0].Name)
  1012  	}
  1013  
  1014  	if string(notations[0].Value) != "test" {
  1015  		t.Fatalf("got %s, expected \"test\"", string(notations[0].Value))
  1016  	}
  1017  
  1018  	if notations[1].IsHumanReadable != false {
  1019  		t.Fatalf("got true, expected false")
  1020  	}
  1021  
  1022  	if notations[1].Name != "binary@example.com" {
  1023  		t.Fatalf("got %s, expected binary@example.com", notations[1].Name)
  1024  	}
  1025  
  1026  	if !bytes.Equal(notations[1].Value, []byte{0, 1, 2, 3}) {
  1027  		t.Fatalf("got %s, expected {0, 1, 2, 3}", string(notations[1].Value))
  1028  	}
  1029  }
  1030  
  1031  func TestEntityPrivateSerialization(t *testing.T) {
  1032  	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKeyBlock))
  1033  	if err != nil {
  1034  		t.Fatal(err)
  1035  	}
  1036  
  1037  	for _, entity := range keys {
  1038  		serializedEntity := bytes.NewBuffer(nil)
  1039  		err = entity.SerializePrivateWithoutSigning(serializedEntity, nil)
  1040  		if err != nil {
  1041  			t.Fatal(err)
  1042  		}
  1043  
  1044  		_, err := ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  1045  		if err != nil {
  1046  			t.Fatal(err)
  1047  		}
  1048  	}
  1049  }
  1050  
  1051  func TestAddUserId(t *testing.T) {
  1052  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1053  	if err != nil {
  1054  		t.Fatal(err)
  1055  	}
  1056  
  1057  	err = entity.AddUserId("Golang Gopher", "Test Key", "add1---@golang.com", nil)
  1058  	if err != nil {
  1059  		t.Fatal(err)
  1060  	}
  1061  
  1062  	err = entity.AddUserId("Golang Gopher", "Test Key", "add2---@golang.com", nil)
  1063  	if err != nil {
  1064  		t.Fatal(err)
  1065  	}
  1066  
  1067  	ignore_err := entity.AddUserId("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1068  	if ignore_err == nil {
  1069  		t.Fatal(err)
  1070  	}
  1071  
  1072  	if len(entity.Identities) != 3 {
  1073  		t.Fatalf("Expected 3 id, got %d", len(entity.Identities))
  1074  	}
  1075  
  1076  	for _, sk := range entity.Identities {
  1077  		err = entity.PrimaryKey.VerifyUserIdSignature(sk.UserId.Id, entity.PrimaryKey, sk.SelfSignature)
  1078  		if err != nil {
  1079  			t.Errorf("Invalid subkey signature: %v", err)
  1080  		}
  1081  	}
  1082  
  1083  	serializedEntity := bytes.NewBuffer(nil)
  1084  	entity.SerializePrivate(serializedEntity, nil)
  1085  
  1086  	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  1087  	if err != nil {
  1088  		t.Fatal(err)
  1089  	}
  1090  }
  1091  func TestAddSubkey(t *testing.T) {
  1092  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1093  	if err != nil {
  1094  		t.Fatal(err)
  1095  	}
  1096  
  1097  	err = entity.AddSigningSubkey(nil)
  1098  	if err != nil {
  1099  		t.Fatal(err)
  1100  	}
  1101  
  1102  	err = entity.AddEncryptionSubkey(nil)
  1103  	if err != nil {
  1104  		t.Fatal(err)
  1105  	}
  1106  
  1107  	if len(entity.Subkeys) != 3 {
  1108  		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
  1109  	}
  1110  
  1111  	for _, sk := range entity.Subkeys {
  1112  		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
  1113  		if err != nil {
  1114  			t.Errorf("Invalid subkey signature: %v", err)
  1115  		}
  1116  	}
  1117  
  1118  	serializedEntity := bytes.NewBuffer(nil)
  1119  	entity.SerializePrivate(serializedEntity, nil)
  1120  
  1121  	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  1122  	if err != nil {
  1123  		t.Fatal(err)
  1124  	}
  1125  }
  1126  
  1127  func TestAddSubkeySerialized(t *testing.T) {
  1128  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1129  	if err != nil {
  1130  		t.Fatal(err)
  1131  	}
  1132  
  1133  	err = entity.AddSigningSubkey(nil)
  1134  	if err != nil {
  1135  		t.Fatal(err)
  1136  	}
  1137  
  1138  	err = entity.AddEncryptionSubkey(nil)
  1139  	if err != nil {
  1140  		t.Fatal(err)
  1141  	}
  1142  
  1143  	serializedEntity := bytes.NewBuffer(nil)
  1144  	entity.SerializePrivateWithoutSigning(serializedEntity, nil)
  1145  
  1146  	entity, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  1147  	if err != nil {
  1148  		t.Fatal(err)
  1149  	}
  1150  
  1151  	if len(entity.Subkeys) != 3 {
  1152  		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
  1153  	}
  1154  
  1155  	for _, sk := range entity.Subkeys {
  1156  		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
  1157  		if err != nil {
  1158  			t.Errorf("Invalid subkey signature: %v", err)
  1159  		}
  1160  	}
  1161  }
  1162  
  1163  func TestAddSubkeyWithConfig(t *testing.T) {
  1164  	c := &packet.Config{
  1165  		DefaultHash: crypto.SHA512,
  1166  		Algorithm:   packet.PubKeyAlgoEdDSA,
  1167  	}
  1168  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1169  	if err != nil {
  1170  		t.Fatal(err)
  1171  	}
  1172  
  1173  	err = entity.AddSigningSubkey(c)
  1174  	if err != nil {
  1175  		t.Fatal(err)
  1176  	}
  1177  
  1178  	err = entity.AddEncryptionSubkey(c)
  1179  	if err != nil {
  1180  		t.Fatal(err)
  1181  	}
  1182  
  1183  	if len(entity.Subkeys) != 3 {
  1184  		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
  1185  	}
  1186  
  1187  	if entity.Subkeys[1].PublicKey.PubKeyAlgo != packet.PubKeyAlgoEdDSA {
  1188  		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
  1189  			entity.Subkeys[1].PublicKey.PubKeyAlgo)
  1190  	}
  1191  
  1192  	if entity.Subkeys[2].PublicKey.PubKeyAlgo != packet.PubKeyAlgoECDH {
  1193  		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoECDH,
  1194  			entity.Subkeys[2].PublicKey.PubKeyAlgo)
  1195  	}
  1196  
  1197  	if entity.Subkeys[1].Sig.Hash != c.DefaultHash {
  1198  		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
  1199  			entity.Subkeys[1].Sig.Hash)
  1200  	}
  1201  
  1202  	if entity.Subkeys[1].Sig.EmbeddedSignature.Hash != c.DefaultHash {
  1203  		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
  1204  			entity.Subkeys[1].Sig.EmbeddedSignature.Hash)
  1205  	}
  1206  
  1207  	if entity.Subkeys[2].Sig.Hash != c.DefaultHash {
  1208  		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
  1209  			entity.Subkeys[2].Sig.Hash)
  1210  	}
  1211  
  1212  	for _, sk := range entity.Subkeys {
  1213  		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
  1214  		if err != nil {
  1215  			t.Errorf("Invalid subkey signature: %v", err)
  1216  		}
  1217  	}
  1218  
  1219  	serializedEntity := bytes.NewBuffer(nil)
  1220  	entity.SerializePrivate(serializedEntity, nil)
  1221  
  1222  	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  1223  	if err != nil {
  1224  		t.Fatal(err)
  1225  	}
  1226  }
  1227  
  1228  func TestAddSubkeyWithConfigSerialized(t *testing.T) {
  1229  	c := &packet.Config{
  1230  		DefaultHash: crypto.SHA512,
  1231  		Algorithm:   packet.PubKeyAlgoEdDSA,
  1232  	}
  1233  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1234  	if err != nil {
  1235  		t.Fatal(err)
  1236  	}
  1237  
  1238  	err = entity.AddSigningSubkey(c)
  1239  	if err != nil {
  1240  		t.Fatal(err)
  1241  	}
  1242  
  1243  	err = entity.AddEncryptionSubkey(c)
  1244  	if err != nil {
  1245  		t.Fatal(err)
  1246  	}
  1247  
  1248  	serializedEntity := bytes.NewBuffer(nil)
  1249  	entity.SerializePrivateWithoutSigning(serializedEntity, nil)
  1250  
  1251  	entity, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  1252  	if err != nil {
  1253  		t.Fatal(err)
  1254  	}
  1255  
  1256  	if len(entity.Subkeys) != 3 {
  1257  		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
  1258  	}
  1259  
  1260  	if entity.Subkeys[1].PublicKey.PubKeyAlgo != packet.PubKeyAlgoEdDSA {
  1261  		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
  1262  			entity.Subkeys[1].PublicKey.PubKeyAlgo)
  1263  	}
  1264  
  1265  	if entity.Subkeys[2].PublicKey.PubKeyAlgo != packet.PubKeyAlgoECDH {
  1266  		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoECDH,
  1267  			entity.Subkeys[2].PublicKey.PubKeyAlgo)
  1268  	}
  1269  
  1270  	if entity.Subkeys[1].Sig.Hash != c.DefaultHash {
  1271  		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
  1272  			entity.Subkeys[1].Sig.Hash)
  1273  	}
  1274  
  1275  	if entity.Subkeys[1].Sig.EmbeddedSignature.Hash != c.DefaultHash {
  1276  		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
  1277  			entity.Subkeys[1].Sig.EmbeddedSignature.Hash)
  1278  	}
  1279  
  1280  	if entity.Subkeys[2].Sig.Hash != c.DefaultHash {
  1281  		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
  1282  			entity.Subkeys[2].Sig.Hash)
  1283  	}
  1284  
  1285  	for _, sk := range entity.Subkeys {
  1286  		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
  1287  		if err != nil {
  1288  			t.Errorf("Invalid subkey signature: %v", err)
  1289  		}
  1290  	}
  1291  }
  1292  
  1293  func TestRevokeKey(t *testing.T) {
  1294  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1295  	if err != nil {
  1296  		t.Fatal(err)
  1297  	}
  1298  
  1299  	err = entity.RevokeKey(packet.NoReason, "Key revocation", nil)
  1300  	if err != nil {
  1301  		t.Fatal(err)
  1302  	}
  1303  
  1304  	if len(entity.Revocations) == 0 {
  1305  		t.Fatal("Revocation signature missing from entity")
  1306  	}
  1307  
  1308  	for _, r := range entity.Revocations {
  1309  		err = entity.PrimaryKey.VerifyRevocationSignature(r)
  1310  		if err != nil {
  1311  			t.Errorf("Invalid revocation: %v", err)
  1312  		}
  1313  	}
  1314  }
  1315  
  1316  func TestRevokeKeyWithConfig(t *testing.T) {
  1317  	c := &packet.Config{
  1318  		DefaultHash: crypto.SHA512,
  1319  	}
  1320  
  1321  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", &packet.Config{
  1322  		Algorithm: packet.PubKeyAlgoEdDSA,
  1323  	})
  1324  	if err != nil {
  1325  		t.Fatal(err)
  1326  	}
  1327  
  1328  	err = entity.RevokeKey(packet.NoReason, "Key revocation", c)
  1329  	if err != nil {
  1330  		t.Fatal(err)
  1331  	}
  1332  
  1333  	if len(entity.Revocations) == 0 {
  1334  		t.Fatal("Revocation signature missing from entity")
  1335  	}
  1336  
  1337  	if entity.Revocations[0].Hash != c.DefaultHash {
  1338  		t.Fatalf("Expected signature hash method: %v, got: %v", c.DefaultHash,
  1339  			entity.Revocations[0].Hash)
  1340  	}
  1341  
  1342  	for _, r := range entity.Revocations {
  1343  		err = entity.PrimaryKey.VerifyRevocationSignature(r)
  1344  		if err != nil {
  1345  			t.Errorf("Invalid revocation: %v", err)
  1346  		}
  1347  	}
  1348  }
  1349  
  1350  func TestRevokeSubkey(t *testing.T) {
  1351  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1352  	if err != nil {
  1353  		t.Fatal(err)
  1354  	}
  1355  
  1356  	sk := &entity.Subkeys[0]
  1357  	err = entity.RevokeSubkey(sk, packet.NoReason, "Key revocation", nil)
  1358  	if err != nil {
  1359  		t.Fatal(err)
  1360  	}
  1361  
  1362  	if len(entity.Subkeys[0].Revocations) != 1 {
  1363  		t.Fatalf("Expected 1 subkey revocation signature, got %v", len(sk.Revocations))
  1364  	}
  1365  
  1366  	revSig := entity.Subkeys[0].Revocations[0]
  1367  
  1368  	err = entity.PrimaryKey.VerifySubkeyRevocationSignature(revSig, sk.PublicKey)
  1369  	if err != nil {
  1370  		t.Fatal(err)
  1371  	}
  1372  
  1373  	if revSig.RevocationReason == nil {
  1374  		t.Fatal("Revocation reason was not set")
  1375  	}
  1376  	if revSig.RevocationReasonText == "" {
  1377  		t.Fatal("Revocation reason text was not set")
  1378  	}
  1379  
  1380  	serializedEntity := bytes.NewBuffer(nil)
  1381  	entity.SerializePrivate(serializedEntity, nil)
  1382  
  1383  	// Make sure revocation reason subpackets are not lost during serialization.
  1384  	newEntity, err := ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  1385  	if err != nil {
  1386  		t.Fatal(err)
  1387  	}
  1388  
  1389  	if newEntity.Subkeys[0].Revocations[0].RevocationReason == nil {
  1390  		t.Fatal("Revocation reason lost after serialization of entity")
  1391  	}
  1392  	if newEntity.Subkeys[0].Revocations[0].RevocationReasonText == "" {
  1393  		t.Fatal("Revocation reason text lost after serialization of entity")
  1394  	}
  1395  }
  1396  
  1397  func TestRevokeSubkeyWithAnotherEntity(t *testing.T) {
  1398  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1399  	if err != nil {
  1400  		t.Fatal(err)
  1401  	}
  1402  
  1403  	sk := entity.Subkeys[0]
  1404  
  1405  	newEntity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1406  	if err != nil {
  1407  		t.Fatal(err)
  1408  	}
  1409  
  1410  	err = newEntity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", nil)
  1411  	if err == nil {
  1412  		t.Fatal("Entity was able to revoke a subkey owned by a different entity")
  1413  	}
  1414  }
  1415  
  1416  func TestRevokeSubkeyWithInvalidSignature(t *testing.T) {
  1417  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1418  	if err != nil {
  1419  		t.Fatal(err)
  1420  	}
  1421  
  1422  	sk := entity.Subkeys[0]
  1423  	sk.Sig = &packet.Signature{Version: 4}
  1424  
  1425  	err = entity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", nil)
  1426  	if err == nil {
  1427  		t.Fatal("Entity was able to revoke a subkey with invalid signature")
  1428  	}
  1429  }
  1430  
  1431  func TestRevokeSubkeyWithConfig(t *testing.T) {
  1432  	c := &packet.Config{
  1433  		DefaultHash: crypto.SHA512,
  1434  	}
  1435  
  1436  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1437  	if err != nil {
  1438  		t.Fatal(err)
  1439  	}
  1440  
  1441  	sk := entity.Subkeys[0]
  1442  	err = entity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", c)
  1443  	if err != nil {
  1444  		t.Fatal(err)
  1445  	}
  1446  
  1447  	if len(sk.Revocations) != 1 {
  1448  		t.Fatalf("Expected 1 subkey revocation signature, got %v", len(sk.Revocations))
  1449  	}
  1450  
  1451  	revSig := sk.Revocations[0]
  1452  
  1453  	if revSig.Hash != c.DefaultHash {
  1454  		t.Fatalf("Expected signature hash method: %v, got: %v", c.DefaultHash, revSig.Hash)
  1455  	}
  1456  
  1457  	err = entity.PrimaryKey.VerifySubkeyRevocationSignature(revSig, sk.PublicKey)
  1458  	if err != nil {
  1459  		t.Fatal(err)
  1460  	}
  1461  }
  1462  
  1463  func TestEncryptAndDecryptPrivateKeys(t *testing.T) {
  1464  	s2kModesToTest := []s2k.Mode{s2k.IteratedSaltedS2K, s2k.Argon2S2K}
  1465  
  1466  	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  1467  	if err != nil {
  1468  		t.Fatal(err)
  1469  	}
  1470  
  1471  	err = entity.AddSigningSubkey(nil)
  1472  	if err != nil {
  1473  		t.Fatal(err)
  1474  	}
  1475  
  1476  	err = entity.AddEncryptionSubkey(nil)
  1477  	if err != nil {
  1478  		t.Fatal(err)
  1479  	}
  1480  	for _, mode := range s2kModesToTest {
  1481  		t.Run(fmt.Sprintf("S2KMode %d", mode), func(t *testing.T) {
  1482  			passphrase := []byte("password")
  1483  			config := &packet.Config{
  1484  				S2KConfig: &s2k.Config{
  1485  					S2KMode: mode,
  1486  				},
  1487  			}
  1488  			err = entity.EncryptPrivateKeys(passphrase, config)
  1489  			if err != nil {
  1490  				t.Fatal(err)
  1491  			}
  1492  	
  1493  			if !entity.PrivateKey.Encrypted {
  1494  				t.Fatal("Expected encrypted private key")
  1495  			}
  1496  			for _, subkey := range entity.Subkeys {
  1497  				if !subkey.PrivateKey.Encrypted {
  1498  					t.Fatal("Expected encrypted private key")
  1499  				}
  1500  			}
  1501  	
  1502  			err = entity.DecryptPrivateKeys(passphrase)
  1503  			if err != nil {
  1504  				t.Fatal(err)
  1505  			}
  1506  	
  1507  			if entity.PrivateKey.Encrypted {
  1508  				t.Fatal("Expected plaintext private key")
  1509  			}
  1510  			for _, subkey := range entity.Subkeys {
  1511  				if subkey.PrivateKey.Encrypted {
  1512  					t.Fatal("Expected plaintext private key")
  1513  				}
  1514  			}
  1515  		})
  1516  	}
  1517  	
  1518  
  1519  }
  1520  
  1521  func TestKeyValidateOnDecrypt(t *testing.T) {
  1522  	randomPassword := make([]byte, 128)
  1523  	_, err := rand.Read(randomPassword)
  1524  	if err != nil {
  1525  		t.Fatal(err)
  1526  	}
  1527  
  1528  	t.Run("RSA", func(t *testing.T) {
  1529  		t.Run("Hardcoded:2048 bits", func(t *testing.T) {
  1530  			keys, err := ReadArmoredKeyRing(bytes.NewBufferString(rsa2048PrivateKey))
  1531  			if err != nil {
  1532  				t.Fatal("Unable to parse hardcoded key: ", err)
  1533  			}
  1534  
  1535  			if err := keys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
  1536  				t.Fatal("Unable to decrypt hardcoded key: ", err)
  1537  			}
  1538  
  1539  			testKeyValidateRsaOnDecrypt(t, keys[0], randomPassword)
  1540  		})
  1541  
  1542  		for _, bits := range []int{2048, 3072, 4096} {
  1543  			t.Run("Generated:"+strconv.Itoa(bits)+" bits", func(t *testing.T) {
  1544  				key := testGenerateRSA(t, bits)
  1545  				testKeyValidateRsaOnDecrypt(t, key, randomPassword)
  1546  			})
  1547  		}
  1548  	})
  1549  
  1550  	t.Run("ECDSA", func(t *testing.T) {
  1551  		t.Run("Hardcoded:NIST P-256", func(t *testing.T) {
  1552  			keys, err := ReadArmoredKeyRing(bytes.NewBufferString(ecdsaPrivateKey))
  1553  			if err != nil {
  1554  				t.Fatal("Unable to parse hardcoded key: ", err)
  1555  			}
  1556  
  1557  			if err := keys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
  1558  				t.Fatal("Unable to decrypt hardcoded key: ", err)
  1559  			}
  1560  
  1561  			if err := keys[0].Subkeys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
  1562  				t.Fatal("Unable to decrypt hardcoded subkey: ", err)
  1563  			}
  1564  
  1565  			testKeyValidateEcdsaOnDecrypt(t, keys[0], randomPassword)
  1566  		})
  1567  
  1568  		ecdsaCurves := map[string]packet.Curve{
  1569  			"NIST P-256":      packet.CurveNistP256,
  1570  			"NIST P-384":      packet.CurveNistP384,
  1571  			"NIST P-521":      packet.CurveNistP521,
  1572  			"Brainpool P-256": packet.CurveBrainpoolP256,
  1573  			"Brainpool P-384": packet.CurveBrainpoolP384,
  1574  			"Brainpool P-512": packet.CurveBrainpoolP512,
  1575  			"SecP256k1":       packet.CurveSecP256k1,
  1576  		}
  1577  
  1578  		for name, curveType := range ecdsaCurves {
  1579  			t.Run("Generated:"+name, func(t *testing.T) {
  1580  				key := testGenerateEC(t, packet.PubKeyAlgoECDSA, curveType)
  1581  				testKeyValidateEcdsaOnDecrypt(t, key, randomPassword)
  1582  			})
  1583  		}
  1584  	})
  1585  
  1586  	t.Run("EdDSA", func(t *testing.T) {
  1587  		eddsaHardcoded := map[string]string{
  1588  			"Curve25519": curve25519PrivateKey,
  1589  			"Curve448":   curve448PrivateKey,
  1590  		}
  1591  
  1592  		for name, skData := range eddsaHardcoded {
  1593  			t.Run("Hardcoded:"+name, func(t *testing.T) {
  1594  				keys, err := ReadArmoredKeyRing(bytes.NewBufferString(skData))
  1595  				if err != nil {
  1596  					t.Fatal("Unable to parse hardcoded key: ", err)
  1597  				}
  1598  
  1599  				testKeyValidateEddsaOnDecrypt(t, keys[0], randomPassword)
  1600  			})
  1601  		}
  1602  
  1603  		eddsaCurves := map[string]packet.Curve{
  1604  			"Curve25519": packet.Curve25519,
  1605  			"Curve448":   packet.Curve448,
  1606  		}
  1607  
  1608  		for name, curveType := range eddsaCurves {
  1609  			t.Run("Generated:"+name, func(t *testing.T) {
  1610  				key := testGenerateEC(t, packet.PubKeyAlgoEdDSA, curveType)
  1611  				testKeyValidateEddsaOnDecrypt(t, key, randomPassword)
  1612  			})
  1613  		}
  1614  	})
  1615  
  1616  	t.Run("DSA With El Gamal Subkey", func(t *testing.T) {
  1617  		testKeyValidateDsaElGamalOnDecrypt(t, randomPassword)
  1618  	})
  1619  }
  1620  
  1621  func testGenerateRSA(t *testing.T, bits int) *Entity {
  1622  	config := &packet.Config{Algorithm: packet.PubKeyAlgoRSA, RSABits: bits}
  1623  	rsaEntity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", config)
  1624  	if err != nil {
  1625  		t.Fatal(err)
  1626  	}
  1627  
  1628  	return rsaEntity
  1629  }
  1630  
  1631  func testKeyValidateRsaOnDecrypt(t *testing.T, rsaEntity *Entity, password []byte) {
  1632  	var err error
  1633  	rsaPrimaryKey := rsaEntity.PrivateKey
  1634  	if err = rsaPrimaryKey.Encrypt(password); err != nil {
  1635  		t.Fatal(err)
  1636  	}
  1637  	if err = rsaPrimaryKey.Decrypt(password); err != nil {
  1638  		t.Fatal("Valid RSA key was marked as invalid: ", err)
  1639  	}
  1640  
  1641  	if err = rsaPrimaryKey.Encrypt(password); err != nil {
  1642  		t.Fatal(err)
  1643  	}
  1644  
  1645  	// Corrupt public modulo n in primary key
  1646  	n := rsaPrimaryKey.PublicKey.PublicKey.(*rsa.PublicKey).N
  1647  	rsaPrimaryKey.PublicKey.PublicKey.(*rsa.PublicKey).N = new(big.Int).Add(n, big.NewInt(2))
  1648  	err = rsaPrimaryKey.Decrypt(password)
  1649  	if _, ok := err.(errors.KeyInvalidError); !ok {
  1650  		t.Fatal("Failed to detect invalid RSA key")
  1651  	}
  1652  }
  1653  
  1654  func testGenerateEC(t *testing.T, algorithm packet.PublicKeyAlgorithm, curve packet.Curve) *Entity {
  1655  	config := &packet.Config{Algorithm: algorithm, Curve: curve}
  1656  	rsaEntity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", config)
  1657  	if err != nil {
  1658  		t.Fatal(err)
  1659  	}
  1660  
  1661  	return rsaEntity
  1662  }
  1663  
  1664  func testKeyValidateEcdsaOnDecrypt(t *testing.T, ecdsaKey *Entity, password []byte) {
  1665  	var err error
  1666  	ecdsaPrimaryKey := ecdsaKey.PrivateKey
  1667  
  1668  	if err = ecdsaPrimaryKey.Encrypt(password); err != nil {
  1669  		t.Fatal(err)
  1670  	}
  1671  
  1672  	if err := ecdsaPrimaryKey.Decrypt(password); err != nil {
  1673  		t.Fatal("Valid ECDSA key was marked as invalid: ", err)
  1674  	}
  1675  
  1676  	if err = ecdsaPrimaryKey.Encrypt(password); err != nil {
  1677  		t.Fatal(err)
  1678  	}
  1679  
  1680  	// Corrupt public X in primary key
  1681  	X := ecdsaPrimaryKey.PublicKey.PublicKey.(*ecdsa.PublicKey).X
  1682  	ecdsaPrimaryKey.PublicKey.PublicKey.(*ecdsa.PublicKey).X = new(big.Int).Add(X, big.NewInt(1))
  1683  	err = ecdsaPrimaryKey.Decrypt(password)
  1684  	if _, ok := err.(errors.KeyInvalidError); !ok {
  1685  		t.Fatal("Failed to detect invalid ECDSA key")
  1686  	}
  1687  
  1688  	// ECDH
  1689  	ecdsaSubkey := ecdsaKey.Subkeys[0].PrivateKey
  1690  	if err = ecdsaSubkey.Encrypt(password); err != nil {
  1691  		t.Fatal(err)
  1692  	}
  1693  
  1694  	if err := ecdsaSubkey.Decrypt(password); err != nil {
  1695  		t.Fatal("Valid ECDH key was marked as invalid: ", err)
  1696  	}
  1697  
  1698  	if err = ecdsaSubkey.Encrypt(password); err != nil {
  1699  		t.Fatal(err)
  1700  	}
  1701  
  1702  	// Corrupt public X in subkey
  1703  	ecdsaSubkey.PublicKey.PublicKey.(*ecdh.PublicKey).Point[5] ^= 1
  1704  
  1705  	err = ecdsaSubkey.Decrypt(password)
  1706  	if _, ok := err.(errors.KeyInvalidError); !ok {
  1707  		t.Fatal("Failed to detect invalid ECDH key")
  1708  	}
  1709  }
  1710  
  1711  func testKeyValidateEddsaOnDecrypt(t *testing.T, eddsaEntity *Entity, password []byte) {
  1712  	var err error
  1713  
  1714  	eddsaPrimaryKey := eddsaEntity.PrivateKey // already encrypted
  1715  	if err = eddsaPrimaryKey.Encrypt(password); err != nil {
  1716  		t.Fatal(err)
  1717  	}
  1718  
  1719  	if err := eddsaPrimaryKey.Decrypt(password); err != nil {
  1720  		t.Fatal("Valid EdDSA key was marked as invalid: ", err)
  1721  	}
  1722  
  1723  	if err = eddsaPrimaryKey.Encrypt(password); err != nil {
  1724  		t.Fatal(err)
  1725  	}
  1726  
  1727  	pubKey := *eddsaPrimaryKey.PublicKey.PublicKey.(*eddsa.PublicKey)
  1728  	pubKey.X[10] ^= 1
  1729  	err = eddsaPrimaryKey.Decrypt(password)
  1730  	if _, ok := err.(errors.KeyInvalidError); !ok {
  1731  		t.Fatal("Failed to detect invalid EdDSA key")
  1732  	}
  1733  
  1734  	// ECDH
  1735  	ecdhSubkey := eddsaEntity.Subkeys[len(eddsaEntity.Subkeys)-1].PrivateKey
  1736  	if err = ecdhSubkey.Encrypt(password); err != nil {
  1737  		t.Fatal(err)
  1738  	}
  1739  
  1740  	if err := ecdhSubkey.Decrypt(password); err != nil {
  1741  		t.Fatal("Valid ECDH key was marked as invalid: ", err)
  1742  	}
  1743  
  1744  	if err = ecdhSubkey.Encrypt(password); err != nil {
  1745  		t.Fatal(err)
  1746  	}
  1747  
  1748  	// Corrupt public X in subkey
  1749  	ecdhSubkey.PublicKey.PublicKey.(*ecdh.PublicKey).Point[5] ^= 1
  1750  	err = ecdhSubkey.Decrypt(password)
  1751  	if _, ok := err.(errors.KeyInvalidError); !ok {
  1752  		t.Fatal("Failed to detect invalid ECDH key")
  1753  	}
  1754  }
  1755  
  1756  // ...the legacy bits
  1757  func testKeyValidateDsaElGamalOnDecrypt(t *testing.T, randomPassword []byte) {
  1758  	var err error
  1759  
  1760  	dsaKeys, err := ReadArmoredKeyRing(bytes.NewBufferString(dsaPrivateKeyWithElGamalSubkey))
  1761  	if err != nil {
  1762  		t.Fatal(err)
  1763  	}
  1764  	dsaPrimaryKey := dsaKeys[0].PrivateKey // already encrypted
  1765  	if err := dsaPrimaryKey.Decrypt([]byte("password")); err != nil {
  1766  		t.Fatal("Valid DSA key was marked as invalid: ", err)
  1767  	}
  1768  
  1769  	if err = dsaPrimaryKey.Encrypt(randomPassword); err != nil {
  1770  		t.Fatal(err)
  1771  	}
  1772  	// corrupt DSA generator
  1773  	G := dsaPrimaryKey.PublicKey.PublicKey.(*dsa.PublicKey).G
  1774  	dsaPrimaryKey.PublicKey.PublicKey.(*dsa.PublicKey).G = new(big.Int).Add(G, big.NewInt(1))
  1775  	err = dsaPrimaryKey.Decrypt(randomPassword)
  1776  	if _, ok := err.(errors.KeyInvalidError); !ok {
  1777  		t.Fatal("Failed to detect invalid DSA key")
  1778  	}
  1779  
  1780  	// ElGamal
  1781  	elGamalSubkey := dsaKeys[0].Subkeys[0].PrivateKey // already encrypted
  1782  	if err := elGamalSubkey.Decrypt([]byte("password")); err != nil {
  1783  		t.Fatal("Valid ElGamal key was marked as invalid: ", err)
  1784  	}
  1785  
  1786  	if err = elGamalSubkey.Encrypt(randomPassword); err != nil {
  1787  		t.Fatal(err)
  1788  	}
  1789  
  1790  	// corrupt ElGamal generator
  1791  	G = elGamalSubkey.PublicKey.PublicKey.(*elgamal.PublicKey).G
  1792  	elGamalSubkey.PublicKey.PublicKey.(*elgamal.PublicKey).G = new(big.Int).Add(G, big.NewInt(1))
  1793  	err = elGamalSubkey.Decrypt(randomPassword)
  1794  	if _, ok := err.(errors.KeyInvalidError); !ok {
  1795  		t.Fatal("Failed to detect invalid ElGamal key")
  1796  	}
  1797  }
  1798  
  1799  // Should not panic (generated with go-fuzz)
  1800  func TestCorruptKeys(t *testing.T) {
  1801  	data := `-----BEGIN PGP PUBLIC KEY BLOCK00000
  1802  
  1803  mQ00BF00000BCAD0000000000000000000000000000000000000000000000000
  1804  0000000000000000000000000000000000000000000000000000000000000000
  1805  0000000000000000000000000000000000000000000000000000000000000000
  1806  0000000000000000000000000000000000000000000000000000000000000000
  1807  0000000000000000000000000000000000000000000000000000000000000000
  1808  000000000000000000000000000000000000ABE000G0Dn000000000000000000iQ00BB0BAgAGBCG00000`
  1809  	ReadArmoredKeyRing(strings.NewReader(data))
  1810  }
  1811  

View as plain text