github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/bccsp/factory/pkcs11factory.go (about)

     1  //go:build pkcs11
     2  // +build pkcs11
     3  
     4  /*
     5  Copyright hechain. All Rights Reserved.
     6  
     7  SPDX-License-Identifier: Apache-2.0
     8  */
     9  
    10  package factory
    11  
    12  import (
    13  	"encoding/hex"
    14  
    15  	"github.com/hechain20/hechain/bccsp"
    16  	"github.com/hechain20/hechain/bccsp/pkcs11"
    17  	"github.com/hechain20/hechain/bccsp/sw"
    18  	"github.com/pkg/errors"
    19  )
    20  
    21  const (
    22  	// PKCS11BasedFactoryName is the name of the factory of the hsm-based BCCSP implementation
    23  	PKCS11BasedFactoryName = "PKCS11"
    24  )
    25  
    26  // PKCS11Factory is the factory of the HSM-based BCCSP.
    27  type PKCS11Factory struct{}
    28  
    29  // Name returns the name of this factory
    30  func (f *PKCS11Factory) Name() string {
    31  	return PKCS11BasedFactoryName
    32  }
    33  
    34  // Get returns an instance of BCCSP using Opts.
    35  func (f *PKCS11Factory) Get(config *FactoryOpts) (bccsp.BCCSP, error) {
    36  	// Validate arguments
    37  	if config == nil || config.PKCS11 == nil {
    38  		return nil, errors.New("Invalid config. It must not be nil.")
    39  	}
    40  
    41  	p11Opts := *config.PKCS11
    42  	ks := sw.NewDummyKeyStore()
    43  	mapper := skiMapper(p11Opts)
    44  
    45  	return pkcs11.New(p11Opts, ks, pkcs11.WithKeyMapper(mapper))
    46  }
    47  
    48  func skiMapper(p11Opts pkcs11.PKCS11Opts) func([]byte) []byte {
    49  	keyMap := map[string]string{}
    50  	for _, k := range p11Opts.KeyIDs {
    51  		keyMap[k.SKI] = k.ID
    52  	}
    53  
    54  	return func(ski []byte) []byte {
    55  		keyID := hex.EncodeToString(ski)
    56  		if id, ok := keyMap[keyID]; ok {
    57  			return []byte(id)
    58  		}
    59  		if p11Opts.AltID != "" {
    60  			return []byte(p11Opts.AltID)
    61  		}
    62  		return ski
    63  	}
    64  }