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