github.com/letsencrypt/trillian@v1.1.2-0.20180615153820-ae375a99d36a/crypto/keys/der/proto/register_test.go (about)

     1  // Copyright 2017 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package proto
    16  
    17  import (
    18  	"context"
    19  	"encoding/base64"
    20  	"testing"
    21  
    22  	"github.com/golang/protobuf/proto"
    23  	"github.com/google/trillian/crypto/keys"
    24  	"github.com/google/trillian/crypto/keys/testonly"
    25  	"github.com/google/trillian/crypto/keyspb"
    26  )
    27  
    28  func TestProtoHandler(t *testing.T) {
    29  	// ECDSA private key in DER format.
    30  	keyDER, err := base64.StdEncoding.DecodeString("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgS81mfpvtTmaINn+gtrYXn4XpxxgE655GLSKsA3hhjHmhRANCAASwBWDdgHS04V/cN0LZgc8vZaK4I1HWLLCoaOO27Z0B1aS1aqBE7g1Oo8ldSCBJAvee866kcHhZkVniPdCG2ZZG")
    31  	if err != nil {
    32  		t.Fatalf("Could not decode test key: %v", err)
    33  	}
    34  
    35  	ctx := context.Background()
    36  
    37  	for _, test := range []struct {
    38  		desc     string
    39  		keyProto proto.Message
    40  		wantErr  bool
    41  	}{
    42  		{
    43  			desc: "PrivateKey",
    44  			keyProto: &keyspb.PrivateKey{
    45  				Der: keyDER,
    46  			},
    47  		},
    48  		{
    49  			desc: "PrivateKey with invalid DER",
    50  			keyProto: &keyspb.PrivateKey{
    51  				Der: []byte("foobar"),
    52  			},
    53  			wantErr: true,
    54  		},
    55  		{
    56  			desc:     "PrivateKey with missing DER",
    57  			keyProto: &keyspb.PrivateKey{},
    58  			wantErr:  true,
    59  		},
    60  	} {
    61  		signer, err := keys.NewSigner(ctx, test.keyProto)
    62  		if gotErr := err != nil; gotErr != test.wantErr {
    63  			t.Errorf("%v: NewSigner(_, %#v) = (_, %q), want (_, nil)", test.desc, test.keyProto, err)
    64  			continue
    65  		} else if gotErr {
    66  			continue
    67  		}
    68  
    69  		// Check that the returned signer can produce signatures successfully.
    70  		if err := testonly.SignAndVerify(signer, signer.Public()); err != nil {
    71  			t.Errorf("%v: SignAndVerify() = %q, want nil", test.desc, err)
    72  		}
    73  	}
    74  }