github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/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  	_, 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  	var R *big.Int
  1117  	for {
  1118  		R, S, err = ecdsa.Sign(rand.Reader, k.(*ecdsaPrivateKey).privKey, digest)
  1119  		if err != nil {
  1120  			t.Fatalf("Failed generating signature [%s]", err)
  1121  		}
  1122  
  1123  		if S.Cmp(curveHalfOrders[k.(*ecdsaPrivateKey).privKey.Curve]) > 0 {
  1124  			break
  1125  		}
  1126  	}
  1127  
  1128  	sig, err := marshalECDSASignature(R, S)
  1129  	if err != nil {
  1130  		t.Fatalf("Failing unmarshalling signature [%s]", err)
  1131  	}
  1132  
  1133  	valid, err = currentBCCSP.Verify(k, sig, digest, nil)
  1134  	if err == nil {
  1135  		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
  1136  	}
  1137  	if valid {
  1138  		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
  1139  	}
  1140  }
  1141  
  1142  func TestAESKeyGen(t *testing.T) {
  1143  
  1144  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1145  	if err != nil {
  1146  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1147  	}
  1148  	if k == nil {
  1149  		t.Fatal("Failed generating AES_256 key. Key must be different from nil")
  1150  	}
  1151  	if !k.Private() {
  1152  		t.Fatal("Failed generating AES_256 key. Key should be private")
  1153  	}
  1154  	if !k.Symmetric() {
  1155  		t.Fatal("Failed generating AES_256 key. Key should be symmetric")
  1156  	}
  1157  
  1158  	pk, err := k.PublicKey()
  1159  	if err == nil {
  1160  		t.Fatal("Error should be different from nil in this case")
  1161  	}
  1162  	if pk != nil {
  1163  		t.Fatal("Return value should be equal to nil in this case")
  1164  	}
  1165  }
  1166  
  1167  func TestAESEncrypt(t *testing.T) {
  1168  
  1169  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1170  	if err != nil {
  1171  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1172  	}
  1173  
  1174  	ct, err := currentBCCSP.Encrypt(k, []byte("Hello World"), &bccsp.AESCBCPKCS7ModeOpts{})
  1175  	if err != nil {
  1176  		t.Fatalf("Failed encrypting [%s]", err)
  1177  	}
  1178  	if len(ct) == 0 {
  1179  		t.Fatal("Failed encrypting. Nil ciphertext")
  1180  	}
  1181  }
  1182  
  1183  func TestAESDecrypt(t *testing.T) {
  1184  
  1185  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1186  	if err != nil {
  1187  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1188  	}
  1189  
  1190  	msg := []byte("Hello World")
  1191  
  1192  	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1193  	if err != nil {
  1194  		t.Fatalf("Failed encrypting [%s]", err)
  1195  	}
  1196  
  1197  	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1198  	if err != nil {
  1199  		t.Fatalf("Failed decrypting [%s]", err)
  1200  	}
  1201  	if len(ct) == 0 {
  1202  		t.Fatal("Failed decrypting. Nil plaintext")
  1203  	}
  1204  
  1205  	if !bytes.Equal(msg, pt) {
  1206  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1207  	}
  1208  }
  1209  
  1210  func TestHMACTruncated256KeyDerivOverAES256Key(t *testing.T) {
  1211  
  1212  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1213  	if err != nil {
  1214  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1215  	}
  1216  
  1217  	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACTruncated256AESDeriveKeyOpts{Temporary: false, Arg: []byte{1}})
  1218  	if err != nil {
  1219  		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
  1220  	}
  1221  	if k == nil {
  1222  		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
  1223  	}
  1224  	if !hmcaedKey.Private() {
  1225  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
  1226  	}
  1227  	if !hmcaedKey.Symmetric() {
  1228  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
  1229  	}
  1230  	raw, err := hmcaedKey.Bytes()
  1231  	if err == nil {
  1232  		t.Fatal("Failed marshalling to bytes. Operation must be forbidden")
  1233  	}
  1234  	if len(raw) != 0 {
  1235  		t.Fatal("Failed marshalling to bytes. Operation must return 0 bytes")
  1236  	}
  1237  
  1238  	msg := []byte("Hello World")
  1239  
  1240  	ct, err := currentBCCSP.Encrypt(hmcaedKey, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1241  	if err != nil {
  1242  		t.Fatalf("Failed encrypting [%s]", err)
  1243  	}
  1244  
  1245  	pt, err := currentBCCSP.Decrypt(hmcaedKey, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1246  	if err != nil {
  1247  		t.Fatalf("Failed decrypting [%s]", err)
  1248  	}
  1249  	if len(ct) == 0 {
  1250  		t.Fatal("Failed decrypting. Nil plaintext")
  1251  	}
  1252  
  1253  	if !bytes.Equal(msg, pt) {
  1254  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1255  	}
  1256  
  1257  }
  1258  
  1259  func TestHMACKeyDerivOverAES256Key(t *testing.T) {
  1260  
  1261  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1262  	if err != nil {
  1263  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1264  	}
  1265  
  1266  	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Temporary: false, Arg: []byte{1}})
  1267  
  1268  	if err != nil {
  1269  		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
  1270  	}
  1271  	if k == nil {
  1272  		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
  1273  	}
  1274  	if !hmcaedKey.Private() {
  1275  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
  1276  	}
  1277  	if !hmcaedKey.Symmetric() {
  1278  		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
  1279  	}
  1280  	raw, err := hmcaedKey.Bytes()
  1281  	if err != nil {
  1282  		t.Fatalf("Failed marshalling to bytes [%s]", err)
  1283  	}
  1284  	if len(raw) == 0 {
  1285  		t.Fatal("Failed marshalling to bytes. 0 bytes")
  1286  	}
  1287  }
  1288  
  1289  func TestAES256KeyImport(t *testing.T) {
  1290  
  1291  	raw, err := GetRandomBytes(32)
  1292  	if err != nil {
  1293  		t.Fatalf("Failed generating AES key [%s]", err)
  1294  	}
  1295  
  1296  	k, err := currentBCCSP.KeyImport(raw, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1297  	if err != nil {
  1298  		t.Fatalf("Failed importing AES_256 key [%s]", err)
  1299  	}
  1300  	if k == nil {
  1301  		t.Fatal("Failed importing AES_256 key. Imported Key must be different from nil")
  1302  	}
  1303  	if !k.Private() {
  1304  		t.Fatal("Failed HMACing AES_256 key. Imported Key should be private")
  1305  	}
  1306  	if !k.Symmetric() {
  1307  		t.Fatal("Failed HMACing AES_256 key. Imported Key should be asymmetric")
  1308  	}
  1309  	raw, err = k.Bytes()
  1310  	if err == nil {
  1311  		t.Fatal("Failed marshalling to bytes. Marshalling must fail.")
  1312  	}
  1313  	if len(raw) != 0 {
  1314  		t.Fatal("Failed marshalling to bytes. Output should be 0 bytes")
  1315  	}
  1316  
  1317  	msg := []byte("Hello World")
  1318  
  1319  	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
  1320  	if err != nil {
  1321  		t.Fatalf("Failed encrypting [%s]", err)
  1322  	}
  1323  
  1324  	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
  1325  	if err != nil {
  1326  		t.Fatalf("Failed decrypting [%s]", err)
  1327  	}
  1328  	if len(ct) == 0 {
  1329  		t.Fatal("Failed decrypting. Nil plaintext")
  1330  	}
  1331  
  1332  	if !bytes.Equal(msg, pt) {
  1333  		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
  1334  	}
  1335  }
  1336  
  1337  func TestAES256KeyImportBadPaths(t *testing.T) {
  1338  
  1339  	_, err := currentBCCSP.KeyImport(nil, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1340  	if err == nil {
  1341  		t.Fatal("Failed importing key. Must fail on importing nil key")
  1342  	}
  1343  
  1344  	_, err = currentBCCSP.KeyImport([]byte{1}, &bccsp.AES256ImportKeyOpts{Temporary: false})
  1345  	if err == nil {
  1346  		t.Fatal("Failed importing key. Must fail on importing a key with an invalid length")
  1347  	}
  1348  }
  1349  
  1350  func TestAES256KeyGenSKI(t *testing.T) {
  1351  
  1352  	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
  1353  	if err != nil {
  1354  		t.Fatalf("Failed generating AES_256 key [%s]", err)
  1355  	}
  1356  
  1357  	k2, err := currentBCCSP.GetKey(k.SKI())
  1358  	if err != nil {
  1359  		t.Fatalf("Failed getting AES_256 key [%s]", err)
  1360  	}
  1361  	if k2 == nil {
  1362  		t.Fatal("Failed getting AES_256 key. Key must be different from nil")
  1363  	}
  1364  	if !k2.Private() {
  1365  		t.Fatal("Failed getting AES_256 key. Key should be private")
  1366  	}
  1367  	if !k2.Symmetric() {
  1368  		t.Fatal("Failed getting AES_256 key. Key should be symmetric")
  1369  	}
  1370  
  1371  	// Check that the SKIs are the same
  1372  	if !bytes.Equal(k.SKI(), k2.SKI()) {
  1373  		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
  1374  	}
  1375  
  1376  }
  1377  
  1378  func TestSHA(t *testing.T) {
  1379  
  1380  	for i := 0; i < 100; i++ {
  1381  		b, err := GetRandomBytes(i)
  1382  		if err != nil {
  1383  			t.Fatalf("Failed getting random bytes [%s]", err)
  1384  		}
  1385  
  1386  		h1, err := currentBCCSP.Hash(b, &bccsp.SHAOpts{})
  1387  		if err != nil {
  1388  			t.Fatalf("Failed computing SHA [%s]", err)
  1389  		}
  1390  
  1391  		var h hash.Hash
  1392  		switch currentTestConfig.hashFamily {
  1393  		case "SHA2":
  1394  			switch currentTestConfig.securityLevel {
  1395  			case 256:
  1396  				h = sha256.New()
  1397  			case 384:
  1398  				h = sha512.New384()
  1399  			default:
  1400  				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1401  			}
  1402  		case "SHA3":
  1403  			switch currentTestConfig.securityLevel {
  1404  			case 256:
  1405  				h = sha3.New256()
  1406  			case 384:
  1407  				h = sha3.New384()
  1408  			default:
  1409  				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1410  			}
  1411  		default:
  1412  			t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
  1413  		}
  1414  
  1415  		h.Write(b)
  1416  		h2 := h.Sum(nil)
  1417  		if !bytes.Equal(h1, h2) {
  1418  			t.Fatalf("Discrempancy found in HASH result [%x], [%x]!=[%x]", b, h1, h2)
  1419  		}
  1420  	}
  1421  }
  1422  
  1423  func TestRSAKeyGenEphemeral(t *testing.T) {
  1424  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: true})
  1425  	if err != nil {
  1426  		t.Fatalf("Failed generating RSA key [%s]", err)
  1427  	}
  1428  	if k == nil {
  1429  		t.Fatal("Failed generating RSA key. Key must be different from nil")
  1430  	}
  1431  	if !k.Private() {
  1432  		t.Fatal("Failed generating RSA key. Key should be private")
  1433  	}
  1434  	if k.Symmetric() {
  1435  		t.Fatal("Failed generating RSA key. Key should be asymmetric")
  1436  	}
  1437  
  1438  	pk, err := k.PublicKey()
  1439  	if err != nil {
  1440  		t.Fatalf("Failed generating RSA corresponding public key [%s]", err)
  1441  	}
  1442  	if pk == nil {
  1443  		t.Fatal("PK must be diffrent from nil")
  1444  	}
  1445  
  1446  	b, err := k.Bytes()
  1447  	if err == nil {
  1448  		t.Fatal("Secret keys cannot be exported. It must fail in this case")
  1449  	}
  1450  	if len(b) != 0 {
  1451  		t.Fatal("Secret keys cannot be exported. It must be nil")
  1452  	}
  1453  
  1454  }
  1455  
  1456  func TestRSAPublicKeyInvalidBytes(t *testing.T) {
  1457  	rsaKey := &rsaPublicKey{nil}
  1458  	b, err := rsaKey.Bytes()
  1459  	if err == nil {
  1460  		t.Fatal("It must fail in this case")
  1461  	}
  1462  	if len(b) != 0 {
  1463  		t.Fatal("It must be nil")
  1464  	}
  1465  }
  1466  
  1467  func TestRSAPrivateKeySKI(t *testing.T) {
  1468  
  1469  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1470  	if err != nil {
  1471  		t.Fatalf("Failed generating RSA key [%s]", err)
  1472  	}
  1473  
  1474  	ski := k.SKI()
  1475  	if len(ski) == 0 {
  1476  		t.Fatal("SKI not valid. Zero length.")
  1477  	}
  1478  }
  1479  
  1480  func TestRSAKeyGenNonEphemeral(t *testing.T) {
  1481  
  1482  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1483  	if err != nil {
  1484  		t.Fatalf("Failed generating RSA key [%s]", err)
  1485  	}
  1486  	if k == nil {
  1487  		t.Fatal("Failed generating RSA key. Key must be different from nil")
  1488  	}
  1489  	if !k.Private() {
  1490  		t.Fatal("Failed generating RSA key. Key should be private")
  1491  	}
  1492  	if k.Symmetric() {
  1493  		t.Fatal("Failed generating RSA key. Key should be asymmetric")
  1494  	}
  1495  }
  1496  
  1497  func TestRSAGetKeyBySKI(t *testing.T) {
  1498  
  1499  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1500  	if err != nil {
  1501  		t.Fatalf("Failed generating RSA key [%s]", err)
  1502  	}
  1503  
  1504  	k2, err := currentBCCSP.GetKey(k.SKI())
  1505  	if err != nil {
  1506  		t.Fatalf("Failed getting RSA key [%s]", err)
  1507  	}
  1508  	if k2 == nil {
  1509  		t.Fatal("Failed getting RSA key. Key must be different from nil")
  1510  	}
  1511  	if !k2.Private() {
  1512  		t.Fatal("Failed getting RSA key. Key should be private")
  1513  	}
  1514  	if k2.Symmetric() {
  1515  		t.Fatal("Failed getting RSA key. Key should be asymmetric")
  1516  	}
  1517  
  1518  	// Check that the SKIs are the same
  1519  	if !bytes.Equal(k.SKI(), k2.SKI()) {
  1520  		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
  1521  	}
  1522  }
  1523  
  1524  func TestRSAPublicKeyFromPrivateKey(t *testing.T) {
  1525  
  1526  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1527  	if err != nil {
  1528  		t.Fatalf("Failed generating RSA key [%s]", err)
  1529  	}
  1530  
  1531  	pk, err := k.PublicKey()
  1532  	if err != nil {
  1533  		t.Fatalf("Failed getting public key from private RSA key [%s]", err)
  1534  	}
  1535  	if pk == nil {
  1536  		t.Fatal("Failed getting public key from private RSA key. Key must be different from nil")
  1537  	}
  1538  	if pk.Private() {
  1539  		t.Fatal("Failed generating RSA key. Key should be public")
  1540  	}
  1541  	if pk.Symmetric() {
  1542  		t.Fatal("Failed generating RSA key. Key should be asymmetric")
  1543  	}
  1544  }
  1545  
  1546  func TestRSAPublicKeyBytes(t *testing.T) {
  1547  
  1548  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1549  	if err != nil {
  1550  		t.Fatalf("Failed generating RSA key [%s]", err)
  1551  	}
  1552  
  1553  	pk, err := k.PublicKey()
  1554  	if err != nil {
  1555  		t.Fatalf("Failed getting public key from private RSA key [%s]", err)
  1556  	}
  1557  
  1558  	raw, err := pk.Bytes()
  1559  	if err != nil {
  1560  		t.Fatalf("Failed marshalling RSA public key [%s]", err)
  1561  	}
  1562  	if len(raw) == 0 {
  1563  		t.Fatal("Failed marshalling RSA public key. Zero length")
  1564  	}
  1565  }
  1566  
  1567  func TestRSAPublicKeySKI(t *testing.T) {
  1568  
  1569  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1570  	if err != nil {
  1571  		t.Fatalf("Failed generating RSA key [%s]", err)
  1572  	}
  1573  
  1574  	pk, err := k.PublicKey()
  1575  	if err != nil {
  1576  		t.Fatalf("Failed getting public key from private RSA key [%s]", err)
  1577  	}
  1578  
  1579  	ski := pk.SKI()
  1580  	if len(ski) == 0 {
  1581  		t.Fatal("SKI not valid. Zero length.")
  1582  	}
  1583  }
  1584  
  1585  func TestRSASign(t *testing.T) {
  1586  
  1587  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1588  	if err != nil {
  1589  		t.Fatalf("Failed generating RSA key [%s]", err)
  1590  	}
  1591  
  1592  	msg := []byte("Hello World")
  1593  
  1594  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1595  	if err != nil {
  1596  		t.Fatalf("Failed computing HASH [%s]", err)
  1597  	}
  1598  
  1599  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1600  	if err != nil {
  1601  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1602  	}
  1603  	if len(signature) == 0 {
  1604  		t.Fatal("Failed generating RSA key. Signature must be different from nil")
  1605  	}
  1606  }
  1607  
  1608  func TestRSAVerify(t *testing.T) {
  1609  
  1610  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1611  	if err != nil {
  1612  		t.Fatalf("Failed generating RSA key [%s]", err)
  1613  	}
  1614  
  1615  	msg := []byte("Hello World")
  1616  
  1617  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1618  	if err != nil {
  1619  		t.Fatalf("Failed computing HASH [%s]", err)
  1620  	}
  1621  
  1622  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1623  	if err != nil {
  1624  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1625  	}
  1626  
  1627  	valid, err := currentBCCSP.Verify(k, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1628  	if err != nil {
  1629  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1630  	}
  1631  	if !valid {
  1632  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1633  	}
  1634  
  1635  	pk, err := k.PublicKey()
  1636  	if err != nil {
  1637  		t.Fatalf("Failed getting corresponding public key [%s]", err)
  1638  	}
  1639  
  1640  	valid, err = currentBCCSP.Verify(pk, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1641  	if err != nil {
  1642  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1643  	}
  1644  	if !valid {
  1645  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1646  	}
  1647  
  1648  	// Store public key
  1649  	err = currentKS.StoreKey(pk)
  1650  	if err != nil {
  1651  		t.Fatalf("Failed storing corresponding public key [%s]", err)
  1652  	}
  1653  
  1654  	pk2, err := currentKS.GetKey(pk.SKI())
  1655  	if err != nil {
  1656  		t.Fatalf("Failed retrieving corresponding public key [%s]", err)
  1657  	}
  1658  
  1659  	valid, err = currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1660  	if err != nil {
  1661  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1662  	}
  1663  	if !valid {
  1664  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1665  	}
  1666  
  1667  }
  1668  
  1669  func TestRSAKeyImportFromRSAPublicKey(t *testing.T) {
  1670  
  1671  	// Generate an RSA key
  1672  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1673  	if err != nil {
  1674  		t.Fatalf("Failed generating RSA key [%s]", err)
  1675  	}
  1676  
  1677  	// Export the public key
  1678  	pk, err := k.PublicKey()
  1679  	if err != nil {
  1680  		t.Fatalf("Failed getting RSA public key [%s]", err)
  1681  	}
  1682  
  1683  	pkRaw, err := pk.Bytes()
  1684  	if err != nil {
  1685  		t.Fatalf("Failed getting RSA raw public key [%s]", err)
  1686  	}
  1687  
  1688  	pub, err := utils.DERToPublicKey(pkRaw)
  1689  	if err != nil {
  1690  		t.Fatalf("Failed converting raw to RSA.PublicKey [%s]", err)
  1691  	}
  1692  
  1693  	// Import the RSA.PublicKey
  1694  	pk2, err := currentBCCSP.KeyImport(pub, &bccsp.RSAGoPublicKeyImportOpts{Temporary: false})
  1695  	if err != nil {
  1696  		t.Fatalf("Failed importing RSA public key [%s]", err)
  1697  	}
  1698  	if pk2 == nil {
  1699  		t.Fatal("Failed importing RSA public key. Return BCCSP key cannot be nil.")
  1700  	}
  1701  
  1702  	// Sign and verify with the imported public key
  1703  	msg := []byte("Hello World")
  1704  
  1705  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1706  	if err != nil {
  1707  		t.Fatalf("Failed computing HASH [%s]", err)
  1708  	}
  1709  
  1710  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1711  	if err != nil {
  1712  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1713  	}
  1714  
  1715  	valid, err := currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1716  	if err != nil {
  1717  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1718  	}
  1719  	if !valid {
  1720  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1721  	}
  1722  }
  1723  
  1724  func TestKeyImportFromX509RSAPublicKey(t *testing.T) {
  1725  
  1726  	// Generate an RSA key
  1727  	k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false})
  1728  	if err != nil {
  1729  		t.Fatalf("Failed generating RSA key [%s]", err)
  1730  	}
  1731  
  1732  	// Generate a self-signed certificate
  1733  	testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
  1734  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
  1735  	extraExtensionData := []byte("extra extension")
  1736  	commonName := "test.example.com"
  1737  	template := x509.Certificate{
  1738  		SerialNumber: big.NewInt(1),
  1739  		Subject: pkix.Name{
  1740  			CommonName:   commonName,
  1741  			Organization: []string{"Σ Acme Co"},
  1742  			Country:      []string{"US"},
  1743  			ExtraNames: []pkix.AttributeTypeAndValue{
  1744  				{
  1745  					Type:  []int{2, 5, 4, 42},
  1746  					Value: "Gopher",
  1747  				},
  1748  				// This should override the Country, above.
  1749  				{
  1750  					Type:  []int{2, 5, 4, 6},
  1751  					Value: "NL",
  1752  				},
  1753  			},
  1754  		},
  1755  		NotBefore: time.Now().Add(-1 * time.Hour),
  1756  		NotAfter:  time.Now().Add(1 * time.Hour),
  1757  
  1758  		SignatureAlgorithm: x509.SHA256WithRSA,
  1759  
  1760  		SubjectKeyId: []byte{1, 2, 3, 4},
  1761  		KeyUsage:     x509.KeyUsageCertSign,
  1762  
  1763  		ExtKeyUsage:        testExtKeyUsage,
  1764  		UnknownExtKeyUsage: testUnknownExtKeyUsage,
  1765  
  1766  		BasicConstraintsValid: true,
  1767  		IsCA: true,
  1768  
  1769  		OCSPServer:            []string{"http://ocurrentBCCSP.example.com"},
  1770  		IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
  1771  
  1772  		DNSNames:       []string{"test.example.com"},
  1773  		EmailAddresses: []string{"gopher@golang.org"},
  1774  		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  1775  
  1776  		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
  1777  		PermittedDNSDomains: []string{".example.com", "example.com"},
  1778  
  1779  		CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
  1780  
  1781  		ExtraExtensions: []pkix.Extension{
  1782  			{
  1783  				Id:    []int{1, 2, 3, 4},
  1784  				Value: extraExtensionData,
  1785  			},
  1786  		},
  1787  	}
  1788  
  1789  	cryptoSigner := &signer.CryptoSigner{}
  1790  	err = cryptoSigner.Init(currentBCCSP, k)
  1791  	if err != nil {
  1792  		t.Fatalf("Failed initializing CyrptoSigner [%s]", err)
  1793  	}
  1794  
  1795  	// Export the public key
  1796  	pk, err := k.PublicKey()
  1797  	if err != nil {
  1798  		t.Fatalf("Failed getting RSA public key [%s]", err)
  1799  	}
  1800  
  1801  	pkRaw, err := pk.Bytes()
  1802  	if err != nil {
  1803  		t.Fatalf("Failed getting RSA raw public key [%s]", err)
  1804  	}
  1805  
  1806  	pub, err := utils.DERToPublicKey(pkRaw)
  1807  	if err != nil {
  1808  		t.Fatalf("Failed converting raw to RSA.PublicKey [%s]", err)
  1809  	}
  1810  
  1811  	certRaw, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, cryptoSigner)
  1812  	if err != nil {
  1813  		t.Fatalf("Failed generating self-signed certificate [%s]", err)
  1814  	}
  1815  
  1816  	cert, err := utils.DERToX509Certificate(certRaw)
  1817  	if err != nil {
  1818  		t.Fatalf("Failed generating X509 certificate object from raw [%s]", err)
  1819  	}
  1820  
  1821  	// Import the certificate's public key
  1822  	pk2, err := currentBCCSP.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: false})
  1823  
  1824  	if err != nil {
  1825  		t.Fatalf("Failed importing RSA public key [%s]", err)
  1826  	}
  1827  	if pk2 == nil {
  1828  		t.Fatal("Failed importing RSA public key. Return BCCSP key cannot be nil.")
  1829  	}
  1830  
  1831  	// Sign and verify with the imported public key
  1832  	msg := []byte("Hello World")
  1833  
  1834  	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1835  	if err != nil {
  1836  		t.Fatalf("Failed computing HASH [%s]", err)
  1837  	}
  1838  
  1839  	signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1840  	if err != nil {
  1841  		t.Fatalf("Failed generating RSA signature [%s]", err)
  1842  	}
  1843  
  1844  	valid, err := currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)})
  1845  	if err != nil {
  1846  		t.Fatalf("Failed verifying RSA signature [%s]", err)
  1847  	}
  1848  	if !valid {
  1849  		t.Fatal("Failed verifying RSA signature. Signature not valid.")
  1850  	}
  1851  }
  1852  
  1853  func TestGetHashAndHashCompatibility(t *testing.T) {
  1854  
  1855  	msg1 := []byte("abcd")
  1856  	msg2 := []byte("efgh")
  1857  	msg := []byte("abcdefgh")
  1858  
  1859  	digest1, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
  1860  	if err != nil {
  1861  		t.Fatalf("Failed computing HASH [%s]", err)
  1862  	}
  1863  
  1864  	digest2, err := currentBCCSP.Hash(msg, nil)
  1865  	if err != nil {
  1866  		t.Fatalf("Failed computing HASH [%s]", err)
  1867  	}
  1868  
  1869  	if !bytes.Equal(digest1, digest2) {
  1870  		t.Fatalf("Different hash computed. [%x][%x]", digest1, digest2)
  1871  	}
  1872  
  1873  	h, err := currentBCCSP.GetHash(nil)
  1874  	if err != nil {
  1875  		t.Fatalf("Failed getting hash.Hash instance [%s]", err)
  1876  	}
  1877  	h.Write(msg1)
  1878  	h.Write(msg2)
  1879  	digest3 := h.Sum(nil)
  1880  
  1881  	h2, err := currentBCCSP.GetHash(&bccsp.SHAOpts{})
  1882  	if err != nil {
  1883  		t.Fatalf("Failed getting SHA hash.Hash instance [%s]", err)
  1884  	}
  1885  	h2.Write(msg1)
  1886  	h2.Write(msg2)
  1887  	digest4 := h2.Sum(nil)
  1888  
  1889  	if !bytes.Equal(digest3, digest4) {
  1890  		t.Fatalf("Different hash computed. [%x][%x]", digest3, digest4)
  1891  	}
  1892  
  1893  	if !bytes.Equal(digest1, digest3) {
  1894  		t.Fatalf("Different hash computed. [%x][%x]", digest1, digest3)
  1895  	}
  1896  }
  1897  
  1898  func getCryptoHashIndex(t *testing.T) crypto.Hash {
  1899  	switch currentTestConfig.hashFamily {
  1900  	case "SHA2":
  1901  		switch currentTestConfig.securityLevel {
  1902  		case 256:
  1903  			return crypto.SHA256
  1904  		case 384:
  1905  			return crypto.SHA384
  1906  		default:
  1907  			t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1908  		}
  1909  	case "SHA3":
  1910  		switch currentTestConfig.securityLevel {
  1911  		case 256:
  1912  			return crypto.SHA3_256
  1913  		case 384:
  1914  			return crypto.SHA3_384
  1915  		default:
  1916  			t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
  1917  		}
  1918  	default:
  1919  		t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
  1920  	}
  1921  
  1922  	return crypto.SHA3_256
  1923  }