...

Source file src/golang.org/x/crypto/openpgp/write_test.go

Documentation: golang.org/x/crypto/openpgp

     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 openpgp
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"testing"
    11  	"time"
    12  
    13  	"golang.org/x/crypto/openpgp/packet"
    14  )
    15  
    16  func TestSignDetached(t *testing.T) {
    17  	kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
    18  	out := bytes.NewBuffer(nil)
    19  	message := bytes.NewBufferString(signedInput)
    20  	err := DetachSign(out, kring[0], message, nil)
    21  	if err != nil {
    22  		t.Error(err)
    23  	}
    24  
    25  	testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId)
    26  }
    27  
    28  func TestSignTextDetached(t *testing.T) {
    29  	kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
    30  	out := bytes.NewBuffer(nil)
    31  	message := bytes.NewBufferString(signedInput)
    32  	err := DetachSignText(out, kring[0], message, nil)
    33  	if err != nil {
    34  		t.Error(err)
    35  	}
    36  
    37  	testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId)
    38  }
    39  
    40  func TestSignDetachedDSA(t *testing.T) {
    41  	kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyPrivateHex))
    42  	out := bytes.NewBuffer(nil)
    43  	message := bytes.NewBufferString(signedInput)
    44  	err := DetachSign(out, kring[0], message, nil)
    45  	if err != nil {
    46  		t.Error(err)
    47  	}
    48  
    49  	testDetachedSignature(t, kring, out, signedInput, "check", testKey3KeyId)
    50  }
    51  
    52  func TestSignDetachedP256(t *testing.T) {
    53  	kring, _ := ReadKeyRing(readerFromHex(p256TestKeyPrivateHex))
    54  	kring[0].PrivateKey.Decrypt([]byte("passphrase"))
    55  
    56  	out := bytes.NewBuffer(nil)
    57  	message := bytes.NewBufferString(signedInput)
    58  	err := DetachSign(out, kring[0], message, nil)
    59  	if err != nil {
    60  		t.Error(err)
    61  	}
    62  
    63  	testDetachedSignature(t, kring, out, signedInput, "check", testKeyP256KeyId)
    64  }
    65  
    66  func TestNewEntity(t *testing.T) {
    67  	if testing.Short() {
    68  		return
    69  	}
    70  
    71  	// Check bit-length with no config.
    72  	e, err := NewEntity("Test User", "test", "test@example.com", nil)
    73  	if err != nil {
    74  		t.Errorf("failed to create entity: %s", err)
    75  		return
    76  	}
    77  	bl, err := e.PrimaryKey.BitLength()
    78  	if err != nil {
    79  		t.Errorf("failed to find bit length: %s", err)
    80  	}
    81  	if int(bl) != defaultRSAKeyBits {
    82  		t.Errorf("BitLength %v, expected %v", int(bl), defaultRSAKeyBits)
    83  	}
    84  
    85  	// Check bit-length with a config.
    86  	cfg := &packet.Config{RSABits: 1024}
    87  	e, err = NewEntity("Test User", "test", "test@example.com", cfg)
    88  	if err != nil {
    89  		t.Errorf("failed to create entity: %s", err)
    90  		return
    91  	}
    92  	bl, err = e.PrimaryKey.BitLength()
    93  	if err != nil {
    94  		t.Errorf("failed to find bit length: %s", err)
    95  	}
    96  	if int(bl) != cfg.RSABits {
    97  		t.Errorf("BitLength %v, expected %v", bl, cfg.RSABits)
    98  	}
    99  
   100  	w := bytes.NewBuffer(nil)
   101  	if err := e.SerializePrivate(w, nil); err != nil {
   102  		t.Errorf("failed to serialize entity: %s", err)
   103  		return
   104  	}
   105  	serialized := w.Bytes()
   106  
   107  	el, err := ReadKeyRing(w)
   108  	if err != nil {
   109  		t.Errorf("failed to reparse entity: %s", err)
   110  		return
   111  	}
   112  
   113  	if len(el) != 1 {
   114  		t.Errorf("wrong number of entities found, got %d, want 1", len(el))
   115  	}
   116  
   117  	w = bytes.NewBuffer(nil)
   118  	if err := e.SerializePrivate(w, nil); err != nil {
   119  		t.Errorf("failed to serialize entity second time: %s", err)
   120  		return
   121  	}
   122  
   123  	if !bytes.Equal(w.Bytes(), serialized) {
   124  		t.Errorf("results differed")
   125  	}
   126  }
   127  
   128  func TestSymmetricEncryption(t *testing.T) {
   129  	buf := new(bytes.Buffer)
   130  	plaintext, err := SymmetricallyEncrypt(buf, []byte("testing"), nil, nil)
   131  	if err != nil {
   132  		t.Errorf("error writing headers: %s", err)
   133  		return
   134  	}
   135  	message := []byte("hello world\n")
   136  	_, err = plaintext.Write(message)
   137  	if err != nil {
   138  		t.Errorf("error writing to plaintext writer: %s", err)
   139  	}
   140  	err = plaintext.Close()
   141  	if err != nil {
   142  		t.Errorf("error closing plaintext writer: %s", err)
   143  	}
   144  
   145  	md, err := ReadMessage(buf, nil, func(keys []Key, symmetric bool) ([]byte, error) {
   146  		return []byte("testing"), nil
   147  	}, nil)
   148  	if err != nil {
   149  		t.Errorf("error rereading message: %s", err)
   150  	}
   151  	messageBuf := bytes.NewBuffer(nil)
   152  	_, err = io.Copy(messageBuf, md.UnverifiedBody)
   153  	if err != nil {
   154  		t.Errorf("error rereading message: %s", err)
   155  	}
   156  	if !bytes.Equal(message, messageBuf.Bytes()) {
   157  		t.Errorf("recovered message incorrect got '%s', want '%s'", messageBuf.Bytes(), message)
   158  	}
   159  }
   160  
   161  var testEncryptionTests = []struct {
   162  	keyRingHex string
   163  	isSigned   bool
   164  }{
   165  	{
   166  		testKeys1And2PrivateHex,
   167  		false,
   168  	},
   169  	{
   170  		testKeys1And2PrivateHex,
   171  		true,
   172  	},
   173  	{
   174  		dsaElGamalTestKeysHex,
   175  		false,
   176  	},
   177  	{
   178  		dsaElGamalTestKeysHex,
   179  		true,
   180  	},
   181  }
   182  
   183  func TestEncryption(t *testing.T) {
   184  	for i, test := range testEncryptionTests {
   185  		kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex))
   186  
   187  		passphrase := []byte("passphrase")
   188  		for _, entity := range kring {
   189  			if entity.PrivateKey != nil && entity.PrivateKey.Encrypted {
   190  				err := entity.PrivateKey.Decrypt(passphrase)
   191  				if err != nil {
   192  					t.Errorf("#%d: failed to decrypt key", i)
   193  				}
   194  			}
   195  			for _, subkey := range entity.Subkeys {
   196  				if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted {
   197  					err := subkey.PrivateKey.Decrypt(passphrase)
   198  					if err != nil {
   199  						t.Errorf("#%d: failed to decrypt subkey", i)
   200  					}
   201  				}
   202  			}
   203  		}
   204  
   205  		var signed *Entity
   206  		if test.isSigned {
   207  			signed = kring[0]
   208  		}
   209  
   210  		buf := new(bytes.Buffer)
   211  		w, err := Encrypt(buf, kring[:1], signed, nil /* no hints */, nil)
   212  		if err != nil {
   213  			t.Errorf("#%d: error in Encrypt: %s", i, err)
   214  			continue
   215  		}
   216  
   217  		const message = "testing"
   218  		_, err = w.Write([]byte(message))
   219  		if err != nil {
   220  			t.Errorf("#%d: error writing plaintext: %s", i, err)
   221  			continue
   222  		}
   223  		err = w.Close()
   224  		if err != nil {
   225  			t.Errorf("#%d: error closing WriteCloser: %s", i, err)
   226  			continue
   227  		}
   228  
   229  		md, err := ReadMessage(buf, kring, nil /* no prompt */, nil)
   230  		if err != nil {
   231  			t.Errorf("#%d: error reading message: %s", i, err)
   232  			continue
   233  		}
   234  
   235  		testTime, _ := time.Parse("2006-01-02", "2013-07-01")
   236  		if test.isSigned {
   237  			signKey, _ := kring[0].signingKey(testTime)
   238  			expectedKeyId := signKey.PublicKey.KeyId
   239  			if md.SignedByKeyId != expectedKeyId {
   240  				t.Errorf("#%d: message signed by wrong key id, got: %v, want: %v", i, *md.SignedBy, expectedKeyId)
   241  			}
   242  			if md.SignedBy == nil {
   243  				t.Errorf("#%d: failed to find the signing Entity", i)
   244  			}
   245  		}
   246  
   247  		plaintext, err := io.ReadAll(md.UnverifiedBody)
   248  		if err != nil {
   249  			t.Errorf("#%d: error reading encrypted contents: %s", i, err)
   250  			continue
   251  		}
   252  
   253  		encryptKey, _ := kring[0].encryptionKey(testTime)
   254  		expectedKeyId := encryptKey.PublicKey.KeyId
   255  		if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedKeyId {
   256  			t.Errorf("#%d: expected message to be encrypted to %v, but got %#v", i, expectedKeyId, md.EncryptedToKeyIds)
   257  		}
   258  
   259  		if string(plaintext) != message {
   260  			t.Errorf("#%d: got: %s, want: %s", i, string(plaintext), message)
   261  		}
   262  
   263  		if test.isSigned {
   264  			if md.SignatureError != nil {
   265  				t.Errorf("#%d: signature error: %s", i, md.SignatureError)
   266  			}
   267  			if md.Signature == nil {
   268  				t.Error("signature missing")
   269  			}
   270  		}
   271  	}
   272  }
   273  
   274  var testSigningTests = []struct {
   275  	keyRingHex string
   276  }{
   277  	{
   278  		testKeys1And2PrivateHex,
   279  	},
   280  	{
   281  		dsaElGamalTestKeysHex,
   282  	},
   283  }
   284  
   285  func TestSigning(t *testing.T) {
   286  	for i, test := range testSigningTests {
   287  		kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex))
   288  
   289  		passphrase := []byte("passphrase")
   290  		for _, entity := range kring {
   291  			if entity.PrivateKey != nil && entity.PrivateKey.Encrypted {
   292  				err := entity.PrivateKey.Decrypt(passphrase)
   293  				if err != nil {
   294  					t.Errorf("#%d: failed to decrypt key", i)
   295  				}
   296  			}
   297  			for _, subkey := range entity.Subkeys {
   298  				if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted {
   299  					err := subkey.PrivateKey.Decrypt(passphrase)
   300  					if err != nil {
   301  						t.Errorf("#%d: failed to decrypt subkey", i)
   302  					}
   303  				}
   304  			}
   305  		}
   306  
   307  		signed := kring[0]
   308  
   309  		buf := new(bytes.Buffer)
   310  		w, err := Sign(buf, signed, nil /* no hints */, nil)
   311  		if err != nil {
   312  			t.Errorf("#%d: error in Sign: %s", i, err)
   313  			continue
   314  		}
   315  
   316  		const message = "testing"
   317  		_, err = w.Write([]byte(message))
   318  		if err != nil {
   319  			t.Errorf("#%d: error writing plaintext: %s", i, err)
   320  			continue
   321  		}
   322  		err = w.Close()
   323  		if err != nil {
   324  			t.Errorf("#%d: error closing WriteCloser: %s", i, err)
   325  			continue
   326  		}
   327  
   328  		md, err := ReadMessage(buf, kring, nil /* no prompt */, nil)
   329  		if err != nil {
   330  			t.Errorf("#%d: error reading message: %s", i, err)
   331  			continue
   332  		}
   333  
   334  		testTime, _ := time.Parse("2006-01-02", "2013-07-01")
   335  		signKey, _ := kring[0].signingKey(testTime)
   336  		expectedKeyId := signKey.PublicKey.KeyId
   337  		if md.SignedByKeyId != expectedKeyId {
   338  			t.Errorf("#%d: message signed by wrong key id, got: %v, want: %v", i, *md.SignedBy, expectedKeyId)
   339  		}
   340  		if md.SignedBy == nil {
   341  			t.Errorf("#%d: failed to find the signing Entity", i)
   342  		}
   343  
   344  		plaintext, err := io.ReadAll(md.UnverifiedBody)
   345  		if err != nil {
   346  			t.Errorf("#%d: error reading contents: %v", i, err)
   347  			continue
   348  		}
   349  
   350  		if string(plaintext) != message {
   351  			t.Errorf("#%d: got: %q, want: %q", i, plaintext, message)
   352  		}
   353  
   354  		if md.SignatureError != nil {
   355  			t.Errorf("#%d: signature error: %q", i, md.SignatureError)
   356  		}
   357  		if md.Signature == nil {
   358  			t.Error("signature missing")
   359  		}
   360  	}
   361  }
   362  

View as plain text