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