github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/bccsp/pkcs11/impl_test.go (about)

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