github.com/osdi23p228/fabric@v0.0.0-20221218062954-77808885f5db/bccsp/pkcs11/pkcs11_test.go (about)

     1  // +build pkcs11
     2  
     3  /*
     4  Copyright IBM Corp. All Rights Reserved.
     5  
     6  SPDX-License-Identifier: Apache-2.0
     7  */
     8  package pkcs11
     9  
    10  import (
    11  	"bytes"
    12  	"crypto/ecdsa"
    13  	"crypto/elliptic"
    14  	"crypto/rand"
    15  	"crypto/sha256"
    16  	"crypto/sha512"
    17  	"crypto/x509"
    18  	"crypto/x509/pkix"
    19  	"encoding/asn1"
    20  	"fmt"
    21  	"hash"
    22  	"io/ioutil"
    23  	"math/big"
    24  	"net"
    25  	"os"
    26  	"strings"
    27  	"testing"
    28  	"time"
    29  
    30  	"github.com/osdi23p228/fabric/bccsp"
    31  	"github.com/osdi23p228/fabric/bccsp/signer"
    32  	"github.com/osdi23p228/fabric/bccsp/sw"
    33  	"github.com/osdi23p228/fabric/bccsp/utils"
    34  	"github.com/miekg/pkcs11"
    35  	"github.com/stretchr/testify/assert"
    36  	"github.com/stretchr/testify/require"
    37  	"golang.org/x/crypto/sha3"
    38  )
    39  
    40  var (
    41  	currentKS         bccsp.KeyStore
    42  	currentBCCSP      bccsp.BCCSP
    43  	currentTestConfig testConfig
    44  )
    45  
    46  type testConfig struct {
    47  	securityLevel int
    48  	hashFamily    string
    49  	softVerify    bool
    50  	immutable     bool
    51  }
    52  
    53  func TestMain(m *testing.M) {
    54  	os.Exit(testMain(m))
    55  }
    56  
    57  func testMain(m *testing.M) int {
    58  	tmpDir, err := ioutil.TempDir("", "pkcs11_ks")
    59  	if err != nil {
    60  		fmt.Printf("Failed to create keystore directory [%s]\n", err)
    61  		return -1
    62  	}
    63  	defer os.RemoveAll(tmpDir)
    64  
    65  	keyStore, err := sw.NewFileBasedKeyStore(nil, tmpDir, false)
    66  	if err != nil {
    67  		fmt.Printf("Failed initiliazing KeyStore [%s]\n", err)
    68  		return -1
    69  	}
    70  	currentKS = keyStore
    71  
    72  	lib, pin, label := FindPKCS11Lib()
    73  	tests := []testConfig{
    74  		{256, "SHA2", true, false},
    75  		{256, "SHA3", false, false},
    76  		{384, "SHA2", false, false},
    77  		{384, "SHA3", false, false},
    78  		{384, "SHA3", true, false},
    79  	}
    80  
    81  	if strings.Contains(lib, "softhsm") {
    82  		tests = append(tests, testConfig{256, "SHA2", true, true})
    83  	}
    84  
    85  	opts := PKCS11Opts{
    86  		Library: lib,
    87  		Label:   label,
    88  		Pin:     pin,
    89  	}
    90  
    91  	for _, config := range tests {
    92  		currentTestConfig = config
    93  
    94  		opts.HashFamily = config.hashFamily
    95  		opts.SecLevel = config.securityLevel
    96  		opts.SoftVerify = config.softVerify
    97  		opts.Immutable = config.immutable
    98  		fmt.Printf("Immutable = [%v]\n", opts.Immutable)
    99  		currentBCCSP, err = New(opts, keyStore)
   100  		if err != nil {
   101  			fmt.Printf("Failed initiliazing BCCSP at [%+v] \n%s\n", opts, err)
   102  			return -1
   103  		}
   104  
   105  		ret := m.Run()
   106  		if ret != 0 {
   107  			fmt.Printf("Failed testing at [%+v]\n", opts)
   108  			return -1
   109  		}
   110  	}
   111  	return 0
   112  }
   113  
   114  func TestNew(t *testing.T) {
   115  	opts := PKCS11Opts{
   116  		HashFamily: "SHA2",
   117  		SecLevel:   256,
   118  		SoftVerify: false,
   119  		Library:    "lib",
   120  		Label:      "ForFabric",
   121  		Pin:        "98765432",
   122  	}
   123  
   124  	// Setup PKCS11 library and provide initial set of values
   125  	lib, _, _ := FindPKCS11Lib()
   126  	opts.Library = lib
   127  
   128  	// Test for nil keystore
   129  	_, err := New(opts, nil)
   130  	require.Error(t, err)
   131  	require.Contains(t, err.Error(), "Invalid bccsp.KeyStore instance. It must be different from nil")
   132  
   133  	// Test for invalid PKCS11 loadLib
   134  	opts.Library = ""
   135  	_, err = New(opts, currentKS)
   136  	require.Error(t, err)
   137  	require.Contains(t, err.Error(), "pkcs11: library path not provided")
   138  }
   139  
   140  func TestFindPKCS11LibEnvVars(t *testing.T) {
   141  	const (
   142  		dummy_PKCS11_LIB   = "/usr/lib/pkcs11"
   143  		dummy_PKCS11_PIN   = "23456789"
   144  		dummy_PKCS11_LABEL = "testing"
   145  	)
   146  
   147  	// Set environment variables used for test and preserve
   148  	// original values for restoration after test completion
   149  	orig_PKCS11_LIB := os.Getenv("PKCS11_LIB")
   150  	orig_PKCS11_PIN := os.Getenv("PKCS11_PIN")
   151  	orig_PKCS11_LABEL := os.Getenv("PKCS11_LABEL")
   152  
   153  	t.Run("ExplicitEnvironment", func(t *testing.T) {
   154  		os.Setenv("PKCS11_LIB", dummy_PKCS11_LIB)
   155  		os.Setenv("PKCS11_PIN", dummy_PKCS11_PIN)
   156  		os.Setenv("PKCS11_LABEL", dummy_PKCS11_LABEL)
   157  
   158  		lib, pin, label := FindPKCS11Lib()
   159  		require.EqualValues(t, dummy_PKCS11_LIB, lib, "FindPKCS11Lib did not return expected library")
   160  		require.EqualValues(t, dummy_PKCS11_PIN, pin, "FindPKCS11Lib did not return expected pin")
   161  		require.EqualValues(t, dummy_PKCS11_LABEL, label, "FindPKCS11Lib did not return expected label")
   162  	})
   163  
   164  	t.Run("MissingEnvironment", func(t *testing.T) {
   165  		os.Unsetenv("PKCS11_LIB")
   166  		os.Unsetenv("PKCS11_PIN")
   167  		os.Unsetenv("PKCS11_LABEL")
   168  
   169  		_, pin, label := FindPKCS11Lib()
   170  		require.EqualValues(t, "98765432", pin, "FindPKCS11Lib did not return expected pin")
   171  		require.EqualValues(t, "ForFabric", label, "FindPKCS11Lib did not return expected label")
   172  	})
   173  
   174  	os.Setenv("PKCS11_LIB", orig_PKCS11_LIB)
   175  	os.Setenv("PKCS11_PIN", orig_PKCS11_PIN)
   176  	os.Setenv("PKCS11_LABEL", orig_PKCS11_LABEL)
   177  }
   178  
   179  func TestInvalidNewParameter(t *testing.T) {
   180  	lib, pin, label := FindPKCS11Lib()
   181  	opts := PKCS11Opts{
   182  		Library:    lib,
   183  		Label:      label,
   184  		Pin:        pin,
   185  		SoftVerify: true,
   186  	}
   187  
   188  	opts.HashFamily = "SHA2"
   189  	opts.SecLevel = 0
   190  	r, err := New(opts, currentKS)
   191  	if err == nil {
   192  		t.Fatal("Error should be different from nil in this case")
   193  	}
   194  	if r != nil {
   195  		t.Fatal("Return value should be equal to nil in this case")
   196  	}
   197  
   198  	opts.HashFamily = "SHA8"
   199  	opts.SecLevel = 256
   200  	r, err = New(opts, currentKS)
   201  	if err == nil {
   202  		t.Fatal("Error should be different from nil in this case")
   203  	}
   204  	if r != nil {
   205  		t.Fatal("Return value should be equal to nil in this case")
   206  	}
   207  
   208  	opts.HashFamily = "SHA2"
   209  	opts.SecLevel = 256
   210  	r, err = New(opts, nil)
   211  	if err == nil {
   212  		t.Fatal("Error should be different from nil in this case")
   213  	}
   214  	if r != nil {
   215  		t.Fatal("Return value should be equal to nil in this case")
   216  	}
   217  
   218  	opts.HashFamily = "SHA3"
   219  	opts.SecLevel = 0
   220  	r, err = New(opts, nil)
   221  	if err == nil {
   222  		t.Fatal("Error should be different from nil in this case")
   223  	}
   224  	if r != nil {
   225  		t.Fatal("Return value should be equal to nil in this case")
   226  	}
   227  }
   228  
   229  func TestInvalidSKI(t *testing.T) {
   230  	k, err := currentBCCSP.GetKey(nil)
   231  	if err == nil {
   232  		t.Fatal("Error should be different from nil in this case")
   233  	}
   234  	if k != nil {
   235  		t.Fatal("Return value should be equal to nil in this case")
   236  	}
   237  
   238  	k, err = currentBCCSP.GetKey([]byte{0, 1, 2, 3, 4, 5, 6})
   239  	if err == nil {
   240  		t.Fatal("Error should be different from nil in this case")
   241  	}
   242  	if k != nil {
   243  		t.Fatal("Return value should be equal to nil in this case")
   244  	}
   245  }
   246  
   247  func TestKeyGenECDSAOpts(t *testing.T) {
   248  	// Curve P256
   249  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
   250  	if err != nil {
   251  		t.Fatalf("Failed generating ECDSA P256 key [%s]", err)
   252  	}
   253  	if k == nil {
   254  		t.Fatal("Failed generating ECDSA P256 key. Key must be different from nil")
   255  	}
   256  	if !k.Private() {
   257  		t.Fatal("Failed generating ECDSA P256 key. Key should be private")
   258  	}
   259  	if k.Symmetric() {
   260  		t.Fatal("Failed generating ECDSA P256 key. Key should be asymmetric")
   261  	}
   262  
   263  	ecdsaKey := k.(*ecdsaPrivateKey).pub
   264  	if elliptic.P256() != ecdsaKey.pub.Curve {
   265  		t.Fatal("P256 generated key in invalid. The curve must be P256.")
   266  	}
   267  
   268  	// Curve P384
   269  	k, err = currentBCCSP.KeyGen(&bccsp.ECDSAP384KeyGenOpts{Temporary: false})
   270  	if err != nil {
   271  		t.Fatalf("Failed generating ECDSA P384 key [%s]", err)
   272  	}
   273  	if k == nil {
   274  		t.Fatal("Failed generating ECDSA P384 key. Key must be different from nil")
   275  	}
   276  	if !k.Private() {
   277  		t.Fatal("Failed generating ECDSA P384 key. Key should be private")
   278  	}
   279  	if k.Symmetric() {
   280  		t.Fatal("Failed generating ECDSA P384 key. Key should be asymmetric")
   281  	}
   282  
   283  	ecdsaKey = k.(*ecdsaPrivateKey).pub
   284  	if elliptic.P384() != ecdsaKey.pub.Curve {
   285  		t.Fatal("P256 generated key in invalid. The curve must be P384.")
   286  	}
   287  }
   288  
   289  func TestKeyGenAESOpts(t *testing.T) {
   290  	// AES 128
   291  	k, err := currentBCCSP.KeyGen(&bccsp.AES128KeyGenOpts{Temporary: false})
   292  	if err != nil {
   293  		t.Fatalf("Failed generating AES 128 key [%s]", err)
   294  	}
   295  	if k == nil {
   296  		t.Fatal("Failed generating AES 128 key. Key must be different from nil")
   297  	}
   298  	if !k.Private() {
   299  		t.Fatal("Failed generating AES 128 key. Key should be private")
   300  	}
   301  	if !k.Symmetric() {
   302  		t.Fatal("Failed generating AES 128 key. Key should be symmetric")
   303  	}
   304  
   305  	// AES 192
   306  	k, err = currentBCCSP.KeyGen(&bccsp.AES192KeyGenOpts{Temporary: false})
   307  	if err != nil {
   308  		t.Fatalf("Failed generating AES 192 key [%s]", err)
   309  	}
   310  	if k == nil {
   311  		t.Fatal("Failed generating AES 192 key. Key must be different from nil")
   312  	}
   313  	if !k.Private() {
   314  		t.Fatal("Failed generating AES 192 key. Key should be private")
   315  	}
   316  	if !k.Symmetric() {
   317  		t.Fatal("Failed generating AES 192 key. Key should be symmetric")
   318  	}
   319  
   320  	// AES 256
   321  	k, err = currentBCCSP.KeyGen(&bccsp.AES256KeyGenOpts{Temporary: false})
   322  	if err != nil {
   323  		t.Fatalf("Failed generating AES 256 key [%s]", err)
   324  	}
   325  	if k == nil {
   326  		t.Fatal("Failed generating AES 256 key. Key must be different from nil")
   327  	}
   328  	if !k.Private() {
   329  		t.Fatal("Failed generating AES 256 key. Key should be private")
   330  	}
   331  	if !k.Symmetric() {
   332  		t.Fatal("Failed generating AES 256 key. Key should be symmetric")
   333  	}
   334  }
   335  
   336  func TestHashOpts(t *testing.T) {
   337  	msg := []byte("abcd")
   338  
   339  	// SHA256
   340  	digest1, err := currentBCCSP.Hash(msg, &bccsp.SHA256Opts{})
   341  	if err != nil {
   342  		t.Fatalf("Failed computing SHA256 [%s]", err)
   343  	}
   344  
   345  	h := sha256.New()
   346  	h.Write(msg)
   347  	digest2 := h.Sum(nil)
   348  
   349  	if !bytes.Equal(digest1, digest2) {
   350  		t.Fatalf("Different SHA256 computed. [%x][%x]", digest1, digest2)
   351  	}
   352  
   353  	// SHA384
   354  	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA384Opts{})
   355  	if err != nil {
   356  		t.Fatalf("Failed computing SHA384 [%s]", err)
   357  	}
   358  
   359  	h = sha512.New384()
   360  	h.Write(msg)
   361  	digest2 = h.Sum(nil)
   362  
   363  	if !bytes.Equal(digest1, digest2) {
   364  		t.Fatalf("Different SHA384 computed. [%x][%x]", digest1, digest2)
   365  	}
   366  
   367  	// SHA3_256O
   368  	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_256Opts{})
   369  	if err != nil {
   370  		t.Fatalf("Failed computing SHA3_256 [%s]", err)
   371  	}
   372  
   373  	h = sha3.New256()
   374  	h.Write(msg)
   375  	digest2 = h.Sum(nil)
   376  
   377  	if !bytes.Equal(digest1, digest2) {
   378  		t.Fatalf("Different SHA3_256 computed. [%x][%x]", digest1, digest2)
   379  	}
   380  
   381  	// SHA3_384
   382  	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_384Opts{})
   383  	if err != nil {
   384  		t.Fatalf("Failed computing SHA3_384 [%s]", err)
   385  	}
   386  
   387  	h = sha3.New384()
   388  	h.Write(msg)
   389  	digest2 = h.Sum(nil)
   390  
   391  	if !bytes.Equal(digest1, digest2) {
   392  		t.Fatalf("Different SHA3_384 computed. [%x][%x]", digest1, digest2)
   393  	}
   394  }
   395  
   396  func TestECDSAKeyGenEphemeral(t *testing.T) {
   397  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: true})
   398  	if err != nil {
   399  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   400  	}
   401  	if k == nil {
   402  		t.Fatal("Failed generating ECDSA key. Key must be different from nil")
   403  	}
   404  	if !k.Private() {
   405  		t.Fatal("Failed generating ECDSA key. Key should be private")
   406  	}
   407  	if k.Symmetric() {
   408  		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
   409  	}
   410  	raw, err := k.Bytes()
   411  	if err == nil {
   412  		t.Fatal("Failed marshalling to bytes. Marshalling must fail.")
   413  	}
   414  	if len(raw) != 0 {
   415  		t.Fatal("Failed marshalling to bytes. Output should be 0 bytes")
   416  	}
   417  	pk, err := k.PublicKey()
   418  	if err != nil {
   419  		t.Fatalf("Failed getting corresponding public key [%s]", err)
   420  	}
   421  	if pk == nil {
   422  		t.Fatal("Public key must be different from nil.")
   423  	}
   424  }
   425  
   426  func TestECDSAPrivateKeySKI(t *testing.T) {
   427  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   428  	if err != nil {
   429  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   430  	}
   431  
   432  	ski := k.SKI()
   433  	if len(ski) == 0 {
   434  		t.Fatal("SKI not valid. Zero length.")
   435  	}
   436  }
   437  
   438  func TestECDSAKeyGenNonEphemeral(t *testing.T) {
   439  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   440  	if err != nil {
   441  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   442  	}
   443  	if k == nil {
   444  		t.Fatal("Failed generating ECDSA key. Key must be different from nil")
   445  	}
   446  	if !k.Private() {
   447  		t.Fatal("Failed generating ECDSA key. Key should be private")
   448  	}
   449  	if k.Symmetric() {
   450  		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
   451  	}
   452  }
   453  
   454  func TestECDSAGetKeyBySKI(t *testing.T) {
   455  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   456  	if err != nil {
   457  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   458  	}
   459  
   460  	k2, err := currentBCCSP.GetKey(k.SKI())
   461  	if err != nil {
   462  		t.Fatalf("Failed getting ECDSA key [%s]", err)
   463  	}
   464  	if k2 == nil {
   465  		t.Fatal("Failed getting ECDSA key. Key must be different from nil")
   466  	}
   467  	if !k2.Private() {
   468  		t.Fatal("Failed getting ECDSA key. Key should be private")
   469  	}
   470  	if k2.Symmetric() {
   471  		t.Fatal("Failed getting ECDSA key. Key should be asymmetric")
   472  	}
   473  
   474  	// Check that the SKIs are the same
   475  	if !bytes.Equal(k.SKI(), k2.SKI()) {
   476  		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
   477  	}
   478  }
   479  
   480  func TestECDSAPublicKeyFromPrivateKey(t *testing.T) {
   481  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   482  	if err != nil {
   483  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   484  	}
   485  
   486  	pk, err := k.PublicKey()
   487  	if err != nil {
   488  		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
   489  	}
   490  	if pk == nil {
   491  		t.Fatal("Failed getting public key from private ECDSA key. Key must be different from nil")
   492  	}
   493  	if pk.Private() {
   494  		t.Fatal("Failed generating ECDSA key. Key should be public")
   495  	}
   496  	if pk.Symmetric() {
   497  		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
   498  	}
   499  }
   500  
   501  func TestECDSAPublicKeyBytes(t *testing.T) {
   502  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   503  	if err != nil {
   504  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   505  	}
   506  
   507  	pk, err := k.PublicKey()
   508  	if err != nil {
   509  		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
   510  	}
   511  
   512  	raw, err := pk.Bytes()
   513  	if err != nil {
   514  		t.Fatalf("Failed marshalling ECDSA public key [%s]", err)
   515  	}
   516  	if len(raw) == 0 {
   517  		t.Fatal("Failed marshalling ECDSA public key. Zero length")
   518  	}
   519  }
   520  
   521  func TestECDSAPublicKeySKI(t *testing.T) {
   522  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   523  	if err != nil {
   524  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   525  	}
   526  
   527  	pk, err := k.PublicKey()
   528  	if err != nil {
   529  		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
   530  	}
   531  
   532  	ski := pk.SKI()
   533  	if len(ski) == 0 {
   534  		t.Fatal("SKI not valid. Zero length.")
   535  	}
   536  }
   537  
   538  func TestECDSASign(t *testing.T) {
   539  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   540  	if err != nil {
   541  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   542  	}
   543  
   544  	msg := []byte("Hello World")
   545  
   546  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   547  	if err != nil {
   548  		t.Fatalf("Failed computing HASH [%s]", err)
   549  	}
   550  
   551  	signature, err := currentBCCSP.Sign(k, digest, nil)
   552  	if err != nil {
   553  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   554  	}
   555  	if len(signature) == 0 {
   556  		t.Fatal("Failed generating ECDSA key. Signature must be different from nil")
   557  	}
   558  
   559  	_, err = currentBCCSP.Sign(nil, digest, nil)
   560  	require.Error(t, err)
   561  	require.Contains(t, err.Error(), "Invalid Key. It must not be nil")
   562  
   563  	_, err = currentBCCSP.Sign(k, nil, nil)
   564  	require.Error(t, err)
   565  	require.Contains(t, err.Error(), "Invalid digest. Cannot be empty")
   566  }
   567  
   568  func TestECDSAVerify(t *testing.T) {
   569  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   570  	if err != nil {
   571  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   572  	}
   573  
   574  	msg := []byte("Hello World")
   575  
   576  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   577  	if err != nil {
   578  		t.Fatalf("Failed computing HASH [%s]", err)
   579  	}
   580  
   581  	signature, err := currentBCCSP.Sign(k, digest, nil)
   582  	if err != nil {
   583  		t.Fatalf("Failed generating ECDSA signature  [%s]", err)
   584  	}
   585  
   586  	valid, err := currentBCCSP.Verify(k, signature, digest, nil)
   587  	if err != nil {
   588  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   589  	}
   590  	if !valid {
   591  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   592  	}
   593  
   594  	pk, err := k.PublicKey()
   595  	if err != nil {
   596  		t.Fatalf("Failed getting corresponding public key [%s]", err)
   597  	}
   598  
   599  	valid, err = currentBCCSP.Verify(pk, signature, digest, nil)
   600  	if err != nil {
   601  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   602  	}
   603  	if !valid {
   604  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   605  	}
   606  
   607  	_, err = currentBCCSP.Verify(nil, signature, digest, nil)
   608  	require.Error(t, err)
   609  	require.Contains(t, err.Error(), "Invalid Key. It must not be nil")
   610  
   611  	_, err = currentBCCSP.Verify(pk, nil, digest, nil)
   612  	require.Error(t, err)
   613  	require.Contains(t, err.Error(), "Invalid signature. Cannot be empty")
   614  
   615  	_, err = currentBCCSP.Verify(pk, signature, nil, nil)
   616  	require.Error(t, err)
   617  	require.Contains(t, err.Error(), "Invalid digest. Cannot be empty")
   618  
   619  	// Import the exported public key
   620  	pkRaw, err := pk.Bytes()
   621  	if err != nil {
   622  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   623  	}
   624  
   625  	// Store public key
   626  	_, err = currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false})
   627  	if err != nil {
   628  		t.Fatalf("Failed storing corresponding public key [%s]", err)
   629  	}
   630  
   631  	pk2, err := currentBCCSP.GetKey(pk.SKI())
   632  	if err != nil {
   633  		t.Fatalf("Failed retrieving corresponding public key [%s]", err)
   634  	}
   635  
   636  	valid, err = currentBCCSP.Verify(pk2, signature, digest, nil)
   637  	if err != nil {
   638  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   639  	}
   640  	if !valid {
   641  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   642  	}
   643  }
   644  
   645  func TestECDSAKeyImportFromExportedKey(t *testing.T) {
   646  	// Generate an ECDSA key
   647  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   648  	if err != nil {
   649  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   650  	}
   651  
   652  	// Export the public key
   653  	pk, err := k.PublicKey()
   654  	if err != nil {
   655  		t.Fatalf("Failed getting ECDSA public key [%s]", err)
   656  	}
   657  
   658  	pkRaw, err := pk.Bytes()
   659  	if err != nil {
   660  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   661  	}
   662  
   663  	// Import the exported public key
   664  	pk2, err := currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false})
   665  	if err != nil {
   666  		t.Fatalf("Failed importing ECDSA public key [%s]", err)
   667  	}
   668  	if pk2 == nil {
   669  		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
   670  	}
   671  
   672  	// Sign and verify with the imported public key
   673  	msg := []byte("Hello World")
   674  
   675  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   676  	if err != nil {
   677  		t.Fatalf("Failed computing HASH [%s]", err)
   678  	}
   679  
   680  	signature, err := currentBCCSP.Sign(k, digest, nil)
   681  	if err != nil {
   682  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   683  	}
   684  
   685  	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
   686  	if err != nil {
   687  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   688  	}
   689  	if !valid {
   690  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   691  	}
   692  }
   693  
   694  func TestECDSAKeyImportFromECDSAPublicKey(t *testing.T) {
   695  	// Generate an ECDSA key
   696  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   697  	if err != nil {
   698  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   699  	}
   700  
   701  	// Export the public key
   702  	pk, err := k.PublicKey()
   703  	if err != nil {
   704  		t.Fatalf("Failed getting ECDSA public key [%s]", err)
   705  	}
   706  
   707  	pkRaw, err := pk.Bytes()
   708  	if err != nil {
   709  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   710  	}
   711  
   712  	pub, err := x509.ParsePKIXPublicKey(pkRaw)
   713  	if err != nil {
   714  		t.Fatalf("Failed converting raw to ecdsa.PublicKey [%s]", err)
   715  	}
   716  
   717  	// Import the ecdsa.PublicKey
   718  	pk2, err := currentBCCSP.KeyImport(pub, &bccsp.ECDSAGoPublicKeyImportOpts{Temporary: false})
   719  	if err != nil {
   720  		t.Fatalf("Failed importing ECDSA public key [%s]", err)
   721  	}
   722  	if pk2 == nil {
   723  		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
   724  	}
   725  
   726  	// Sign and verify with the imported public key
   727  	msg := []byte("Hello World")
   728  
   729  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   730  	if err != nil {
   731  		t.Fatalf("Failed computing HASH [%s]", err)
   732  	}
   733  
   734  	signature, err := currentBCCSP.Sign(k, digest, nil)
   735  	if err != nil {
   736  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   737  	}
   738  
   739  	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
   740  	if err != nil {
   741  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   742  	}
   743  	if !valid {
   744  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   745  	}
   746  }
   747  
   748  func TestKeyImportFromX509ECDSAPublicKey(t *testing.T) {
   749  	// Generate an ECDSA key
   750  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   751  	if err != nil {
   752  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   753  	}
   754  
   755  	// Generate a self-signed certificate
   756  	testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
   757  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
   758  	extraExtensionData := []byte("extra extension")
   759  	commonName := "test.example.com"
   760  	template := x509.Certificate{
   761  		SerialNumber: big.NewInt(1),
   762  		Subject: pkix.Name{
   763  			CommonName:   commonName,
   764  			Organization: []string{"Σ Acme Co"},
   765  			Country:      []string{"US"},
   766  			ExtraNames: []pkix.AttributeTypeAndValue{
   767  				{
   768  					Type:  []int{2, 5, 4, 42},
   769  					Value: "Gopher",
   770  				},
   771  				// This should override the Country, above.
   772  				{
   773  					Type:  []int{2, 5, 4, 6},
   774  					Value: "NL",
   775  				},
   776  			},
   777  		},
   778  		NotBefore: time.Now().Add(-1 * time.Hour),
   779  		NotAfter:  time.Now().Add(1 * time.Hour),
   780  
   781  		SignatureAlgorithm: x509.ECDSAWithSHA256,
   782  
   783  		SubjectKeyId: []byte{1, 2, 3, 4},
   784  		KeyUsage:     x509.KeyUsageCertSign,
   785  
   786  		ExtKeyUsage:        testExtKeyUsage,
   787  		UnknownExtKeyUsage: testUnknownExtKeyUsage,
   788  
   789  		BasicConstraintsValid: true,
   790  		IsCA:                  true,
   791  
   792  		OCSPServer:            []string{"http://ocurrentBCCSP.example.com"},
   793  		IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
   794  
   795  		DNSNames:       []string{"test.example.com"},
   796  		EmailAddresses: []string{"gopher@golang.org"},
   797  		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   798  
   799  		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
   800  		PermittedDNSDomains: []string{".example.com", "example.com"},
   801  
   802  		CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
   803  
   804  		ExtraExtensions: []pkix.Extension{
   805  			{
   806  				Id:    []int{1, 2, 3, 4},
   807  				Value: extraExtensionData,
   808  			},
   809  		},
   810  	}
   811  
   812  	cryptoSigner, err := signer.New(currentBCCSP, k)
   813  	if err != nil {
   814  		t.Fatalf("Failed initializing CyrptoSigner [%s]", err)
   815  	}
   816  
   817  	// Export the public key
   818  	pk, err := k.PublicKey()
   819  	if err != nil {
   820  		t.Fatalf("Failed getting ECDSA public key [%s]", err)
   821  	}
   822  
   823  	pkRaw, err := pk.Bytes()
   824  	if err != nil {
   825  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   826  	}
   827  
   828  	pub, err := x509.ParsePKIXPublicKey(pkRaw)
   829  	if err != nil {
   830  		t.Fatalf("Failed converting raw to ECDSA.PublicKey [%s]", err)
   831  	}
   832  
   833  	certRaw, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, cryptoSigner)
   834  	if err != nil {
   835  		t.Fatalf("Failed generating self-signed certificate [%s]", err)
   836  	}
   837  
   838  	cert, err := x509.ParseCertificate(certRaw)
   839  	if err != nil {
   840  		t.Fatalf("Failed generating X509 certificate object from raw [%s]", err)
   841  	}
   842  
   843  	// Import the certificate's public key
   844  	pk2, err := currentBCCSP.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: false})
   845  
   846  	if err != nil {
   847  		t.Fatalf("Failed importing ECDSA public key [%s]", err)
   848  	}
   849  	if pk2 == nil {
   850  		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
   851  	}
   852  
   853  	// Sign and verify with the imported public key
   854  	msg := []byte("Hello World")
   855  
   856  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   857  	if err != nil {
   858  		t.Fatalf("Failed computing HASH [%s]", err)
   859  	}
   860  
   861  	signature, err := currentBCCSP.Sign(k, digest, nil)
   862  	if err != nil {
   863  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   864  	}
   865  
   866  	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
   867  	if err != nil {
   868  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   869  	}
   870  	if !valid {
   871  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   872  	}
   873  }
   874  
   875  func TestECDSASignatureEncoding(t *testing.T) {
   876  	v := []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0xff, 0xf1}
   877  	_, err := asn1.Unmarshal(v, &utils.ECDSASignature{})
   878  	if err == nil {
   879  		t.Fatalf("Unmarshalling should fail for [% x]", v)
   880  	}
   881  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
   882  
   883  	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0x00, 0x01}
   884  	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
   885  	if err == nil {
   886  		t.Fatalf("Unmarshalling should fail for [% x]", v)
   887  	}
   888  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
   889  
   890  	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x01}
   891  	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
   892  	if err == nil {
   893  		t.Fatalf("Unmarshalling should fail for [% x]", v)
   894  	}
   895  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
   896  
   897  	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x8F}
   898  	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
   899  	if err == nil {
   900  		t.Fatalf("Unmarshalling should fail for [% x]", v)
   901  	}
   902  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
   903  
   904  	v = []byte{0x30, 0x0A, 0x02, 0x01, 0x8F, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00, 0x8F}
   905  	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
   906  	if err == nil {
   907  		t.Fatalf("Unmarshalling should fail for [% x]", v)
   908  	}
   909  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
   910  
   911  }
   912  
   913  func TestECDSALowS(t *testing.T) {
   914  	// Ensure that signature with low-S are generated
   915  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   916  	if err != nil {
   917  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   918  	}
   919  
   920  	msg := []byte("Hello World")
   921  
   922  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   923  	if err != nil {
   924  		t.Fatalf("Failed computing HASH [%s]", err)
   925  	}
   926  
   927  	signature, err := currentBCCSP.Sign(k, digest, nil)
   928  	if err != nil {
   929  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   930  	}
   931  
   932  	R, S, err := utils.UnmarshalECDSASignature(signature)
   933  	if err != nil {
   934  		t.Fatalf("Failed unmarshalling signature [%s]", err)
   935  	}
   936  
   937  	if S.Cmp(utils.GetCurveHalfOrdersAt(k.(*ecdsaPrivateKey).pub.pub.Curve)) >= 0 {
   938  		t.Fatal("Invalid signature. It must have low-S")
   939  	}
   940  
   941  	valid, err := currentBCCSP.Verify(k, signature, digest, nil)
   942  	if err != nil {
   943  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   944  	}
   945  	if !valid {
   946  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   947  	}
   948  
   949  	// Ensure that signature with high-S are rejected.
   950  	for {
   951  		R, S, err = currentBCCSP.(*impl).signP11ECDSA(k.SKI(), digest)
   952  		if err != nil {
   953  			t.Fatalf("Failed generating signature [%s]", err)
   954  		}
   955  
   956  		if S.Cmp(utils.GetCurveHalfOrdersAt(k.(*ecdsaPrivateKey).pub.pub.Curve)) > 0 {
   957  			break
   958  		}
   959  	}
   960  
   961  	sig, err := utils.MarshalECDSASignature(R, S)
   962  	if err != nil {
   963  		t.Fatalf("Failing unmarshalling signature [%s]", err)
   964  	}
   965  
   966  	valid, err = currentBCCSP.Verify(k, sig, digest, nil)
   967  	if err == nil {
   968  		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
   969  	}
   970  	if valid {
   971  		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
   972  	}
   973  }
   974  
   975  func TestAESKeyGen(t *testing.T) {
   976  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
   977  	if err != nil {
   978  		t.Fatalf("Failed generating AES_256 key [%s]", err)
   979  	}
   980  	if k == nil {
   981  		t.Fatal("Failed generating AES_256 key. Key must be different from nil")
   982  	}
   983  	if !k.Private() {
   984  		t.Fatal("Failed generating AES_256 key. Key should be private")
   985  	}
   986  	if !k.Symmetric() {
   987  		t.Fatal("Failed generating AES_256 key. Key should be symmetric")
   988  	}
   989  
   990  	pk, err := k.PublicKey()
   991  	if err == nil {
   992  		t.Fatal("Error should be different from nil in this case")
   993  	}
   994  	if pk != nil {
   995  		t.Fatal("Return value should be equal to nil in this case")
   996  	}
   997  }
   998  
   999  func TestAESEncrypt(t *testing.T) {
  1000  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1001  	if err != nil {
  1002  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1003  	}
  1004  
  1005  	ct, err := currentBCCSP.Encrypt(k, []byte("Hello World"), &bccsp.AESCBCPKCS7ModeOpts{})
  1006  	if err != nil {
  1007  		t.Fatalf("Failed encrypting [%s]", err)
  1008  	}
  1009  	if len(ct) == 0 {
  1010  		t.Fatal("Failed encrypting. Nil ciphertext")
  1011  	}
  1012  }
  1013  
  1014  func TestAESDecrypt(t *testing.T) {
  1015  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1016  	if err != nil {
  1017  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1018  	}
  1019  
  1020  	msg := []byte("Hello World")
  1021  
  1022  	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1023  	if err != nil {
  1024  		t.Fatalf("Failed encrypting [%s]", err)
  1025  	}
  1026  
  1027  	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1028  	if err != nil {
  1029  		t.Fatalf("Failed decrypting [%s]", err)
  1030  	}
  1031  	if len(ct) == 0 {
  1032  		t.Fatal("Failed decrypting. Nil plaintext")
  1033  	}
  1034  
  1035  	if !bytes.Equal(msg, pt) {
  1036  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1037  	}
  1038  }
  1039  
  1040  func TestHMACTruncated256KeyDerivOverAES256Key(t *testing.T) {
  1041  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1042  	if err != nil {
  1043  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1044  	}
  1045  
  1046  	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACTruncated256AESDeriveKeyOpts{Temporary: false, Arg: []byte{1}})
  1047  	if err != nil {
  1048  		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
  1049  	}
  1050  	if k == nil {
  1051  		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
  1052  	}
  1053  	if !hmcaedKey.Private() {
  1054  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
  1055  	}
  1056  	if !hmcaedKey.Symmetric() {
  1057  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
  1058  	}
  1059  	raw, err := hmcaedKey.Bytes()
  1060  	if err == nil {
  1061  		t.Fatal("Failed marshalling to bytes. Operation must be forbidden")
  1062  	}
  1063  	if len(raw) != 0 {
  1064  		t.Fatal("Failed marshalling to bytes. Operation must return 0 bytes")
  1065  	}
  1066  
  1067  	msg := []byte("Hello World")
  1068  
  1069  	ct, err := currentBCCSP.Encrypt(hmcaedKey, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1070  	if err != nil {
  1071  		t.Fatalf("Failed encrypting [%s]", err)
  1072  	}
  1073  
  1074  	pt, err := currentBCCSP.Decrypt(hmcaedKey, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1075  	if err != nil {
  1076  		t.Fatalf("Failed decrypting [%s]", err)
  1077  	}
  1078  	if len(ct) == 0 {
  1079  		t.Fatal("Failed decrypting. Nil plaintext")
  1080  	}
  1081  
  1082  	if !bytes.Equal(msg, pt) {
  1083  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1084  	}
  1085  
  1086  }
  1087  
  1088  func TestHMACKeyDerivOverAES256Key(t *testing.T) {
  1089  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1090  	if err != nil {
  1091  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1092  	}
  1093  
  1094  	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Temporary: false, Arg: []byte{1}})
  1095  
  1096  	if err != nil {
  1097  		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
  1098  	}
  1099  	if k == nil {
  1100  		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
  1101  	}
  1102  	if !hmcaedKey.Private() {
  1103  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
  1104  	}
  1105  	if !hmcaedKey.Symmetric() {
  1106  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
  1107  	}
  1108  	raw, err := hmcaedKey.Bytes()
  1109  	if err != nil {
  1110  		t.Fatalf("Failed marshalling to bytes [%s]", err)
  1111  	}
  1112  	if len(raw) == 0 {
  1113  		t.Fatal("Failed marshalling to bytes. 0 bytes")
  1114  	}
  1115  }
  1116  
  1117  func TestAES256KeyImport(t *testing.T) {
  1118  	raw, err := sw.GetRandomBytes(32)
  1119  	if err != nil {
  1120  		t.Fatalf("Failed generating AES key [%s]", err)
  1121  	}
  1122  
  1123  	k, err := currentBCCSP.KeyImport(raw, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1124  	if err != nil {
  1125  		t.Fatalf("Failed importing AES_256 key [%s]", err)
  1126  	}
  1127  	if k == nil {
  1128  		t.Fatal("Failed importing AES_256 key. Imported Key must be different from nil")
  1129  	}
  1130  	if !k.Private() {
  1131  		t.Fatal("Failed HMACing AES_256 key. Imported Key should be private")
  1132  	}
  1133  	if !k.Symmetric() {
  1134  		t.Fatal("Failed HMACing AES_256 key. Imported Key should be asymmetric")
  1135  	}
  1136  	raw, err = k.Bytes()
  1137  	if err == nil {
  1138  		t.Fatal("Failed marshalling to bytes. Marshalling must fail.")
  1139  	}
  1140  	if len(raw) != 0 {
  1141  		t.Fatal("Failed marshalling to bytes. Output should be 0 bytes")
  1142  	}
  1143  
  1144  	msg := []byte("Hello World")
  1145  
  1146  	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1147  	if err != nil {
  1148  		t.Fatalf("Failed encrypting [%s]", err)
  1149  	}
  1150  
  1151  	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1152  	if err != nil {
  1153  		t.Fatalf("Failed decrypting [%s]", err)
  1154  	}
  1155  	if len(ct) == 0 {
  1156  		t.Fatal("Failed decrypting. Nil plaintext")
  1157  	}
  1158  
  1159  	if !bytes.Equal(msg, pt) {
  1160  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1161  	}
  1162  }
  1163  
  1164  func TestAES256KeyImportBadPaths(t *testing.T) {
  1165  	_, err := currentBCCSP.KeyImport(nil, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1166  	if err == nil {
  1167  		t.Fatal("Failed importing key. Must fail on importing nil key")
  1168  	}
  1169  
  1170  	_, err = currentBCCSP.KeyImport([]byte{1}, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1171  	if err == nil {
  1172  		t.Fatal("Failed importing key. Must fail on importing a key with an invalid length")
  1173  	}
  1174  }
  1175  
  1176  func TestAES256KeyGenSKI(t *testing.T) {
  1177  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1178  	if err != nil {
  1179  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1180  	}
  1181  
  1182  	k2, err := currentBCCSP.GetKey(k.SKI())
  1183  	if err != nil {
  1184  		t.Fatalf("Failed getting AES_256 key [%s]", err)
  1185  	}
  1186  	if k2 == nil {
  1187  		t.Fatal("Failed getting AES_256 key. Key must be different from nil")
  1188  	}
  1189  	if !k2.Private() {
  1190  		t.Fatal("Failed getting AES_256 key. Key should be private")
  1191  	}
  1192  	if !k2.Symmetric() {
  1193  		t.Fatal("Failed getting AES_256 key. Key should be symmetric")
  1194  	}
  1195  
  1196  	// Check that the SKIs are the same
  1197  	if !bytes.Equal(k.SKI(), k2.SKI()) {
  1198  		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
  1199  	}
  1200  
  1201  }
  1202  
  1203  func TestSHA(t *testing.T) {
  1204  	for i := 0; i < 100; i++ {
  1205  		b, err := sw.GetRandomBytes(i)
  1206  		if err != nil {
  1207  			t.Fatalf("Failed getting random bytes [%s]", err)
  1208  		}
  1209  
  1210  		h1, err := currentBCCSP.Hash(b, &bccsp.SHAOpts{})
  1211  		if err != nil {
  1212  			t.Fatalf("Failed computing SHA [%s]", err)
  1213  		}
  1214  
  1215  		var h hash.Hash
  1216  		switch currentTestConfig.hashFamily {
  1217  		case "SHA2":
  1218  			switch currentTestConfig.securityLevel {
  1219  			case 256:
  1220  				h = sha256.New()
  1221  			case 384:
  1222  				h = sha512.New384()
  1223  			default:
  1224  				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1225  			}
  1226  		case "SHA3":
  1227  			switch currentTestConfig.securityLevel {
  1228  			case 256:
  1229  				h = sha3.New256()
  1230  			case 384:
  1231  				h = sha3.New384()
  1232  			default:
  1233  				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1234  			}
  1235  		default:
  1236  			t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
  1237  		}
  1238  
  1239  		h.Write(b)
  1240  		h2 := h.Sum(nil)
  1241  		if !bytes.Equal(h1, h2) {
  1242  			t.Fatalf("Discrempancy found in HASH result [%x], [%x]!=[%x]", b, h1, h2)
  1243  		}
  1244  	}
  1245  }
  1246  
  1247  func TestKeyGenFailures(t *testing.T) {
  1248  	var testOpts bccsp.KeyGenOpts
  1249  	ki := currentBCCSP
  1250  	_, err := ki.KeyGen(testOpts)
  1251  	assert.Error(t, err)
  1252  	assert.Contains(t, err.Error(), "Invalid Opts parameter. It must not be nil")
  1253  }
  1254  
  1255  func TestInitialize(t *testing.T) {
  1256  	// Setup PKCS11 library and provide initial set of values
  1257  	lib, pin, label := FindPKCS11Lib()
  1258  
  1259  	// Test for no specified PKCS11 library
  1260  	_, err := (&impl{}).initialize(PKCS11Opts{Library: "", Pin: pin, Label: label})
  1261  	require.Error(t, err)
  1262  	require.Contains(t, err.Error(), "pkcs11: library path not provided")
  1263  
  1264  	// Test for invalid PKCS11 library
  1265  	_, err = (&impl{}).initialize(PKCS11Opts{Library: "badLib", Pin: pin, Label: label})
  1266  	require.Error(t, err)
  1267  	require.Contains(t, err.Error(), "pkcs11: instantiation failed for badLib")
  1268  
  1269  	// Test for invalid label
  1270  	_, err = (&impl{}).initialize(PKCS11Opts{Library: lib, Pin: pin, Label: "badLabel"})
  1271  	require.Error(t, err)
  1272  	require.Contains(t, err.Error(), "could not find token with label")
  1273  
  1274  	// Test for no pin
  1275  	_, err = (&impl{}).initialize(PKCS11Opts{Library: lib, Pin: "", Label: label})
  1276  	require.Error(t, err)
  1277  	require.Contains(t, err.Error(), "Login failed: pkcs11")
  1278  }
  1279  
  1280  func TestNamedCurveFromOID(t *testing.T) {
  1281  	// Test for valid P224 elliptic curve
  1282  	namedCurve := namedCurveFromOID(oidNamedCurveP224)
  1283  	assert.Equal(t, elliptic.P224(), namedCurve, "Did not receive expected named curve for oidNamedCurveP224")
  1284  
  1285  	// Test for valid P256 elliptic curve
  1286  	namedCurve = namedCurveFromOID(oidNamedCurveP256)
  1287  	assert.Equal(t, elliptic.P256(), namedCurve, "Did not receive expected named curve for oidNamedCurveP256")
  1288  
  1289  	// Test for valid P256 elliptic curve
  1290  	namedCurve = namedCurveFromOID(oidNamedCurveP384)
  1291  	assert.Equal(t, elliptic.P384(), namedCurve, "Did not receive expected named curve for oidNamedCurveP384")
  1292  
  1293  	// Test for valid P521 elliptic curve
  1294  	namedCurve = namedCurveFromOID(oidNamedCurveP521)
  1295  	assert.Equal(t, elliptic.P521(), namedCurve, "Did not receive expected named curved for oidNamedCurveP521")
  1296  
  1297  	testAsn1Value := asn1.ObjectIdentifier{4, 9, 15, 1}
  1298  	namedCurve = namedCurveFromOID(testAsn1Value)
  1299  	if namedCurve != nil {
  1300  		t.Fatal("Expected nil to be returned.")
  1301  	}
  1302  }
  1303  
  1304  func TestPKCS11GetSession(t *testing.T) {
  1305  	var sessions []pkcs11.SessionHandle
  1306  	for i := 0; i < 3*sessionCacheSize; i++ {
  1307  		session, err := currentBCCSP.(*impl).getSession()
  1308  		assert.NoError(t, err)
  1309  		sessions = append(sessions, session)
  1310  	}
  1311  
  1312  	// Return all sessions, should leave sessionCacheSize cached
  1313  	for _, session := range sessions {
  1314  		currentBCCSP.(*impl).returnSession(session)
  1315  	}
  1316  
  1317  	// Should be able to get sessionCacheSize cached sessions
  1318  	sessions = nil
  1319  	for i := 0; i < sessionCacheSize; i++ {
  1320  		session, err := currentBCCSP.(*impl).getSession()
  1321  		assert.NoError(t, err)
  1322  		sessions = append(sessions, session)
  1323  	}
  1324  
  1325  	// Cleanup
  1326  	for _, session := range sessions {
  1327  		currentBCCSP.(*impl).returnSession(session)
  1328  	}
  1329  }
  1330  
  1331  func TestSessionHandleCaching(t *testing.T) {
  1332  	defer func(s int) { sessionCacheSize = s }(sessionCacheSize)
  1333  	opts := PKCS11Opts{
  1334  		HashFamily: "SHA2",
  1335  		SecLevel:   256,
  1336  		SoftVerify: false,
  1337  	}
  1338  	opts.Library, opts.Pin, opts.Label = FindPKCS11Lib()
  1339  
  1340  	verifyHandleCache := func(t *testing.T, pi *impl, sess pkcs11.SessionHandle, k bccsp.Key) {
  1341  		pubHandle, err := pi.findKeyPairFromSKI(sess, k.SKI(), publicKeyType)
  1342  		require.NoError(t, err)
  1343  		h, ok := pi.cachedHandle(publicKeyType, k.SKI())
  1344  		require.True(t, ok)
  1345  		require.Equal(t, h, pubHandle)
  1346  
  1347  		privHandle, err := pi.findKeyPairFromSKI(sess, k.SKI(), privateKeyType)
  1348  		require.NoError(t, err)
  1349  		h, ok = pi.cachedHandle(privateKeyType, k.SKI())
  1350  		require.True(t, ok)
  1351  		require.Equal(t, h, privHandle)
  1352  	}
  1353  
  1354  	t.Run("SessionCacheDisabled", func(t *testing.T) {
  1355  		sessionCacheSize = 0
  1356  
  1357  		provider, err := New(opts, currentKS)
  1358  		require.NoError(t, err)
  1359  		pi := provider.(*impl)
  1360  		defer pi.ctx.Destroy()
  1361  
  1362  		require.Nil(t, pi.sessPool, "sessPool channel should be nil")
  1363  		require.Empty(t, pi.sessions, "sessions set should be empty")
  1364  		require.Empty(t, pi.handleCache, "handleCache should be empty")
  1365  
  1366  		sess1, err := pi.getSession()
  1367  		require.NoError(t, err)
  1368  		require.Len(t, pi.sessions, 1, "expected one open session")
  1369  
  1370  		sess2, err := pi.getSession()
  1371  		require.NoError(t, err)
  1372  		require.Len(t, pi.sessions, 2, "expected two open sessions")
  1373  
  1374  		// Generate a key
  1375  		k, err := pi.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
  1376  		require.NoError(t, err)
  1377  		verifyHandleCache(t, pi, sess1, k)
  1378  		require.Len(t, pi.handleCache, 2, "expected two handles in handle cache")
  1379  
  1380  		pi.returnSession(sess1)
  1381  		require.Len(t, pi.sessions, 1, "expected one open session")
  1382  		verifyHandleCache(t, pi, sess1, k)
  1383  		require.Len(t, pi.handleCache, 2, "expected two handles in handle cache")
  1384  
  1385  		pi.returnSession(sess2)
  1386  		require.Empty(t, pi.sessions, "expected sessions to be empty")
  1387  		require.Empty(t, pi.handleCache, "expected handles to be cleared")
  1388  	})
  1389  
  1390  	t.Run("SessionCacheEnabled", func(t *testing.T) {
  1391  		sessionCacheSize = 1
  1392  
  1393  		provider, err := New(opts, currentKS)
  1394  		require.NoError(t, err)
  1395  		pi := provider.(*impl)
  1396  		defer pi.ctx.Destroy()
  1397  
  1398  		require.NotNil(t, pi.sessPool, "sessPool channel should not be nil")
  1399  		require.Equal(t, 1, cap(pi.sessPool))
  1400  		require.Len(t, pi.sessions, 1, "sessions should contain login session")
  1401  		require.Len(t, pi.sessPool, 1, "sessionPool should hold login session")
  1402  		require.Empty(t, pi.handleCache, "handleCache should be empty")
  1403  
  1404  		sess1, err := pi.getSession()
  1405  		require.NoError(t, err)
  1406  		require.Len(t, pi.sessions, 1, "expected one open session (sess1 from login)")
  1407  		require.Len(t, pi.sessPool, 0, "sessionPool should be empty")
  1408  
  1409  		sess2, err := pi.getSession()
  1410  		require.NoError(t, err)
  1411  		require.Len(t, pi.sessions, 2, "expected two open sessions (sess1 and sess2)")
  1412  		require.Len(t, pi.sessPool, 0, "sessionPool should be empty")
  1413  
  1414  		// Generate a key
  1415  		k, err := pi.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
  1416  		require.NoError(t, err)
  1417  		verifyHandleCache(t, pi, sess1, k)
  1418  		require.Len(t, pi.handleCache, 2, "expected two handles in handle cache")
  1419  
  1420  		pi.returnSession(sess1)
  1421  		require.Len(t, pi.sessions, 2, "expected two open sessions (sess2 in-use, sess1 cached)")
  1422  		require.Len(t, pi.sessPool, 1, "sessionPool should have one handle (sess1)")
  1423  		verifyHandleCache(t, pi, sess1, k)
  1424  		require.Len(t, pi.handleCache, 2, "expected two handles in handle cache")
  1425  
  1426  		pi.returnSession(sess2)
  1427  		require.Len(t, pi.sessions, 1, "expected one cached session (sess1)")
  1428  		require.Len(t, pi.sessPool, 1, "sessionPool should have one handle (sess1)")
  1429  		require.Len(t, pi.handleCache, 2, "expected two handles in handle cache")
  1430  
  1431  		sess1, err = pi.getSession()
  1432  		require.NoError(t, err)
  1433  		require.Len(t, pi.sessions, 1, "expected one open session (sess1)")
  1434  		require.Len(t, pi.sessPool, 0, "sessionPool should be empty")
  1435  		require.Len(t, pi.handleCache, 2, "expected two handles in handle cache")
  1436  	})
  1437  }
  1438  
  1439  func TestKeyCache(t *testing.T) {
  1440  	defer func(s int) { sessionCacheSize = s }(sessionCacheSize)
  1441  	sessionCacheSize = 1
  1442  
  1443  	opts := PKCS11Opts{
  1444  		HashFamily: "SHA2",
  1445  		SecLevel:   256,
  1446  		SoftVerify: false,
  1447  	}
  1448  	opts.Library, opts.Pin, opts.Label = FindPKCS11Lib()
  1449  
  1450  	provider, err := New(opts, currentKS)
  1451  	require.NoError(t, err)
  1452  	pi := provider.(*impl)
  1453  	defer pi.ctx.Destroy()
  1454  
  1455  	require.Empty(t, pi.keyCache)
  1456  
  1457  	_, err = pi.GetKey([]byte("nonsense-key"))
  1458  	require.Error(t, err) // message comes from software keystore
  1459  	require.Empty(t, pi.keyCache)
  1460  
  1461  	k, err := pi.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
  1462  	require.NoError(t, err)
  1463  	_, ok := pi.cachedKey(k.SKI())
  1464  	require.False(t, ok, "created keys are not (currently) cached")
  1465  
  1466  	key, err := pi.GetKey(k.SKI())
  1467  	require.NoError(t, err)
  1468  	cached, ok := pi.cachedKey(k.SKI())
  1469  	require.True(t, ok, "key should be cached")
  1470  	require.Same(t, key, cached, "key from cache should be what was found")
  1471  
  1472  	// Kill all valid cached sessions
  1473  	pi.slot = ^uint(0)
  1474  	sess, err := pi.getSession()
  1475  	require.NoError(t, err)
  1476  	require.Len(t, pi.sessions, 1, "should have one active session")
  1477  	require.Len(t, pi.sessPool, 0, "sessionPool should be empty")
  1478  	pi.returnSession(pkcs11.SessionHandle(^uint(0)))
  1479  	require.Len(t, pi.sessions, 1, "should have one active session")
  1480  	require.Len(t, pi.sessPool, 1, "sessionPool should be empty")
  1481  
  1482  	_, ok = pi.cachedKey(k.SKI())
  1483  	require.True(t, ok, "key should remain in cache due to active sessions")
  1484  
  1485  	// Force caches to be cleared
  1486  	pi.returnSession(sess)
  1487  	require.Empty(t, pi.sessions, "sessions should be empty")
  1488  	require.Empty(t, pi.keyCache, "key cache should be empty")
  1489  
  1490  	_, ok = pi.cachedKey(k.SKI())
  1491  	require.False(t, ok, "key should not be in cache")
  1492  }
  1493  
  1494  func TestPKCS11ECKeySignVerify(t *testing.T) {
  1495  	msg1 := []byte("This is my very authentic message")
  1496  	msg2 := []byte("This is my very unauthentic message")
  1497  	hash1, _ := currentBCCSP.Hash(msg1, &bccsp.SHAOpts{})
  1498  	hash2, _ := currentBCCSP.Hash(msg2, &bccsp.SHAOpts{})
  1499  
  1500  	var oid asn1.ObjectIdentifier
  1501  	if currentTestConfig.securityLevel == 256 {
  1502  		oid = oidNamedCurveP256
  1503  	} else if currentTestConfig.securityLevel == 384 {
  1504  		oid = oidNamedCurveP384
  1505  	}
  1506  
  1507  	key, pubKey, err := currentBCCSP.(*impl).generateECKey(oid, true)
  1508  	if err != nil {
  1509  		t.Fatalf("Failed generating Key [%s]", err)
  1510  	}
  1511  
  1512  	R, S, err := currentBCCSP.(*impl).signP11ECDSA(key, hash1)
  1513  	if err != nil {
  1514  		t.Fatalf("Failed signing message [%s]", err)
  1515  	}
  1516  
  1517  	_, _, err = currentBCCSP.(*impl).signP11ECDSA(nil, hash1)
  1518  	assert.Error(t, err)
  1519  	assert.Contains(t, err.Error(), "Private key not found")
  1520  
  1521  	pass, err := currentBCCSP.(*impl).verifyP11ECDSA(key, hash1, R, S, currentTestConfig.securityLevel/8)
  1522  	if err != nil {
  1523  		t.Fatalf("Error verifying message 1 [%s]", err)
  1524  	}
  1525  	if pass == false {
  1526  		t.Fatal("Signature should match!")
  1527  	}
  1528  
  1529  	pass = ecdsa.Verify(pubKey, hash1, R, S)
  1530  	if pass == false {
  1531  		t.Fatal("Signature should match with software verification!")
  1532  	}
  1533  
  1534  	pass, err = currentBCCSP.(*impl).verifyP11ECDSA(key, hash2, R, S, currentTestConfig.securityLevel/8)
  1535  	if err != nil {
  1536  		t.Fatalf("Error verifying message 2 [%s]", err)
  1537  	}
  1538  
  1539  	if pass != false {
  1540  		t.Fatal("Signature should not match!")
  1541  	}
  1542  
  1543  	pass = ecdsa.Verify(pubKey, hash2, R, S)
  1544  	if pass != false {
  1545  		t.Fatal("Signature should not match with software verification!")
  1546  	}
  1547  }
  1548  
  1549  func TestHandleSessionReturn(t *testing.T) {
  1550  	opts := PKCS11Opts{
  1551  		HashFamily: "SHA2",
  1552  		SecLevel:   256,
  1553  		SoftVerify: false,
  1554  	}
  1555  	opts.Library, opts.Pin, opts.Label = FindPKCS11Lib()
  1556  
  1557  	provider, err := New(opts, currentKS)
  1558  	require.NoError(t, err)
  1559  	pi := provider.(*impl)
  1560  	defer pi.ctx.Destroy()
  1561  
  1562  	// Retrieve and destroy default session created during initialization
  1563  	session, err := pi.getSession()
  1564  	require.NoError(t, err)
  1565  	pi.closeSession(session)
  1566  
  1567  	// Verify session pool is empty and place invalid session in pool
  1568  	require.Empty(t, pi.sessPool, "sessionPool should be empty")
  1569  	pi.returnSession(pkcs11.SessionHandle(^uint(0)))
  1570  
  1571  	// Attempt to generate key with invalid session
  1572  	_, err = pi.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
  1573  	require.EqualError(t, err, "Failed generating ECDSA P256 key: P11: keypair generate failed [pkcs11: 0xB3: CKR_SESSION_HANDLE_INVALID]")
  1574  	require.Empty(t, pi.sessPool, "sessionPool should be empty")
  1575  }