github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/bccsp/pkcs11/impl_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  package pkcs11
    17  
    18  import (
    19  	"bytes"
    20  	"crypto"
    21  	"crypto/ecdsa"
    22  	"crypto/elliptic"
    23  	"crypto/rand"
    24  	"crypto/rsa"
    25  	"crypto/sha256"
    26  	"crypto/sha512"
    27  	"crypto/x509"
    28  	"crypto/x509/pkix"
    29  	"encoding/asn1"
    30  	"fmt"
    31  	"hash"
    32  	"math/big"
    33  	"net"
    34  	"os"
    35  	"testing"
    36  	"time"
    37  
    38  	"github.com/hyperledger/fabric/bccsp"
    39  	"github.com/hyperledger/fabric/bccsp/signer"
    40  	"github.com/hyperledger/fabric/bccsp/sw"
    41  	"github.com/hyperledger/fabric/bccsp/utils"
    42  	"golang.org/x/crypto/sha3"
    43  )
    44  
    45  var (
    46  	currentKS         bccsp.KeyStore
    47  	currentBCCSP      bccsp.BCCSP
    48  	currentSWBCCSP    bccsp.BCCSP
    49  	currentTestConfig testConfig
    50  )
    51  
    52  type testConfig struct {
    53  	securityLevel int
    54  	hashFamily    string
    55  }
    56  
    57  func TestMain(m *testing.M) {
    58  	ks := &FileBasedKeyStore{}
    59  	if err := ks.Init(nil, os.TempDir(), false); err != nil {
    60  		fmt.Printf("Failed initiliazing KeyStore [%s]", err)
    61  		os.Exit(-1)
    62  	}
    63  	currentKS = ks
    64  
    65  	lib, pin, label := findPKCS11Lib()
    66  	if enablePKCS11tests {
    67  		err := InitPKCS11(lib, pin, label)
    68  		if err != nil {
    69  			fmt.Printf("Failed initializing PKCS11 library [%s]", err)
    70  			os.Exit(-1)
    71  		}
    72  	} else {
    73  		fmt.Printf("No PKCS11 library found, skipping PKCS11 tests")
    74  	}
    75  
    76  	tests := []testConfig{
    77  		{256, "SHA2"},
    78  		{256, "SHA3"},
    79  		{384, "SHA2"},
    80  		{384, "SHA3"},
    81  	}
    82  
    83  	for _, config := range tests {
    84  		var err error
    85  		currentTestConfig = config
    86  		currentBCCSP, err = New(config.securityLevel, config.hashFamily, currentKS)
    87  		if err != nil {
    88  			fmt.Printf("Failed initiliazing BCCSP at [%d, %s]: [%s]", config.securityLevel, config.hashFamily, err)
    89  			os.Exit(-1)
    90  		}
    91  
    92  		currentSWBCCSP, err = sw.New(config.securityLevel, config.hashFamily, sw.NewDummyKeyStore())
    93  		if err != nil {
    94  			fmt.Printf("Failed initiliazing BCCSP at [%d, %s]: [%s]", config.securityLevel, config.hashFamily, err)
    95  			os.Exit(-1)
    96  		}
    97  		ret := m.Run()
    98  		if ret != 0 {
    99  			fmt.Printf("Failed testing at [%d, %s]", config.securityLevel, config.hashFamily)
   100  			os.Exit(-1)
   101  		}
   102  	}
   103  	os.Exit(0)
   104  }
   105  
   106  func TestInvalidNewParameter(t *testing.T) {
   107  	r, err := New(0, "SHA2", currentKS)
   108  	if err == nil {
   109  		t.Fatal("Error should be different from nil in this case")
   110  	}
   111  	if r != nil {
   112  		t.Fatal("Return value should be equal to nil in this case")
   113  	}
   114  
   115  	r, err = New(256, "SHA8", currentKS)
   116  	if err == nil {
   117  		t.Fatal("Error should be different from nil in this case")
   118  	}
   119  	if r != nil {
   120  		t.Fatal("Return value should be equal to nil in this case")
   121  	}
   122  
   123  	r, err = New(256, "SHA2", nil)
   124  	if err == nil {
   125  		t.Fatal("Error should be different from nil in this case")
   126  	}
   127  	if r != nil {
   128  		t.Fatal("Return value should be equal to nil in this case")
   129  	}
   130  
   131  	r, err = New(0, "SHA3", nil)
   132  	if err == nil {
   133  		t.Fatal("Error should be different from nil in this case")
   134  	}
   135  	if r != nil {
   136  		t.Fatal("Return value should be equal to nil in this case")
   137  	}
   138  
   139  	r, err = NewDefaultSecurityLevel("")
   140  	if err == nil {
   141  		t.Fatal("Error should be different from nil in this case")
   142  	}
   143  	if r != nil {
   144  		t.Fatal("Return value should be equal to nil in this case")
   145  	}
   146  }
   147  
   148  func TestInvalidSKI(t *testing.T) {
   149  	k, err := currentBCCSP.GetKey(nil)
   150  	if err == nil {
   151  		t.Fatal("Error should be different from nil in this case")
   152  	}
   153  	if k != nil {
   154  		t.Fatal("Return value should be equal to nil in this case")
   155  	}
   156  
   157  	k, err = currentBCCSP.GetKey([]byte{0, 1, 2, 3, 4, 5, 6})
   158  	if err == nil {
   159  		t.Fatal("Error should be different from nil in this case")
   160  	}
   161  	if k != nil {
   162  		t.Fatal("Return value should be equal to nil in this case")
   163  	}
   164  }
   165  
   166  func TestKeyGenECDSAOpts(t *testing.T) {
   167  	// Curve P256
   168  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
   169  	if err != nil {
   170  		t.Fatalf("Failed generating ECDSA P256 key [%s]", err)
   171  	}
   172  	if k == nil {
   173  		t.Fatal("Failed generating ECDSA P256 key. Key must be different from nil")
   174  	}
   175  	if !k.Private() {
   176  		t.Fatal("Failed generating ECDSA P256 key. Key should be private")
   177  	}
   178  	if k.Symmetric() {
   179  		t.Fatal("Failed generating ECDSA P256 key. Key should be asymmetric")
   180  	}
   181  
   182  	ecdsaKey := k.(*ecdsaPrivateKey).pub
   183  	if elliptic.P256() != ecdsaKey.pub.Curve {
   184  		t.Fatal("P256 generated key in invalid. The curve must be P256.")
   185  	}
   186  
   187  	// Curve P384
   188  	k, err = currentBCCSP.KeyGen(&bccsp.ECDSAP384KeyGenOpts{Temporary: false})
   189  	if err != nil {
   190  		t.Fatalf("Failed generating ECDSA P384 key [%s]", err)
   191  	}
   192  	if k == nil {
   193  		t.Fatal("Failed generating ECDSA P384 key. Key must be different from nil")
   194  	}
   195  	if !k.Private() {
   196  		t.Fatal("Failed generating ECDSA P384 key. Key should be private")
   197  	}
   198  	if k.Symmetric() {
   199  		t.Fatal("Failed generating ECDSA P384 key. Key should be asymmetric")
   200  	}
   201  
   202  	ecdsaKey = k.(*ecdsaPrivateKey).pub
   203  	if elliptic.P384() != ecdsaKey.pub.Curve {
   204  		t.Fatal("P256 generated key in invalid. The curve must be P384.")
   205  	}
   206  }
   207  
   208  func TestKeyGenRSAOpts(t *testing.T) {
   209  	// 1024
   210  	k, err := currentBCCSP.KeyGen(&bccsp.RSA1024KeyGenOpts{Temporary: false})
   211  	if err != nil {
   212  		t.Fatalf("Failed generating RSA 1024 key [%s]", err)
   213  	}
   214  	if k == nil {
   215  		t.Fatal("Failed generating RSA 1024 key. Key must be different from nil")
   216  	}
   217  	if !k.Private() {
   218  		t.Fatal("Failed generating RSA 1024 key. Key should be private")
   219  	}
   220  	if k.Symmetric() {
   221  		t.Fatal("Failed generating RSA 1024 key. Key should be asymmetric")
   222  	}
   223  
   224  	rsaKey := k.(*rsaPrivateKey).privKey
   225  	if rsaKey.N.BitLen() != 1024 {
   226  		t.Fatal("1024 RSA generated key in invalid. Modulus be of length 1024.")
   227  	}
   228  	if rsaKey.D.Cmp(big.NewInt(0)) == 0 {
   229  		t.Fatal("1024 RSA generated key in invalid. Private key must be different from 0.")
   230  	}
   231  	if rsaKey.E < 3 {
   232  		t.Fatal("1024 RSA generated key in invalid. Private key must be different from 0.")
   233  	}
   234  
   235  	// 2048
   236  	k, err = currentBCCSP.KeyGen(&bccsp.RSA2048KeyGenOpts{Temporary: false})
   237  	if err != nil {
   238  		t.Fatalf("Failed generating RSA 2048 key [%s]", err)
   239  	}
   240  	if k == nil {
   241  		t.Fatal("Failed generating RSA 2048 key. Key must be different from nil")
   242  	}
   243  	if !k.Private() {
   244  		t.Fatal("Failed generating RSA 2048 key. Key should be private")
   245  	}
   246  	if k.Symmetric() {
   247  		t.Fatal("Failed generating RSA 2048 key. Key should be asymmetric")
   248  	}
   249  
   250  	rsaKey = k.(*rsaPrivateKey).privKey
   251  	if rsaKey.N.BitLen() != 2048 {
   252  		t.Fatal("2048 RSA generated key in invalid. Modulus be of length 2048.")
   253  	}
   254  	if rsaKey.D.Cmp(big.NewInt(0)) == 0 {
   255  		t.Fatal("2048 RSA generated key in invalid. Private key must be different from 0.")
   256  	}
   257  	if rsaKey.E < 3 {
   258  		t.Fatal("2048 RSA generated key in invalid. Private key must be different from 0.")
   259  	}
   260  
   261  	/*
   262  		// Skipping these tests because they take too much time to run.
   263  		// 3072
   264  		k, err = currentBCCSP.KeyGen(&bccsp.RSA3072KeyGenOpts{Temporary: false})
   265  		if err != nil {
   266  			t.Fatalf("Failed generating RSA 3072 key [%s]", err)
   267  		}
   268  		if k == nil {
   269  			t.Fatal("Failed generating RSA 3072 key. Key must be different from nil")
   270  		}
   271  		if !k.Private() {
   272  			t.Fatal("Failed generating RSA 3072 key. Key should be private")
   273  		}
   274  		if k.Symmetric() {
   275  			t.Fatal("Failed generating RSA 3072 key. Key should be asymmetric")
   276  		}
   277  
   278  		rsaKey = k.(*rsaPrivateKey).privKey
   279  		if rsaKey.N.BitLen() != 3072 {
   280  			t.Fatal("3072 RSA generated key in invalid. Modulus be of length 3072.")
   281  		}
   282  		if rsaKey.D.Cmp(big.NewInt(0)) == 0 {
   283  			t.Fatal("3072 RSA generated key in invalid. Private key must be different from 0.")
   284  		}
   285  		if rsaKey.E < 3 {
   286  			t.Fatal("3072 RSA generated key in invalid. Private key must be different from 0.")
   287  		}
   288  
   289  		// 4096
   290  		k, err = currentBCCSP.KeyGen(&bccsp.RSA4096KeyGenOpts{Temporary: false})
   291  		if err != nil {
   292  			t.Fatalf("Failed generating RSA 4096 key [%s]", err)
   293  		}
   294  		if k == nil {
   295  			t.Fatal("Failed generating RSA 4096 key. Key must be different from nil")
   296  		}
   297  		if !k.Private() {
   298  			t.Fatal("Failed generating RSA 4096 key. Key should be private")
   299  		}
   300  		if k.Symmetric() {
   301  			t.Fatal("Failed generating RSA 4096 key. Key should be asymmetric")
   302  		}
   303  
   304  		rsaKey = k.(*rsaPrivateKey).privKey
   305  		if rsaKey.N.BitLen() != 4096 {
   306  			t.Fatal("4096 RSA generated key in invalid. Modulus be of length 4096.")
   307  		}
   308  		if rsaKey.D.Cmp(big.NewInt(0)) == 0 {
   309  			t.Fatal("4096 RSA generated key in invalid. Private key must be different from 0.")
   310  		}
   311  		if rsaKey.E < 3 {
   312  			t.Fatal("4096 RSA generated key in invalid. Private key must be different from 0.")
   313  		}
   314  	*/
   315  }
   316  
   317  func TestKeyGenAESOpts(t *testing.T) {
   318  	// AES 128
   319  	k, err := currentBCCSP.KeyGen(&bccsp.AES128KeyGenOpts{Temporary: false})
   320  	if err != nil {
   321  		t.Fatalf("Failed generating AES 128 key [%s]", err)
   322  	}
   323  	if k == nil {
   324  		t.Fatal("Failed generating AES 128 key. Key must be different from nil")
   325  	}
   326  	if !k.Private() {
   327  		t.Fatal("Failed generating AES 128 key. Key should be private")
   328  	}
   329  	if !k.Symmetric() {
   330  		t.Fatal("Failed generating AES 128 key. Key should be symmetric")
   331  	}
   332  
   333  	aesKey := k.(*aesPrivateKey).privKey
   334  	if len(aesKey) != 16 {
   335  		t.Fatal("AES Key generated key in invalid. The key must have length 16.")
   336  	}
   337  
   338  	// AES 192
   339  	k, err = currentBCCSP.KeyGen(&bccsp.AES192KeyGenOpts{Temporary: false})
   340  	if err != nil {
   341  		t.Fatalf("Failed generating AES 192 key [%s]", err)
   342  	}
   343  	if k == nil {
   344  		t.Fatal("Failed generating AES 192 key. Key must be different from nil")
   345  	}
   346  	if !k.Private() {
   347  		t.Fatal("Failed generating AES 192 key. Key should be private")
   348  	}
   349  	if !k.Symmetric() {
   350  		t.Fatal("Failed generating AES 192 key. Key should be symmetric")
   351  	}
   352  
   353  	aesKey = k.(*aesPrivateKey).privKey
   354  	if len(aesKey) != 24 {
   355  		t.Fatal("AES Key generated key in invalid. The key must have length 16.")
   356  	}
   357  
   358  	// AES 256
   359  	k, err = currentBCCSP.KeyGen(&bccsp.AES256KeyGenOpts{Temporary: false})
   360  	if err != nil {
   361  		t.Fatalf("Failed generating AES 256 key [%s]", err)
   362  	}
   363  	if k == nil {
   364  		t.Fatal("Failed generating AES 256 key. Key must be different from nil")
   365  	}
   366  	if !k.Private() {
   367  		t.Fatal("Failed generating AES 256 key. Key should be private")
   368  	}
   369  	if !k.Symmetric() {
   370  		t.Fatal("Failed generating AES 256 key. Key should be symmetric")
   371  	}
   372  
   373  	aesKey = k.(*aesPrivateKey).privKey
   374  	if len(aesKey) != 32 {
   375  		t.Fatal("AES Key generated key in invalid. The key must have length 16.")
   376  	}
   377  }
   378  
   379  func TestHashOpts(t *testing.T) {
   380  	msg := []byte("abcd")
   381  
   382  	// SHA256
   383  	digest1, err := currentBCCSP.Hash(msg, &bccsp.SHA256Opts{})
   384  	if err != nil {
   385  		t.Fatalf("Failed computing SHA256 [%s]", err)
   386  	}
   387  
   388  	h := sha256.New()
   389  	h.Write(msg)
   390  	digest2 := h.Sum(nil)
   391  
   392  	if !bytes.Equal(digest1, digest2) {
   393  		t.Fatalf("Different SHA256 computed. [%x][%x]", digest1, digest2)
   394  	}
   395  
   396  	// SHA384
   397  	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA384Opts{})
   398  	if err != nil {
   399  		t.Fatalf("Failed computing SHA384 [%s]", err)
   400  	}
   401  
   402  	h = sha512.New384()
   403  	h.Write(msg)
   404  	digest2 = h.Sum(nil)
   405  
   406  	if !bytes.Equal(digest1, digest2) {
   407  		t.Fatalf("Different SHA384 computed. [%x][%x]", digest1, digest2)
   408  	}
   409  
   410  	// SHA3_256O
   411  	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_256Opts{})
   412  	if err != nil {
   413  		t.Fatalf("Failed computing SHA3_256 [%s]", err)
   414  	}
   415  
   416  	h = sha3.New256()
   417  	h.Write(msg)
   418  	digest2 = h.Sum(nil)
   419  
   420  	if !bytes.Equal(digest1, digest2) {
   421  		t.Fatalf("Different SHA3_256 computed. [%x][%x]", digest1, digest2)
   422  	}
   423  
   424  	// SHA3_384
   425  	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_384Opts{})
   426  	if err != nil {
   427  		t.Fatalf("Failed computing SHA3_384 [%s]", err)
   428  	}
   429  
   430  	h = sha3.New384()
   431  	h.Write(msg)
   432  	digest2 = h.Sum(nil)
   433  
   434  	if !bytes.Equal(digest1, digest2) {
   435  		t.Fatalf("Different SHA3_384 computed. [%x][%x]", digest1, digest2)
   436  	}
   437  }
   438  
   439  func TestECDSAKeyGenEphemeral(t *testing.T) {
   440  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: true})
   441  	if err != nil {
   442  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   443  	}
   444  	if k == nil {
   445  		t.Fatal("Failed generating ECDSA key. Key must be different from nil")
   446  	}
   447  	if !k.Private() {
   448  		t.Fatal("Failed generating ECDSA key. Key should be private")
   449  	}
   450  	if k.Symmetric() {
   451  		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
   452  	}
   453  	raw, err := k.Bytes()
   454  	if err == nil {
   455  		t.Fatal("Failed marshalling to bytes. Marshalling must fail.")
   456  	}
   457  	if len(raw) != 0 {
   458  		t.Fatal("Failed marshalling to bytes. Output should be 0 bytes")
   459  	}
   460  	pk, err := k.PublicKey()
   461  	if err != nil {
   462  		t.Fatalf("Failed getting corresponding public key [%s]", err)
   463  	}
   464  	if pk == nil {
   465  		t.Fatal("Public key must be different from nil.")
   466  	}
   467  }
   468  
   469  func TestECDSAPrivateKeySKI(t *testing.T) {
   470  
   471  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   472  	if err != nil {
   473  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   474  	}
   475  
   476  	ski := k.SKI()
   477  	if len(ski) == 0 {
   478  		t.Fatal("SKI not valid. Zero length.")
   479  	}
   480  }
   481  
   482  func TestECDSAKeyGenNonEphemeral(t *testing.T) {
   483  
   484  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   485  	if err != nil {
   486  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   487  	}
   488  	if k == nil {
   489  		t.Fatal("Failed generating ECDSA key. Key must be different from nil")
   490  	}
   491  	if !k.Private() {
   492  		t.Fatal("Failed generating ECDSA key. Key should be private")
   493  	}
   494  	if k.Symmetric() {
   495  		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
   496  	}
   497  }
   498  
   499  func TestECDSAGetKeyBySKI(t *testing.T) {
   500  
   501  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   502  	if err != nil {
   503  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   504  	}
   505  
   506  	k2, err := currentBCCSP.GetKey(k.SKI())
   507  	if err != nil {
   508  		t.Fatalf("Failed getting ECDSA key [%s]", err)
   509  	}
   510  	if k2 == nil {
   511  		t.Fatal("Failed getting ECDSA key. Key must be different from nil")
   512  	}
   513  	if !k2.Private() {
   514  		t.Fatal("Failed getting ECDSA key. Key should be private")
   515  	}
   516  	if k2.Symmetric() {
   517  		t.Fatal("Failed getting ECDSA key. Key should be asymmetric")
   518  	}
   519  
   520  	// Check that the SKIs are the same
   521  	if !bytes.Equal(k.SKI(), k2.SKI()) {
   522  		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
   523  	}
   524  }
   525  
   526  func TestECDSAPublicKeyFromPrivateKey(t *testing.T) {
   527  
   528  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   529  	if err != nil {
   530  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   531  	}
   532  
   533  	pk, err := k.PublicKey()
   534  	if err != nil {
   535  		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
   536  	}
   537  	if pk == nil {
   538  		t.Fatal("Failed getting public key from private ECDSA key. Key must be different from nil")
   539  	}
   540  	if pk.Private() {
   541  		t.Fatal("Failed generating ECDSA key. Key should be public")
   542  	}
   543  	if pk.Symmetric() {
   544  		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
   545  	}
   546  }
   547  
   548  func TestECDSAPublicKeyBytes(t *testing.T) {
   549  
   550  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   551  	if err != nil {
   552  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   553  	}
   554  
   555  	pk, err := k.PublicKey()
   556  	if err != nil {
   557  		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
   558  	}
   559  
   560  	raw, err := pk.Bytes()
   561  	if err != nil {
   562  		t.Fatalf("Failed marshalling ECDSA public key [%s]", err)
   563  	}
   564  	if len(raw) == 0 {
   565  		t.Fatal("Failed marshalling ECDSA public key. Zero length")
   566  	}
   567  }
   568  
   569  func TestECDSAPublicKeySKI(t *testing.T) {
   570  
   571  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   572  	if err != nil {
   573  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   574  	}
   575  
   576  	pk, err := k.PublicKey()
   577  	if err != nil {
   578  		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
   579  	}
   580  
   581  	ski := pk.SKI()
   582  	if len(ski) == 0 {
   583  		t.Fatal("SKI not valid. Zero length.")
   584  	}
   585  }
   586  
   587  func TestECDSAKeyReRand(t *testing.T) {
   588  
   589  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   590  	if err != nil {
   591  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   592  	}
   593  	if k == nil {
   594  		t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key must be different from nil")
   595  	}
   596  
   597  	reRandomizedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.ECDSAReRandKeyOpts{Temporary: false, Expansion: []byte{1}})
   598  	if err != nil {
   599  		t.Fatalf("Failed re-randomizing ECDSA key [%s]", err)
   600  	}
   601  	if !reRandomizedKey.Private() {
   602  		t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key should be private")
   603  	}
   604  	if reRandomizedKey.Symmetric() {
   605  		t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key should be asymmetric")
   606  	}
   607  
   608  	k2, err := k.PublicKey()
   609  	if err != nil {
   610  		t.Fatalf("Failed getting public ECDSA key from private [%s]", err)
   611  	}
   612  	if k2 == nil {
   613  		t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key must be different from nil")
   614  	}
   615  
   616  	reRandomizedKey2, err := currentBCCSP.KeyDeriv(k2, &bccsp.ECDSAReRandKeyOpts{Temporary: false, Expansion: []byte{1}})
   617  	if err != nil {
   618  		t.Fatalf("Failed re-randomizing ECDSA key [%s]", err)
   619  	}
   620  
   621  	if reRandomizedKey2.Private() {
   622  		t.Fatal("Re-randomized public Key must remain public")
   623  	}
   624  	if reRandomizedKey2.Symmetric() {
   625  		t.Fatal("Re-randomized ECDSA asymmetric key must remain asymmetric")
   626  	}
   627  
   628  	if false == bytes.Equal(reRandomizedKey.SKI(), reRandomizedKey2.SKI()) {
   629  		t.Fatal("Re-randomized ECDSA Private- or Public-Keys must end up having the same SKI")
   630  	}
   631  }
   632  
   633  func TestECDSASign(t *testing.T) {
   634  
   635  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   636  	if err != nil {
   637  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   638  	}
   639  
   640  	msg := []byte("Hello World")
   641  
   642  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   643  	if err != nil {
   644  		t.Fatalf("Failed computing HASH [%s]", err)
   645  	}
   646  
   647  	signature, err := currentBCCSP.Sign(k, digest, nil)
   648  	if err != nil {
   649  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   650  	}
   651  	if len(signature) == 0 {
   652  		t.Fatal("Failed generating ECDSA key. Signature must be different from nil")
   653  	}
   654  }
   655  
   656  func TestECDSAVerify(t *testing.T) {
   657  
   658  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   659  	if err != nil {
   660  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   661  	}
   662  
   663  	msg := []byte("Hello World")
   664  
   665  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   666  	if err != nil {
   667  		t.Fatalf("Failed computing HASH [%s]", err)
   668  	}
   669  
   670  	signature, err := currentBCCSP.Sign(k, digest, nil)
   671  	if err != nil {
   672  		t.Fatalf("Failed generating ECDSA signature  [%s]", err)
   673  	}
   674  
   675  	valid, err := currentBCCSP.Verify(k, signature, digest, nil)
   676  	if err != nil {
   677  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   678  	}
   679  	if !valid {
   680  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   681  	}
   682  
   683  	pk, err := k.PublicKey()
   684  	if err != nil {
   685  		t.Fatalf("Failed getting corresponding public key [%s]", err)
   686  	}
   687  
   688  	valid, err = currentBCCSP.Verify(pk, signature, digest, nil)
   689  	if err != nil {
   690  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   691  	}
   692  	if !valid {
   693  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   694  	}
   695  
   696  	// Import the exported public key
   697  	pkRaw, err := pk.Bytes()
   698  	if err != nil {
   699  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   700  	}
   701  
   702  	// Store public key
   703  	_, err = currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false})
   704  	if err != nil {
   705  		t.Fatalf("Failed storing corresponding public key [%s]", err)
   706  	}
   707  
   708  	pk2, err := currentBCCSP.GetKey(pk.SKI())
   709  	if err != nil {
   710  		t.Fatalf("Failed retrieving corresponding public key [%s]", err)
   711  	}
   712  
   713  	valid, err = currentBCCSP.Verify(pk2, signature, digest, nil)
   714  	if err != nil {
   715  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   716  	}
   717  	if !valid {
   718  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   719  	}
   720  }
   721  
   722  func TestECDSAKeyDeriv(t *testing.T) {
   723  
   724  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   725  	if err != nil {
   726  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   727  	}
   728  
   729  	reRandomizedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.ECDSAReRandKeyOpts{Temporary: false, Expansion: []byte{1}})
   730  	if err != nil {
   731  		t.Fatalf("Failed re-randomizing ECDSA key [%s]", err)
   732  	}
   733  
   734  	msg := []byte("Hello World")
   735  
   736  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   737  	if err != nil {
   738  		t.Fatalf("Failed computing HASH [%s]", err)
   739  	}
   740  
   741  	signature, err := currentBCCSP.Sign(reRandomizedKey, digest, nil)
   742  	if err != nil {
   743  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   744  	}
   745  
   746  	valid, err := currentBCCSP.Verify(reRandomizedKey, signature, digest, nil)
   747  	if err != nil {
   748  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   749  	}
   750  	if !valid {
   751  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   752  	}
   753  }
   754  
   755  func TestECDSAKeyImportFromExportedKey(t *testing.T) {
   756  
   757  	// Generate an ECDSA key
   758  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   759  	if err != nil {
   760  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   761  	}
   762  
   763  	// Export the public key
   764  	pk, err := k.PublicKey()
   765  	if err != nil {
   766  		t.Fatalf("Failed getting ECDSA public key [%s]", err)
   767  	}
   768  
   769  	pkRaw, err := pk.Bytes()
   770  	if err != nil {
   771  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   772  	}
   773  
   774  	// Import the exported public key
   775  	pk2, err := currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false})
   776  	if err != nil {
   777  		t.Fatalf("Failed importing ECDSA public key [%s]", err)
   778  	}
   779  	if pk2 == nil {
   780  		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
   781  	}
   782  
   783  	// Sign and verify with the imported public key
   784  	msg := []byte("Hello World")
   785  
   786  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   787  	if err != nil {
   788  		t.Fatalf("Failed computing HASH [%s]", err)
   789  	}
   790  
   791  	signature, err := currentBCCSP.Sign(k, digest, nil)
   792  	if err != nil {
   793  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   794  	}
   795  
   796  	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
   797  	if err != nil {
   798  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   799  	}
   800  	if !valid {
   801  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   802  	}
   803  }
   804  
   805  func TestECDSAKeyImportFromECDSAPublicKey(t *testing.T) {
   806  
   807  	// Generate an ECDSA key
   808  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   809  	if err != nil {
   810  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   811  	}
   812  
   813  	// Export the public key
   814  	pk, err := k.PublicKey()
   815  	if err != nil {
   816  		t.Fatalf("Failed getting ECDSA public key [%s]", err)
   817  	}
   818  
   819  	pkRaw, err := pk.Bytes()
   820  	if err != nil {
   821  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   822  	}
   823  
   824  	pub, err := utils.DERToPublicKey(pkRaw)
   825  	if err != nil {
   826  		t.Fatalf("Failed converting raw to ecdsa.PublicKey [%s]", err)
   827  	}
   828  
   829  	// Import the ecdsa.PublicKey
   830  	pk2, err := currentBCCSP.KeyImport(pub, &bccsp.ECDSAGoPublicKeyImportOpts{Temporary: false})
   831  	if err != nil {
   832  		t.Fatalf("Failed importing ECDSA public key [%s]", err)
   833  	}
   834  	if pk2 == nil {
   835  		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
   836  	}
   837  
   838  	// Sign and verify with the imported public key
   839  	msg := []byte("Hello World")
   840  
   841  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   842  	if err != nil {
   843  		t.Fatalf("Failed computing HASH [%s]", err)
   844  	}
   845  
   846  	signature, err := currentBCCSP.Sign(k, digest, nil)
   847  	if err != nil {
   848  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   849  	}
   850  
   851  	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
   852  	if err != nil {
   853  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   854  	}
   855  	if !valid {
   856  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   857  	}
   858  }
   859  
   860  func TestECDSAKeyImportFromECDSAPrivateKey(t *testing.T) {
   861  
   862  	// Generate an ECDSA key, default is P256
   863  	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   864  	if err != nil {
   865  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   866  	}
   867  
   868  	// Import the ecdsa.PrivateKey
   869  	priv, err := utils.PrivateKeyToDER(key)
   870  	if err != nil {
   871  		t.Fatalf("Failed converting raw to ecdsa.PrivateKey [%s]", err)
   872  	}
   873  
   874  	sk, err := currentBCCSP.KeyImport(priv, &bccsp.ECDSAPrivateKeyImportOpts{Temporary: false})
   875  	if err != nil {
   876  		t.Fatalf("Failed importing ECDSA private key [%s]", err)
   877  	}
   878  	if sk == nil {
   879  		t.Fatal("Failed importing ECDSA private key. Return BCCSP key cannot be nil.")
   880  	}
   881  
   882  	// Import the ecdsa.PublicKey
   883  	pub, err := utils.PublicKeyToDER(&key.PublicKey)
   884  	if err != nil {
   885  		t.Fatalf("Failed converting raw to ecdsa.PublicKey [%s]", err)
   886  	}
   887  
   888  	pk, err := currentBCCSP.KeyImport(pub, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false})
   889  
   890  	if err != nil {
   891  		t.Fatalf("Failed importing ECDSA public key [%s]", err)
   892  	}
   893  	if pk == nil {
   894  		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
   895  	}
   896  
   897  	// Sign and verify with the imported public key
   898  	msg := []byte("Hello World")
   899  
   900  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
   901  	if err != nil {
   902  		t.Fatalf("Failed computing HASH [%s]", err)
   903  	}
   904  
   905  	signature, err := currentBCCSP.Sign(sk, digest, nil)
   906  	if err != nil {
   907  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
   908  	}
   909  
   910  	valid, err := currentBCCSP.Verify(pk, signature, digest, nil)
   911  	if err != nil {
   912  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
   913  	}
   914  	if !valid {
   915  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
   916  	}
   917  }
   918  
   919  func TestKeyImportFromX509ECDSAPublicKey(t *testing.T) {
   920  
   921  	// Generate an ECDSA key
   922  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
   923  	if err != nil {
   924  		t.Fatalf("Failed generating ECDSA key [%s]", err)
   925  	}
   926  
   927  	// Generate a self-signed certificate
   928  	testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
   929  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
   930  	extraExtensionData := []byte("extra extension")
   931  	commonName := "test.example.com"
   932  	template := x509.Certificate{
   933  		SerialNumber: big.NewInt(1),
   934  		Subject: pkix.Name{
   935  			CommonName:   commonName,
   936  			Organization: []string{"Σ Acme Co"},
   937  			Country:      []string{"US"},
   938  			ExtraNames: []pkix.AttributeTypeAndValue{
   939  				{
   940  					Type:  []int{2, 5, 4, 42},
   941  					Value: "Gopher",
   942  				},
   943  				// This should override the Country, above.
   944  				{
   945  					Type:  []int{2, 5, 4, 6},
   946  					Value: "NL",
   947  				},
   948  			},
   949  		},
   950  		NotBefore: time.Now().Add(-1 * time.Hour),
   951  		NotAfter:  time.Now().Add(1 * time.Hour),
   952  
   953  		SignatureAlgorithm: x509.ECDSAWithSHA256,
   954  
   955  		SubjectKeyId: []byte{1, 2, 3, 4},
   956  		KeyUsage:     x509.KeyUsageCertSign,
   957  
   958  		ExtKeyUsage:        testExtKeyUsage,
   959  		UnknownExtKeyUsage: testUnknownExtKeyUsage,
   960  
   961  		BasicConstraintsValid: true,
   962  		IsCA: true,
   963  
   964  		OCSPServer:            []string{"http://ocurrentBCCSP.example.com"},
   965  		IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
   966  
   967  		DNSNames:       []string{"test.example.com"},
   968  		EmailAddresses: []string{"gopher@golang.org"},
   969  		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   970  
   971  		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
   972  		PermittedDNSDomains: []string{".example.com", "example.com"},
   973  
   974  		CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
   975  
   976  		ExtraExtensions: []pkix.Extension{
   977  			{
   978  				Id:    []int{1, 2, 3, 4},
   979  				Value: extraExtensionData,
   980  			},
   981  		},
   982  	}
   983  
   984  	cryptoSigner := &signer.CryptoSigner{}
   985  	err = cryptoSigner.Init(currentBCCSP, k)
   986  	if err != nil {
   987  		t.Fatalf("Failed initializing CyrptoSigner [%s]", err)
   988  	}
   989  
   990  	// Export the public key
   991  	pk, err := k.PublicKey()
   992  	if err != nil {
   993  		t.Fatalf("Failed getting ECDSA public key [%s]", err)
   994  	}
   995  
   996  	pkRaw, err := pk.Bytes()
   997  	if err != nil {
   998  		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
   999  	}
  1000  
  1001  	pub, err := utils.DERToPublicKey(pkRaw)
  1002  	if err != nil {
  1003  		t.Fatalf("Failed converting raw to ECDSA.PublicKey [%s]", err)
  1004  	}
  1005  
  1006  	certRaw, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, cryptoSigner)
  1007  	if err != nil {
  1008  		t.Fatalf("Failed generating self-signed certificate [%s]", err)
  1009  	}
  1010  
  1011  	cert, err := utils.DERToX509Certificate(certRaw)
  1012  	if err != nil {
  1013  		t.Fatalf("Failed generating X509 certificate object from raw [%s]", err)
  1014  	}
  1015  
  1016  	// Import the certificate's public key
  1017  	pk2, err := currentBCCSP.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: false})
  1018  
  1019  	if err != nil {
  1020  		t.Fatalf("Failed importing ECDSA public key [%s]", err)
  1021  	}
  1022  	if pk2 == nil {
  1023  		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
  1024  	}
  1025  
  1026  	// Sign and verify with the imported public key
  1027  	msg := []byte("Hello World")
  1028  
  1029  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1030  	if err != nil {
  1031  		t.Fatalf("Failed computing HASH [%s]", err)
  1032  	}
  1033  
  1034  	signature, err := currentBCCSP.Sign(k, digest, nil)
  1035  	if err != nil {
  1036  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
  1037  	}
  1038  
  1039  	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
  1040  	if err != nil {
  1041  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
  1042  	}
  1043  	if !valid {
  1044  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
  1045  	}
  1046  }
  1047  
  1048  func TestECDSASignatureEncoding(t *testing.T) {
  1049  	v := []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0xff, 0xf1}
  1050  	_, err := asn1.Unmarshal(v, &ecdsaSignature{})
  1051  	if err == nil {
  1052  		t.Fatalf("Unmarshalling should fail for [% x]", v)
  1053  	}
  1054  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
  1055  
  1056  	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0x00, 0x01}
  1057  	_, err = asn1.Unmarshal(v, &ecdsaSignature{})
  1058  	if err == nil {
  1059  		t.Fatalf("Unmarshalling should fail for [% x]", v)
  1060  	}
  1061  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
  1062  
  1063  	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x01}
  1064  	_, err = asn1.Unmarshal(v, &ecdsaSignature{})
  1065  	if err == nil {
  1066  		t.Fatalf("Unmarshalling should fail for [% x]", v)
  1067  	}
  1068  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
  1069  
  1070  	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x8F}
  1071  	_, err = asn1.Unmarshal(v, &ecdsaSignature{})
  1072  	if err == nil {
  1073  		t.Fatalf("Unmarshalling should fail for [% x]", v)
  1074  	}
  1075  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
  1076  
  1077  	v = []byte{0x30, 0x0A, 0x02, 0x01, 0x8F, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00, 0x8F}
  1078  	_, err = asn1.Unmarshal(v, &ecdsaSignature{})
  1079  	if err == nil {
  1080  		t.Fatalf("Unmarshalling should fail for [% x]", v)
  1081  	}
  1082  	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)
  1083  
  1084  }
  1085  
  1086  func TestECDSALowS(t *testing.T) {
  1087  	// Ensure that signature with low-S are generated
  1088  	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
  1089  	if err != nil {
  1090  		t.Fatalf("Failed generating ECDSA key [%s]", err)
  1091  	}
  1092  
  1093  	msg := []byte("Hello World")
  1094  
  1095  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1096  	if err != nil {
  1097  		t.Fatalf("Failed computing HASH [%s]", err)
  1098  	}
  1099  
  1100  	signature, err := currentBCCSP.Sign(k, digest, nil)
  1101  	if err != nil {
  1102  		t.Fatalf("Failed generating ECDSA signature [%s]", err)
  1103  	}
  1104  
  1105  	R, S, err := unmarshalECDSASignature(signature)
  1106  	if err != nil {
  1107  		t.Fatalf("Failed unmarshalling signature [%s]", err)
  1108  	}
  1109  
  1110  	if S.Cmp(curveHalfOrders[k.(*ecdsaPrivateKey).pub.pub.Curve]) >= 0 {
  1111  		t.Fatal("Invalid signature. It must have low-S")
  1112  	}
  1113  
  1114  	valid, err := currentBCCSP.Verify(k, signature, digest, nil)
  1115  	if err != nil {
  1116  		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
  1117  	}
  1118  	if !valid {
  1119  		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
  1120  	}
  1121  
  1122  	// Ensure that signature with high-S are rejected.
  1123  	for {
  1124  		R, S, err = signECDSA(k.SKI(), digest)
  1125  		if err != nil {
  1126  			t.Fatalf("Failed generating signature [%s]", err)
  1127  		}
  1128  
  1129  		if S.Cmp(curveHalfOrders[k.(*ecdsaPrivateKey).pub.pub.Curve]) > 0 {
  1130  			break
  1131  		}
  1132  	}
  1133  
  1134  	sig, err := marshalECDSASignature(R, S)
  1135  	if err != nil {
  1136  		t.Fatalf("Failing unmarshalling signature [%s]", err)
  1137  	}
  1138  
  1139  	valid, err = currentBCCSP.Verify(k, sig, digest, nil)
  1140  	if err == nil {
  1141  		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
  1142  	}
  1143  	if valid {
  1144  		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
  1145  	}
  1146  }
  1147  
  1148  func TestAESKeyGen(t *testing.T) {
  1149  
  1150  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1151  	if err != nil {
  1152  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1153  	}
  1154  	if k == nil {
  1155  		t.Fatal("Failed generating AES_256 key. Key must be different from nil")
  1156  	}
  1157  	if !k.Private() {
  1158  		t.Fatal("Failed generating AES_256 key. Key should be private")
  1159  	}
  1160  	if !k.Symmetric() {
  1161  		t.Fatal("Failed generating AES_256 key. Key should be symmetric")
  1162  	}
  1163  
  1164  	pk, err := k.PublicKey()
  1165  	if err == nil {
  1166  		t.Fatal("Error should be different from nil in this case")
  1167  	}
  1168  	if pk != nil {
  1169  		t.Fatal("Return value should be equal to nil in this case")
  1170  	}
  1171  }
  1172  
  1173  func TestAESEncrypt(t *testing.T) {
  1174  
  1175  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1176  	if err != nil {
  1177  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1178  	}
  1179  
  1180  	ct, err := currentBCCSP.Encrypt(k, []byte("Hello World"), &bccsp.AESCBCPKCS7ModeOpts{})
  1181  	if err != nil {
  1182  		t.Fatalf("Failed encrypting [%s]", err)
  1183  	}
  1184  	if len(ct) == 0 {
  1185  		t.Fatal("Failed encrypting. Nil ciphertext")
  1186  	}
  1187  }
  1188  
  1189  func TestAESDecrypt(t *testing.T) {
  1190  
  1191  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1192  	if err != nil {
  1193  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1194  	}
  1195  
  1196  	msg := []byte("Hello World")
  1197  
  1198  	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1199  	if err != nil {
  1200  		t.Fatalf("Failed encrypting [%s]", err)
  1201  	}
  1202  
  1203  	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1204  	if err != nil {
  1205  		t.Fatalf("Failed decrypting [%s]", err)
  1206  	}
  1207  	if len(ct) == 0 {
  1208  		t.Fatal("Failed decrypting. Nil plaintext")
  1209  	}
  1210  
  1211  	if !bytes.Equal(msg, pt) {
  1212  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1213  	}
  1214  }
  1215  
  1216  func TestHMACTruncated256KeyDerivOverAES256Key(t *testing.T) {
  1217  
  1218  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1219  	if err != nil {
  1220  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1221  	}
  1222  
  1223  	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACTruncated256AESDeriveKeyOpts{Temporary: false, Arg: []byte{1}})
  1224  	if err != nil {
  1225  		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
  1226  	}
  1227  	if k == nil {
  1228  		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
  1229  	}
  1230  	if !hmcaedKey.Private() {
  1231  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
  1232  	}
  1233  	if !hmcaedKey.Symmetric() {
  1234  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
  1235  	}
  1236  	raw, err := hmcaedKey.Bytes()
  1237  	if err == nil {
  1238  		t.Fatal("Failed marshalling to bytes. Operation must be forbidden")
  1239  	}
  1240  	if len(raw) != 0 {
  1241  		t.Fatal("Failed marshalling to bytes. Operation must return 0 bytes")
  1242  	}
  1243  
  1244  	msg := []byte("Hello World")
  1245  
  1246  	ct, err := currentBCCSP.Encrypt(hmcaedKey, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1247  	if err != nil {
  1248  		t.Fatalf("Failed encrypting [%s]", err)
  1249  	}
  1250  
  1251  	pt, err := currentBCCSP.Decrypt(hmcaedKey, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1252  	if err != nil {
  1253  		t.Fatalf("Failed decrypting [%s]", err)
  1254  	}
  1255  	if len(ct) == 0 {
  1256  		t.Fatal("Failed decrypting. Nil plaintext")
  1257  	}
  1258  
  1259  	if !bytes.Equal(msg, pt) {
  1260  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1261  	}
  1262  
  1263  }
  1264  
  1265  func TestHMACKeyDerivOverAES256Key(t *testing.T) {
  1266  
  1267  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1268  	if err != nil {
  1269  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1270  	}
  1271  
  1272  	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Temporary: false, Arg: []byte{1}})
  1273  
  1274  	if err != nil {
  1275  		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
  1276  	}
  1277  	if k == nil {
  1278  		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
  1279  	}
  1280  	if !hmcaedKey.Private() {
  1281  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
  1282  	}
  1283  	if !hmcaedKey.Symmetric() {
  1284  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
  1285  	}
  1286  	raw, err := hmcaedKey.Bytes()
  1287  	if err != nil {
  1288  		t.Fatalf("Failed marshalling to bytes [%s]", err)
  1289  	}
  1290  	if len(raw) == 0 {
  1291  		t.Fatal("Failed marshalling to bytes. 0 bytes")
  1292  	}
  1293  }
  1294  
  1295  func TestAES256KeyImport(t *testing.T) {
  1296  
  1297  	raw, err := GetRandomBytes(32)
  1298  	if err != nil {
  1299  		t.Fatalf("Failed generating AES key [%s]", err)
  1300  	}
  1301  
  1302  	k, err := currentBCCSP.KeyImport(raw, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1303  	if err != nil {
  1304  		t.Fatalf("Failed importing AES_256 key [%s]", err)
  1305  	}
  1306  	if k == nil {
  1307  		t.Fatal("Failed importing AES_256 key. Imported Key must be different from nil")
  1308  	}
  1309  	if !k.Private() {
  1310  		t.Fatal("Failed HMACing AES_256 key. Imported Key should be private")
  1311  	}
  1312  	if !k.Symmetric() {
  1313  		t.Fatal("Failed HMACing AES_256 key. Imported Key should be asymmetric")
  1314  	}
  1315  	raw, err = k.Bytes()
  1316  	if err == nil {
  1317  		t.Fatal("Failed marshalling to bytes. Marshalling must fail.")
  1318  	}
  1319  	if len(raw) != 0 {
  1320  		t.Fatal("Failed marshalling to bytes. Output should be 0 bytes")
  1321  	}
  1322  
  1323  	msg := []byte("Hello World")
  1324  
  1325  	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1326  	if err != nil {
  1327  		t.Fatalf("Failed encrypting [%s]", err)
  1328  	}
  1329  
  1330  	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1331  	if err != nil {
  1332  		t.Fatalf("Failed decrypting [%s]", err)
  1333  	}
  1334  	if len(ct) == 0 {
  1335  		t.Fatal("Failed decrypting. Nil plaintext")
  1336  	}
  1337  
  1338  	if !bytes.Equal(msg, pt) {
  1339  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1340  	}
  1341  }
  1342  
  1343  func TestAES256KeyImportBadPaths(t *testing.T) {
  1344  
  1345  	_, err := currentBCCSP.KeyImport(nil, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1346  	if err == nil {
  1347  		t.Fatal("Failed importing key. Must fail on importing nil key")
  1348  	}
  1349  
  1350  	_, err = currentBCCSP.KeyImport([]byte{1}, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1351  	if err == nil {
  1352  		t.Fatal("Failed importing key. Must fail on importing a key with an invalid length")
  1353  	}
  1354  }
  1355  
  1356  func TestAES256KeyGenSKI(t *testing.T) {
  1357  
  1358  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1359  	if err != nil {
  1360  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1361  	}
  1362  
  1363  	k2, err := currentBCCSP.GetKey(k.SKI())
  1364  	if err != nil {
  1365  		t.Fatalf("Failed getting AES_256 key [%s]", err)
  1366  	}
  1367  	if k2 == nil {
  1368  		t.Fatal("Failed getting AES_256 key. Key must be different from nil")
  1369  	}
  1370  	if !k2.Private() {
  1371  		t.Fatal("Failed getting AES_256 key. Key should be private")
  1372  	}
  1373  	if !k2.Symmetric() {
  1374  		t.Fatal("Failed getting AES_256 key. Key should be symmetric")
  1375  	}
  1376  
  1377  	// Check that the SKIs are the same
  1378  	if !bytes.Equal(k.SKI(), k2.SKI()) {
  1379  		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
  1380  	}
  1381  
  1382  }
  1383  
  1384  func TestSHA(t *testing.T) {
  1385  
  1386  	for i := 0; i < 100; i++ {
  1387  		b, err := GetRandomBytes(i)
  1388  		if err != nil {
  1389  			t.Fatalf("Failed getting random bytes [%s]", err)
  1390  		}
  1391  
  1392  		h1, err := currentBCCSP.Hash(b, &bccsp.SHAOpts{})
  1393  		if err != nil {
  1394  			t.Fatalf("Failed computing SHA [%s]", err)
  1395  		}
  1396  
  1397  		var h hash.Hash
  1398  		switch currentTestConfig.hashFamily {
  1399  		case "SHA2":
  1400  			switch currentTestConfig.securityLevel {
  1401  			case 256:
  1402  				h = sha256.New()
  1403  			case 384:
  1404  				h = sha512.New384()
  1405  			default:
  1406  				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1407  			}
  1408  		case "SHA3":
  1409  			switch currentTestConfig.securityLevel {
  1410  			case 256:
  1411  				h = sha3.New256()
  1412  			case 384:
  1413  				h = sha3.New384()
  1414  			default:
  1415  				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1416  			}
  1417  		default:
  1418  			t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
  1419  		}
  1420  
  1421  		h.Write(b)
  1422  		h2 := h.Sum(nil)
  1423  		if !bytes.Equal(h1, h2) {
  1424  			t.Fatalf("Discrempancy found in HASH result [%x], [%x]!=[%x]", b, h1, h2)
  1425  		}
  1426  	}
  1427  }
  1428  
  1429  func TestRSAKeyGenEphemeral(t *testing.T) {
  1430  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: true})
  1431  	if err != nil {
  1432  		t.Fatalf("Failed generating RSA key [%s]", err)
  1433  	}
  1434  	if k == nil {
  1435  		t.Fatal("Failed generating RSA key. Key must be different from nil")
  1436  	}
  1437  	if !k.Private() {
  1438  		t.Fatal("Failed generating RSA key. Key should be private")
  1439  	}
  1440  	if k.Symmetric() {
  1441  		t.Fatal("Failed generating RSA key. Key should be asymmetric")
  1442  	}
  1443  
  1444  	pk, err := k.PublicKey()
  1445  	if err != nil {
  1446  		t.Fatalf("Failed generating RSA corresponding public key [%s]", err)
  1447  	}
  1448  	if pk == nil {
  1449  		t.Fatal("PK must be diffrent from nil")
  1450  	}
  1451  
  1452  	b, err := k.Bytes()
  1453  	if err == nil {
  1454  		t.Fatal("Secret keys cannot be exported. It must fail in this case")
  1455  	}
  1456  	if len(b) != 0 {
  1457  		t.Fatal("Secret keys cannot be exported. It must be nil")
  1458  	}
  1459  
  1460  }
  1461  
  1462  func TestRSAPublicKeyInvalidBytes(t *testing.T) {
  1463  	rsaKey := &rsaPublicKey{nil}
  1464  	b, err := rsaKey.Bytes()
  1465  	if err == nil {
  1466  		t.Fatal("It must fail in this case")
  1467  	}
  1468  	if len(b) != 0 {
  1469  		t.Fatal("It must be nil")
  1470  	}
  1471  }
  1472  
  1473  func TestRSAPrivateKeySKI(t *testing.T) {
  1474  
  1475  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1476  	if err != nil {
  1477  		t.Fatalf("Failed generating RSA key [%s]", err)
  1478  	}
  1479  
  1480  	ski := k.SKI()
  1481  	if len(ski) == 0 {
  1482  		t.Fatal("SKI not valid. Zero length.")
  1483  	}
  1484  }
  1485  
  1486  func TestRSAKeyGenNonEphemeral(t *testing.T) {
  1487  
  1488  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1489  	if err != nil {
  1490  		t.Fatalf("Failed generating RSA key [%s]", err)
  1491  	}
  1492  	if k == nil {
  1493  		t.Fatal("Failed generating RSA key. Key must be different from nil")
  1494  	}
  1495  	if !k.Private() {
  1496  		t.Fatal("Failed generating RSA key. Key should be private")
  1497  	}
  1498  	if k.Symmetric() {
  1499  		t.Fatal("Failed generating RSA key. Key should be asymmetric")
  1500  	}
  1501  }
  1502  
  1503  func TestRSAGetKeyBySKI(t *testing.T) {
  1504  
  1505  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1506  	if err != nil {
  1507  		t.Fatalf("Failed generating RSA key [%s]", err)
  1508  	}
  1509  
  1510  	k2, err := currentBCCSP.GetKey(k.SKI())
  1511  	if err != nil {
  1512  		t.Fatalf("Failed getting RSA key [%s]", err)
  1513  	}
  1514  	if k2 == nil {
  1515  		t.Fatal("Failed getting RSA key. Key must be different from nil")
  1516  	}
  1517  	if !k2.Private() {
  1518  		t.Fatal("Failed getting RSA key. Key should be private")
  1519  	}
  1520  	if k2.Symmetric() {
  1521  		t.Fatal("Failed getting RSA key. Key should be asymmetric")
  1522  	}
  1523  
  1524  	// Check that the SKIs are the same
  1525  	if !bytes.Equal(k.SKI(), k2.SKI()) {
  1526  		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
  1527  	}
  1528  }
  1529  
  1530  func TestRSAPublicKeyFromPrivateKey(t *testing.T) {
  1531  
  1532  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1533  	if err != nil {
  1534  		t.Fatalf("Failed generating RSA key [%s]", err)
  1535  	}
  1536  
  1537  	pk, err := k.PublicKey()
  1538  	if err != nil {
  1539  		t.Fatalf("Failed getting public key from private RSA key [%s]", err)
  1540  	}
  1541  	if pk == nil {
  1542  		t.Fatal("Failed getting public key from private RSA key. Key must be different from nil")
  1543  	}
  1544  	if pk.Private() {
  1545  		t.Fatal("Failed generating RSA key. Key should be public")
  1546  	}
  1547  	if pk.Symmetric() {
  1548  		t.Fatal("Failed generating RSA key. Key should be asymmetric")
  1549  	}
  1550  }
  1551  
  1552  func TestRSAPublicKeyBytes(t *testing.T) {
  1553  
  1554  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1555  	if err != nil {
  1556  		t.Fatalf("Failed generating RSA key [%s]", err)
  1557  	}
  1558  
  1559  	pk, err := k.PublicKey()
  1560  	if err != nil {
  1561  		t.Fatalf("Failed getting public key from private RSA key [%s]", err)
  1562  	}
  1563  
  1564  	raw, err := pk.Bytes()
  1565  	if err != nil {
  1566  		t.Fatalf("Failed marshalling RSA public key [%s]", err)
  1567  	}
  1568  	if len(raw) == 0 {
  1569  		t.Fatal("Failed marshalling RSA public key. Zero length")
  1570  	}
  1571  }
  1572  
  1573  func TestRSAPublicKeySKI(t *testing.T) {
  1574  
  1575  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1576  	if err != nil {
  1577  		t.Fatalf("Failed generating RSA key [%s]", err)
  1578  	}
  1579  
  1580  	pk, err := k.PublicKey()
  1581  	if err != nil {
  1582  		t.Fatalf("Failed getting public key from private RSA key [%s]", err)
  1583  	}
  1584  
  1585  	ski := pk.SKI()
  1586  	if len(ski) == 0 {
  1587  		t.Fatal("SKI not valid. Zero length.")
  1588  	}
  1589  }
  1590  
  1591  func TestRSASign(t *testing.T) {
  1592  
  1593  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1594  	if err != nil {
  1595  		t.Fatalf("Failed generating RSA key [%s]", err)
  1596  	}
  1597  
  1598  	msg := []byte("Hello World")
  1599  
  1600  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1601  	if err != nil {
  1602  		t.Fatalf("Failed computing HASH [%s]", err)
  1603  	}
  1604  
  1605  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1606  	if err != nil {
  1607  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1608  	}
  1609  	if len(signature) == 0 {
  1610  		t.Fatal("Failed generating RSA key. Signature must be different from nil")
  1611  	}
  1612  }
  1613  
  1614  func TestRSAVerify(t *testing.T) {
  1615  
  1616  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1617  	if err != nil {
  1618  		t.Fatalf("Failed generating RSA key [%s]", err)
  1619  	}
  1620  
  1621  	msg := []byte("Hello World")
  1622  
  1623  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1624  	if err != nil {
  1625  		t.Fatalf("Failed computing HASH [%s]", err)
  1626  	}
  1627  
  1628  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1629  	if err != nil {
  1630  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1631  	}
  1632  
  1633  	valid, err := currentBCCSP.Verify(k, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1634  	if err != nil {
  1635  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1636  	}
  1637  	if !valid {
  1638  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1639  	}
  1640  
  1641  	pk, err := k.PublicKey()
  1642  	if err != nil {
  1643  		t.Fatalf("Failed getting corresponding public key [%s]", err)
  1644  	}
  1645  
  1646  	valid, err = currentBCCSP.Verify(pk, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1647  	if err != nil {
  1648  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1649  	}
  1650  	if !valid {
  1651  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1652  	}
  1653  
  1654  	// Store public key
  1655  	err = currentKS.StoreKey(pk)
  1656  	if err != nil {
  1657  		t.Fatalf("Failed storing corresponding public key [%s]", err)
  1658  	}
  1659  
  1660  	pk2, err := currentKS.GetKey(pk.SKI())
  1661  	if err != nil {
  1662  		t.Fatalf("Failed retrieving corresponding public key [%s]", err)
  1663  	}
  1664  
  1665  	valid, err = currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1666  	if err != nil {
  1667  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1668  	}
  1669  	if !valid {
  1670  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1671  	}
  1672  
  1673  }
  1674  
  1675  func TestRSAKeyImportFromRSAPublicKey(t *testing.T) {
  1676  
  1677  	// Generate an RSA key
  1678  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1679  	if err != nil {
  1680  		t.Fatalf("Failed generating RSA key [%s]", err)
  1681  	}
  1682  
  1683  	// Export the public key
  1684  	pk, err := k.PublicKey()
  1685  	if err != nil {
  1686  		t.Fatalf("Failed getting RSA public key [%s]", err)
  1687  	}
  1688  
  1689  	pkRaw, err := pk.Bytes()
  1690  	if err != nil {
  1691  		t.Fatalf("Failed getting RSA raw public key [%s]", err)
  1692  	}
  1693  
  1694  	pub, err := utils.DERToPublicKey(pkRaw)
  1695  	if err != nil {
  1696  		t.Fatalf("Failed converting raw to RSA.PublicKey [%s]", err)
  1697  	}
  1698  
  1699  	// Import the RSA.PublicKey
  1700  	pk2, err := currentBCCSP.KeyImport(pub, &bccsp.RSAGoPublicKeyImportOpts{Temporary: false})
  1701  	if err != nil {
  1702  		t.Fatalf("Failed importing RSA public key [%s]", err)
  1703  	}
  1704  	if pk2 == nil {
  1705  		t.Fatal("Failed importing RSA public key. Return BCCSP key cannot be nil.")
  1706  	}
  1707  
  1708  	// Sign and verify with the imported public key
  1709  	msg := []byte("Hello World")
  1710  
  1711  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1712  	if err != nil {
  1713  		t.Fatalf("Failed computing HASH [%s]", err)
  1714  	}
  1715  
  1716  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1717  	if err != nil {
  1718  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1719  	}
  1720  
  1721  	valid, err := currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1722  	if err != nil {
  1723  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1724  	}
  1725  	if !valid {
  1726  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1727  	}
  1728  }
  1729  
  1730  func TestKeyImportFromX509RSAPublicKey(t *testing.T) {
  1731  
  1732  	// Generate an RSA key
  1733  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1734  	if err != nil {
  1735  		t.Fatalf("Failed generating RSA key [%s]", err)
  1736  	}
  1737  
  1738  	// Generate a self-signed certificate
  1739  	testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
  1740  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
  1741  	extraExtensionData := []byte("extra extension")
  1742  	commonName := "test.example.com"
  1743  	template := x509.Certificate{
  1744  		SerialNumber: big.NewInt(1),
  1745  		Subject: pkix.Name{
  1746  			CommonName:   commonName,
  1747  			Organization: []string{"Σ Acme Co"},
  1748  			Country:      []string{"US"},
  1749  			ExtraNames: []pkix.AttributeTypeAndValue{
  1750  				{
  1751  					Type:  []int{2, 5, 4, 42},
  1752  					Value: "Gopher",
  1753  				},
  1754  				// This should override the Country, above.
  1755  				{
  1756  					Type:  []int{2, 5, 4, 6},
  1757  					Value: "NL",
  1758  				},
  1759  			},
  1760  		},
  1761  		NotBefore: time.Now().Add(-1 * time.Hour),
  1762  		NotAfter:  time.Now().Add(1 * time.Hour),
  1763  
  1764  		SignatureAlgorithm: x509.SHA256WithRSA,
  1765  
  1766  		SubjectKeyId: []byte{1, 2, 3, 4},
  1767  		KeyUsage:     x509.KeyUsageCertSign,
  1768  
  1769  		ExtKeyUsage:        testExtKeyUsage,
  1770  		UnknownExtKeyUsage: testUnknownExtKeyUsage,
  1771  
  1772  		BasicConstraintsValid: true,
  1773  		IsCA: true,
  1774  
  1775  		OCSPServer:            []string{"http://ocurrentBCCSP.example.com"},
  1776  		IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
  1777  
  1778  		DNSNames:       []string{"test.example.com"},
  1779  		EmailAddresses: []string{"gopher@golang.org"},
  1780  		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  1781  
  1782  		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
  1783  		PermittedDNSDomains: []string{".example.com", "example.com"},
  1784  
  1785  		CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
  1786  
  1787  		ExtraExtensions: []pkix.Extension{
  1788  			{
  1789  				Id:    []int{1, 2, 3, 4},
  1790  				Value: extraExtensionData,
  1791  			},
  1792  		},
  1793  	}
  1794  
  1795  	cryptoSigner := &signer.CryptoSigner{}
  1796  	err = cryptoSigner.Init(currentBCCSP, k)
  1797  	if err != nil {
  1798  		t.Fatalf("Failed initializing CyrptoSigner [%s]", err)
  1799  	}
  1800  
  1801  	// Export the public key
  1802  	pk, err := k.PublicKey()
  1803  	if err != nil {
  1804  		t.Fatalf("Failed getting RSA public key [%s]", err)
  1805  	}
  1806  
  1807  	pkRaw, err := pk.Bytes()
  1808  	if err != nil {
  1809  		t.Fatalf("Failed getting RSA raw public key [%s]", err)
  1810  	}
  1811  
  1812  	pub, err := utils.DERToPublicKey(pkRaw)
  1813  	if err != nil {
  1814  		t.Fatalf("Failed converting raw to RSA.PublicKey [%s]", err)
  1815  	}
  1816  
  1817  	certRaw, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, cryptoSigner)
  1818  	if err != nil {
  1819  		t.Fatalf("Failed generating self-signed certificate [%s]", err)
  1820  	}
  1821  
  1822  	cert, err := utils.DERToX509Certificate(certRaw)
  1823  	if err != nil {
  1824  		t.Fatalf("Failed generating X509 certificate object from raw [%s]", err)
  1825  	}
  1826  
  1827  	// Import the certificate's public key
  1828  	pk2, err := currentBCCSP.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: false})
  1829  
  1830  	if err != nil {
  1831  		t.Fatalf("Failed importing RSA public key [%s]", err)
  1832  	}
  1833  	if pk2 == nil {
  1834  		t.Fatal("Failed importing RSA public key. Return BCCSP key cannot be nil.")
  1835  	}
  1836  
  1837  	// Sign and verify with the imported public key
  1838  	msg := []byte("Hello World")
  1839  
  1840  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1841  	if err != nil {
  1842  		t.Fatalf("Failed computing HASH [%s]", err)
  1843  	}
  1844  
  1845  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1846  	if err != nil {
  1847  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1848  	}
  1849  
  1850  	valid, err := currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1851  	if err != nil {
  1852  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1853  	}
  1854  	if !valid {
  1855  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1856  	}
  1857  }
  1858  
  1859  func TestGetHashAndHashCompatibility(t *testing.T) {
  1860  
  1861  	msg1 := []byte("abcd")
  1862  	msg2 := []byte("efgh")
  1863  	msg := []byte("abcdefgh")
  1864  
  1865  	digest1, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1866  	if err != nil {
  1867  		t.Fatalf("Failed computing HASH [%s]", err)
  1868  	}
  1869  
  1870  	digest2, err := currentBCCSP.Hash(msg, nil)
  1871  	if err != nil {
  1872  		t.Fatalf("Failed computing HASH [%s]", err)
  1873  	}
  1874  
  1875  	if !bytes.Equal(digest1, digest2) {
  1876  		t.Fatalf("Different hash computed. [%x][%x]", digest1, digest2)
  1877  	}
  1878  
  1879  	h, err := currentBCCSP.GetHash(nil)
  1880  	if err != nil {
  1881  		t.Fatalf("Failed getting hash.Hash instance [%s]", err)
  1882  	}
  1883  	h.Write(msg1)
  1884  	h.Write(msg2)
  1885  	digest3 := h.Sum(nil)
  1886  
  1887  	h2, err := currentBCCSP.GetHash(&bccsp.SHAOpts{})
  1888  	if err != nil {
  1889  		t.Fatalf("Failed getting SHA hash.Hash instance [%s]", err)
  1890  	}
  1891  	h2.Write(msg1)
  1892  	h2.Write(msg2)
  1893  	digest4 := h2.Sum(nil)
  1894  
  1895  	if !bytes.Equal(digest3, digest4) {
  1896  		t.Fatalf("Different hash computed. [%x][%x]", digest3, digest4)
  1897  	}
  1898  
  1899  	if !bytes.Equal(digest1, digest3) {
  1900  		t.Fatalf("Different hash computed. [%x][%x]", digest1, digest3)
  1901  	}
  1902  }
  1903  
  1904  func getCryptoHashIndex(t *testing.T) crypto.Hash {
  1905  	switch currentTestConfig.hashFamily {
  1906  	case "SHA2":
  1907  		switch currentTestConfig.securityLevel {
  1908  		case 256:
  1909  			return crypto.SHA256
  1910  		case 384:
  1911  			return crypto.SHA384
  1912  		default:
  1913  			t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1914  		}
  1915  	case "SHA3":
  1916  		switch currentTestConfig.securityLevel {
  1917  		case 256:
  1918  			return crypto.SHA3_256
  1919  		case 384:
  1920  			return crypto.SHA3_384
  1921  		default:
  1922  			t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1923  		}
  1924  	default:
  1925  		t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
  1926  	}
  1927  
  1928  	return crypto.SHA3_256
  1929  }
  1930  
  1931  var enablePKCS11tests = false
  1932  
  1933  func findPKCS11Lib() (lib, pin, label string) {
  1934  	//FIXME: Till we workout the configuration piece, look for the libraries in the familiar places
  1935  	lib = os.Getenv("PKCS11_LIB")
  1936  	if lib == "" {
  1937  		pin = "98765432"
  1938  		label = "ForFabric"
  1939  		possibilities := []string{
  1940  			"/usr/lib/softhsm/libsofthsm2.so",                            //Debian
  1941  			"/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so",           //Ubuntu
  1942  			"/usr/lib/s390x-linux-gnu/softhsm/libsofthsm2.so",            //Ubuntu
  1943  			"/usr/lib/powerpc64le-linux-gnu/softhsm/libsofthsm2.so",      //Power
  1944  			"/usr/local/Cellar/softhsm/2.1.0/lib/softhsm/libsofthsm2.so", //MacOS
  1945  		}
  1946  		for _, path := range possibilities {
  1947  			if _, err := os.Stat(path); !os.IsNotExist(err) {
  1948  				lib = path
  1949  				enablePKCS11tests = true
  1950  				break
  1951  			}
  1952  		}
  1953  		if lib == "" {
  1954  			enablePKCS11tests = false
  1955  		}
  1956  	} else {
  1957  		enablePKCS11tests = true
  1958  		pin = os.Getenv("PKCS11_PIN")
  1959  		label = os.Getenv("PKCS11_LABEL")
  1960  	}
  1961  	return lib, pin, label
  1962  }