github.com/lzy4123/fabric@v2.1.1+incompatible/bccsp/pkcs11/pkcs11_test.go (about)

     1  // +build pkcs11
     2  
     3  /*
     4  Copyright IBM Corp. All Rights Reserved.
     5  
     6  SPDX-License-Identifier: Apache-2.0
     7  */
     8  package pkcs11
     9  
    10  import (
    11  	"crypto/ecdsa"
    12  	"crypto/elliptic"
    13  	"encoding/asn1"
    14  	"testing"
    15  
    16  	"github.com/hyperledger/fabric/bccsp"
    17  	"github.com/miekg/pkcs11"
    18  	"github.com/stretchr/testify/assert"
    19  )
    20  
    21  func TestKeyGenFailures(t *testing.T) {
    22  	if testing.Short() {
    23  		t.Skip("Skipping TestKeyGenFailures")
    24  	}
    25  	var testOpts bccsp.KeyGenOpts
    26  	ki := currentBCCSP
    27  	_, err := ki.KeyGen(testOpts)
    28  	assert.Error(t, err)
    29  	assert.Contains(t, err.Error(), "Invalid Opts parameter. It must not be nil")
    30  }
    31  
    32  func TestLoadLib(t *testing.T) {
    33  	if testing.Short() {
    34  		t.Skip("Skipping TestLoadLib")
    35  	}
    36  	// Setup PKCS11 library and provide initial set of values
    37  	lib, pin, label := FindPKCS11Lib()
    38  
    39  	// Test for no specified PKCS11 library
    40  	_, _, _, err := loadLib("", pin, label)
    41  	assert.Error(t, err)
    42  	assert.Contains(t, err.Error(), "No PKCS11 library default")
    43  
    44  	// Test for invalid PKCS11 library
    45  	_, _, _, err = loadLib("badLib", pin, label)
    46  	assert.Error(t, err)
    47  	assert.Contains(t, err.Error(), "Instantiate failed")
    48  
    49  	// Test for invalid label
    50  	_, _, _, err = loadLib(lib, pin, "badLabel")
    51  	assert.Error(t, err)
    52  	assert.Contains(t, err.Error(), "Could not find token with label")
    53  
    54  	// Test for no pin
    55  	_, _, _, err = loadLib(lib, "", label)
    56  	assert.Error(t, err)
    57  	assert.Contains(t, err.Error(), "No PIN set")
    58  }
    59  
    60  func TestNamedCurveFromOID(t *testing.T) {
    61  	if testing.Short() {
    62  		t.Skip("Skipping TestNamedCurveFromOID")
    63  	}
    64  	// Test for valid P224 elliptic curve
    65  	namedCurve := namedCurveFromOID(oidNamedCurveP224)
    66  	assert.Equal(t, elliptic.P224(), namedCurve, "Did not receive expected named curve for oidNamedCurveP224")
    67  
    68  	// Test for valid P256 elliptic curve
    69  	namedCurve = namedCurveFromOID(oidNamedCurveP256)
    70  	assert.Equal(t, elliptic.P256(), namedCurve, "Did not receive expected named curve for oidNamedCurveP256")
    71  
    72  	// Test for valid P256 elliptic curve
    73  	namedCurve = namedCurveFromOID(oidNamedCurveP384)
    74  	assert.Equal(t, elliptic.P384(), namedCurve, "Did not receive expected named curve for oidNamedCurveP384")
    75  
    76  	// Test for valid P521 elliptic curve
    77  	namedCurve = namedCurveFromOID(oidNamedCurveP521)
    78  	assert.Equal(t, elliptic.P521(), namedCurve, "Did not receive expected named curved for oidNamedCurveP521")
    79  
    80  	testAsn1Value := asn1.ObjectIdentifier{4, 9, 15, 1}
    81  	namedCurve = namedCurveFromOID(testAsn1Value)
    82  	if namedCurve != nil {
    83  		t.Fatal("Expected nil to be returned.")
    84  	}
    85  }
    86  
    87  func TestPKCS11GetSession(t *testing.T) {
    88  	if testing.Short() {
    89  		t.Skip("Skipping TestPKCS11GetSession")
    90  	}
    91  	var sessions []pkcs11.SessionHandle
    92  	for i := 0; i < 3*sessionCacheSize; i++ {
    93  		sessions = append(sessions, currentBCCSP.(*impl).getSession())
    94  	}
    95  
    96  	// Return all sessions, should leave sessionCacheSize cached
    97  	for _, session := range sessions {
    98  		currentBCCSP.(*impl).returnSession(session)
    99  	}
   100  	sessions = nil
   101  
   102  	// Lets break OpenSession, so non-cached session cannot be opened
   103  	oldSlot := currentBCCSP.(*impl).slot
   104  	currentBCCSP.(*impl).slot = ^uint(0)
   105  
   106  	// Should be able to get sessionCacheSize cached sessions
   107  	for i := 0; i < sessionCacheSize; i++ {
   108  		sessions = append(sessions, currentBCCSP.(*impl).getSession())
   109  	}
   110  
   111  	// This one should fail
   112  	assert.Panics(t, func() {
   113  		currentBCCSP.(*impl).getSession()
   114  	}, "Should not been able to create another session")
   115  
   116  	// Cleanup
   117  	for _, session := range sessions {
   118  		currentBCCSP.(*impl).returnSession(session)
   119  	}
   120  	currentBCCSP.(*impl).slot = oldSlot
   121  }
   122  
   123  func TestPKCS11ECKeySignVerify(t *testing.T) {
   124  	if testing.Short() {
   125  		t.Skip("Skipping TestPKCS11ECKeySignVerify")
   126  	}
   127  
   128  	msg1 := []byte("This is my very authentic message")
   129  	msg2 := []byte("This is my very unauthentic message")
   130  	hash1, _ := currentBCCSP.Hash(msg1, &bccsp.SHAOpts{})
   131  	hash2, _ := currentBCCSP.Hash(msg2, &bccsp.SHAOpts{})
   132  
   133  	var oid asn1.ObjectIdentifier
   134  	if currentTestConfig.securityLevel == 256 {
   135  		oid = oidNamedCurveP256
   136  	} else if currentTestConfig.securityLevel == 384 {
   137  		oid = oidNamedCurveP384
   138  	}
   139  
   140  	key, pubKey, err := currentBCCSP.(*impl).generateECKey(oid, true)
   141  	if err != nil {
   142  		t.Fatalf("Failed generating Key [%s]", err)
   143  	}
   144  
   145  	R, S, err := currentBCCSP.(*impl).signP11ECDSA(key, hash1)
   146  
   147  	if err != nil {
   148  		t.Fatalf("Failed signing message [%s]", err)
   149  	}
   150  
   151  	_, _, err = currentBCCSP.(*impl).signP11ECDSA(nil, hash1)
   152  	assert.Error(t, err)
   153  	assert.Contains(t, err.Error(), "Private key not found")
   154  
   155  	pass, err := currentBCCSP.(*impl).verifyP11ECDSA(key, hash1, R, S, currentTestConfig.securityLevel/8)
   156  	if err != nil {
   157  		t.Fatalf("Error verifying message 1 [%s]", err)
   158  	}
   159  	if pass == false {
   160  		t.Fatal("Signature should match!")
   161  	}
   162  
   163  	pass = ecdsa.Verify(pubKey, hash1, R, S)
   164  	if pass == false {
   165  		t.Fatal("Signature should match with software verification!")
   166  	}
   167  
   168  	pass, err = currentBCCSP.(*impl).verifyP11ECDSA(key, hash2, R, S, currentTestConfig.securityLevel/8)
   169  	if err != nil {
   170  		t.Fatalf("Error verifying message 2 [%s]", err)
   171  	}
   172  
   173  	if pass != false {
   174  		t.Fatal("Signature should not match!")
   175  	}
   176  
   177  	pass = ecdsa.Verify(pubKey, hash2, R, S)
   178  	if pass != false {
   179  		t.Fatal("Signature should not match with software verification!")
   180  	}
   181  }