Hyperledger Fabric密码模块系列之BCCSP(四)

前面说过要找时间介绍一下bccsp包下面的工厂factory,so here it is.

通过factory目前可以获得两类BCCSP实例,一个是上文说的sw,还有一个是通过pkcs11实现的。

BCCSP实例是通过工厂来提供的,sw包对应的工厂在swFactory.go中实现,pkcs11包对应的工厂在pkcs11Factory.go中实现,它们都共同实现了下面的BCCSPFactory接口:

// BCCSPFactory is used to get instances of the BCCSP interface.
11 // A Factory has name used to address it.
12 type BCCSPFactory interface {
13
14     // Name returns the name of this factory
15     Name() string  //用来返回bccsp接口实例名
16
17     // Get returns an instance of BCCSP using opts.
18     Get(opts *FactoryOpts) (bccsp.BCCSP, error)  //根据opts配置返回具体的bccsp实例
19 }

需要注意的是,在factory.go源码中,用全局变量bccspMap(一个BCCSP的数组)来保存这些实例化的bccsp,同时用一个全局变量bootBCCSP来保存缺省的BCCSP接口实例.  这两个全局变量的初始化工作是通过调用InitFactories来实现的。

// InitFactories must be called before using factory interfaces
  8 // It is acceptable to call with config = nil, in which case
  7 // some defaults will get used
  6 // Error is returned only if defaultBCCSP cannot be found
  5 func InitFactories(config *FactoryOpts) error {
  4     factoriesInitOnce.Do(func() {
  3         setFactories(config)
  2     })
  1
        return factoriesInitError
  1 }

1、在使用BCCSP之前都需要调用上面的函数来对bootBCCSP和bccspMap来赋值,之后就可以使用GetDefault()来获取缺省bootBCCSP(默认是sw)或者通过GetBCCSP(name string)来获取bccspMap中其他的BCCSP实例(sw或者pkcs11).  其实bccsp/factory包下面还提供了其他的方法来获取BCCSP实例,如也可以直接通过GetBCCSPFromOpts根据opts的设置来直接得到具体的BCCSP实例,这部分可以直接去看代码实现。

2、接下来就可以通过获取的BCCSP实例(如sw或者pkcs11实现)进行加解密,签名验证,哈希,密钥导入和派生以及密钥生成操作

------------------------------------------

 先把流程弄清楚然后撸代码,这样会爽一点。

 
原文地址:https://www.cnblogs.com/informatics/p/7604470.html