Fabric Source Parsing 13--peer's BCCSP service

Source: Internet
Author: User
Tags bool constant decrypt hash sessions asymmetric encryption
Fabric Source Parsing 13--peer's BCCSP service General topics of cryptography

Encryption involves the content is very complex, is a highly professional discipline. I have not specifically learned, here is just a little bit about the BCCSP services involved in the fur: RSA-an asymmetric encryption algorithm for encryption. There are several ethnic clusters, such as rsa1024,rsa2048. AES-a block encryption algorithm for encrypting large chunks of data. There are several ethnic clusters, such as aes128,aes192. ECDSA-an Elliptic curve signature that is used for signing. There are several ethnic clusters, such as ecdsap256,ecdsap384. Hash-hashes, with several ethnic clusters, such as sha256,sha3_256. HMAC-the cryptographic key-related hash operation message authentication code. X509-One of the certificates, see the explanation of the certificate in article 12. Pkcs#11-A set of standard security interfaces, which can be related to security hardware, above these things, can find it to establish, read, write, modify, delete and other operations to manage.

The constant names of these technologies used by fabric are defined in/fabric/bccsp/opts.go, such as ECDSA support for several types of ecdsap256,ecdsap384. BCCSP Service Structure

BCCSP , which is the abbreviation for Blockchain cryptographic service provider , personal translation area chain Cryptographic service provider The , which provides a variety of encryption techniques for fabric projects, signature technology, and the nature of the tools, are used in the MSP Service module for BCCSP. One point to note here is that the tool is strong, it also shows that if you do not want to specialize in this field, in fact, do not care about the details of its implementation, as long as the use of the line. The code for the BCCSP service is set in /FABRIC/BCCSP , and the directory structure is as follows: mocks-simulation code folder, which you can see to help understand BCCSP services Signer -implements the signer interface of the Crypto standard library, and can be seen in article 12 in the MSP service implementation with the "Private signature pen" Identity signingidentity, the directory of the signature interface is dedicated to the outside world to provide the Signature object functionality. Factory -BCCSP service Factory pkcs11 - BCCSP Service Implementation : HSM-based BCCSP (the hsm-based BCCSP Implementation) SW - BCCSP service Implementation bis : Software-based BCCSP (the software-based Implementation of the BCCSP) UTILS-BCCSP Service tool function Bccsp.go-defines the Bccsp,key interface, the options interface used by many BCCSP interfaces, such as key, Keygenopts,keyderivopts-Keystore.go-defines the management storage interface of key, if the generated key is not temporary, is stored in the implementation object of the interface, if it is transient, does not store Xxxopts.go- XXX represents the various values under this directory, the option implementation of the various techniques used by the BCCSP service implementation

From the above you can see that there are two implementations of the BCCSP service: PKCS11 and SW . The simple and clear explanation (though not very precise) is that PCKCS11 is the hardware-based cryptographic service implementation, SW is the software-based cryptographic service implementation. The implementation of this hardware base is based on the https://github.com/miekg/pkcs11 of this library, and the HSM is the abbreviation for the hardware security Modules, the hardware safety module. Corresponding to the two BCCSP service implementations, there are two kinds of factories, two factories for other use BCCSP Service module provides window functions (that is, to other modules to provide window functions, these functions are generally unified management of their own service module for the outside world to call, The Initfactories function as described later). All the resulting BCCSP instances are stored in the global variables defined in Factory/factory.go. interfaces and options in BCCSP Interface

Define type BCCSP Interface {///Based on key generation option in Fabric/bccsp/bccsp.go opts generate a key//key related option OPTs option to fit the original key (with "certificate is a level one authentication" Yes) KeyGen (opts keygenopts) (k key, err Error)//Get the option by key opts retrieve a Key from K Keyderiv (k key, opts keyderivopts) (DK key, err Error)//Based on key import option opts import a key Keyimport (Raw interface{}, opts keyimportopts) from a key raw data (K key, err
    Error)/////depending on the ski return the Key GetKey (ski []byte) (k Key, err Error)//////According to the hash option opts hash a message msg, if opts is empty, use the default option Hash (msg []byte, opts hashopts) (hash []byte, err Error)//hash option opts get hash. Hash instance, if opts is empty, the default option Gethash (OPTs hashopts) (H hash) is used. Hash, err Error)//According to the signer option opts, use K to sign the digest, note that if you need to sign the hash value//of a particularly large message, the caller is responsible for hashing the particularly large message and passing it as digest. IGN (K Key, Digest []byte, opts signeropts) (signature []byte, err Error)///According to the appraiser option opts, by comparing K and digest, identify signature Verify (k Key, Signature, Digest []byte, opts signeropts) (valid bool, err error)//According to the dongle option opts, use K encryption plaintext Encrypt (k Key , Plaintext []byte, opts encrypteropts) (ciphertext []byte, err Error)//According to the decryption option opts, use K to decrypt ciphertext Decrypt (K Key, C Iphertext []byte, opts decrypteropts) (plaintext []byte, err Error)}
Options

Any file with opt word in the BCCSP folder is the source code associated with the option. With regard to the matching options for objects, we have seen it when we speak MSP services. Depending on the configuration of an option, the object body can get different data or perform different operations , which is also a more interesting language to learn the organizational skills . Especially in BCCSP this involves a lot of technology, and each object itself is divided into many kinds of situations. This is illustrated here with the hash option hashopts and the key import option Keyimportopts as an example:

In/fabric/bccsp/bccsp.go, define//hash options interface type Hashopts interface {algorithm () string//Get hash algorithm string identifier, such as "SHA256", "sha3_25 6 "}//In/fabric/bccsp/hashopts.go one of the definition//hash option implementations, SHA256 option type sha256opts struct {} func (opts *sha256opts) algorithm () St
    Ring {return SHA256}//hash option implementation Two, SHA384 option type sha384opts struct {} func (opts *sha384opts) algorithm () string { Return SHA384}--------------------------------------------------//define//KEY Import option interface type in/fabric/bccsp/bccsp.go Keyimportopts Interface {algorithm () string//Return key import algorithm string ID ephemeral () bool//If the generated key is ephemeral (ephemeral), returns True, Otherwise, return false}//define//key Import options interface implementation in/fabric/bccsp/opts.go, import options for ECDSA keys type ecdsapkixpublickeyimportopts struct {tempor ary bool} func (opts *ecdsapkixpublickeyimportopts) algorithm () string {return ECDSA} func (opts *ecdsapkixpublicke yimportopts) ephemeral () bool {return opts. Temporary}//key Import Option interface implementation Two, ECDSA private key import option type ecdsaprivatekeyimportopts struct {temporary bool} func (OPTs *ecdsaprivatekeyimportopts) Algorithm () string {return ECDSA} func (opts *ecdsaprivatekeyimportopts) ephemeral () bool {return opts. Temporary}//More special, such as signature options interface signeropts//due to the use of the standard library, so the use of this option is more assigned to the NIL,BCCSP source is not implemented
SW Implementation Method

The BCCSP Software (SW) Implementation form is the default form, which can be seen only from the factory's default options defaultopts in/fabric/bccsp/factory/opts.go and the configuration of BCCSP in the core configuration document. The main use of the package is the standard library hash and crypto(including the various packages, such as AES,RSA,ECDSA,sha256, Elliptic,x509 , etc.).

directory structure :/FABRIC/BCCSP/SW
The SW implementation of the IMPL.GO-BCCSP impl Internals.go-The signer, the appraiser, the dongle, the decryption interface definition CONF.GO-BCCSP the SW implementation of the configuration definition —————————————————————— The-–aes.go-aes type of the generated key function, the crypto/decryption implements the ECDSA.GO-ECDSA type of signer, the public key/private key appraiser implements the Rsa.go-rsa type of signer, the public key/private key appraiser implements ———————————————————— ——— –aeskey.go-aes Type Key interface implements the ECDSAKEY.GO-ECDSA type key interface implementation of the RSAKEY.GO-RSA type key interface implementation ——————————————————————— –DUMMYKS.G The KeyStore interface of the O-dummy type is implemented Dummykeystore, when the generated key is ephemeral, it means that the keys are not saved to the file, but are saved in memory, and the key disappears when the system shuts down Fileks.go- The KeyStore interface of the file type implements Filebasedkeystore, when the generated key is not ephemeral, it means that these keys are stored in the file when they are imported, and will not disappear even if the system is turned off

BCCSP Interface Implementation :

To define the
instance structure of the//SW BCCSP in/fabric/bccsp/sw/impl.go
type impl struct {conf *config//bccsp                          instance configuration
    ks   BCCSP. KeyStore                   //key Storage System objects, storing and retrieving key objects
    encryptors map[reflect. Type]encryptor//Crypto map
    decryptors Map[reflect. Type]decryptor//decryption map
    signers    Map[reflect. Type]signer    //signer mapping, key implementation type as the mapped key
    verifiers  Map[reflect. Type]verifier  //Appraiser mapping, key implementation type as a mapped key
}
//dedicated Generate function
func New (...) (BCCSP. BCCSP, error) {...}
The interface implements the
func (CSP *impl) KeyGen (opts BCCSP. keygenopts) (k BCCSP. Key, ...) { ... }
...

On the broad lines, because of the existence of Impl objects and various operation options, most of the interfaces are implemented withSwitch-caseAs the backbone, depending on the type or configuration of the option, the function is completed, and the operations of each branch are basically similar, such as keygen. Next:KeyGen-Three series of keys are generated depending on the key generation options:Ecdsa,aes,rsa。 ECDSA uses the GenerateKey function of the library ECDSA, AES uses a custom getrandombytes function (implemented in Aes.go, wraps Rand.read), and RSA uses the GenerateKey function of the library RSA. Each series also generates different "size" keys depending on the specific parameters, and details are skipped. Finally, different key implementation objects are returned, such as Ecdsaprivatekey,aesprivatekey (defined in the Xxxkey.go in the same directory). It is important to note that the current version of the key used for signing, only support the ECDSA series of key, which is stated in the official document, but from the implementation of the signature support more than one, but, BCCSP in essence, regardless of the implementation of the key, only the caller decides which one to use. And the MSP module is one of BCCSP's users, should be in it this place only recognize ECDSA key.Keyderiv-Based on key get option opts retrieve a key from K, the re-acquisition here can be understood to re-disrupt the contents of K to regenerate into a key. Handle two types of key:Ecdsaxxxkey (XXX stands for public and private), Aesprivatekey。 Finally, two types of keys are returned that are scrambled and regenerated:RerandomizedkeyAndHmacedkey。 For a regenerated key, if the key specified in the option is not transient, it is stored in the KS.Keyimport-Remove the option from raw data raw opts the specified key, if it is not temporary, is stored in the KS and finally returns key. The primitive here refers to the []byte or key-containing data (such as the key in the certificate data). Raw is an empty interface, which means that you can receive any form of raw data. In order to get key, the conversion or extraction of raw data raw, part of the use of Utils tool function Utils. Clone and Utils.dertopublickey, such as the Aes256,ecdsaprivatekey type key, and part of the assertion raw directly with the go language. (*key type), such as the Ecdsagopublickey,rsagopublickey type key.Hash-Hashes a message msg according to the hash option opts, and returns the hash value of the MSG. If opts is empty, the default option is used. This is better understood, the kind supports the SHA2,SHA3 hash family. Sign-Based on the signer option, use K to digestSignature, the signer option here is of little use in the current version, and the caller gives nil.SignatureInvolves theKey InterfaceAndSigner signerImplementation in SW BCCSP. There are three implementations of the key interface: The Rsapublickey/rsaprivatekey in the Ecdsapublickey/ecdsaprivatekey,rsakey.go in Ecdsakey.go, Aeskey.go in the Aesprivatekey, the signature (natural) used is the private key. The signer interface signer is defined in Internals.go in the same directory, there are two types of implementations: Rsa.go in Ecdsasigner and Rsasigner in Ecdsa.go. See the Signers Assignment section of the special generation function new for SW BCCSP, which shows the use of two corresponding types of key and signer:Ecdsaprivatekey-ecdsasignerAndRsaprivatekey-rsasigner。 Over hereSignatureThe implementation is to obtain the type reflect from the Signer collection member signers of the BCCSP instance. The Signer of TypeOf (k) signer, and then directly calls signer's interface sign, retroactively, ecdsasigner using the ECDSA Library's signing function, Rsasigner using the RSA library Privatekey the sign function of the struct body.Verify-According to the appraiser option opts, by comparing K and Digest,IdentificationSignature.IdentificationInvolves theKey InterfaceAndAppraiser Interface VerifierImplementation in SW BCCSP. The key interface is implemented as described above. The Appraiser Interface verifier is defined in Internals.go in the same directory, there are two types of implementations: ecdsapublickeykeyverifier/in Ecdsa.go The Rsapublickeykeyverifier/rsaprivatekeyverifier in Ecdsaprivatekeyverifier and Rsa.go. See the Verifiers Assignment section of the special generation function new for SW BCCSP, which shows that all the appraisers (and the corresponding key interface implementations) are useful. Over hereIdentificationThe implementation is that from the BCCSP instance of the Appraiser collection member verifiers gets the type reflect. TypeOf (k) of the Appraiser Verifier, and then directly Call Verifier interface verify, Trace, Ecdsaxxxkeyverifier use ECDSA Library of the Verify function, Rsaxxxkeyverifier uses the VERIFYPSS function of the RSA library (here XXX represents publickey or private).Encrypt-Using k** encryption according to the OPTs optionplaintext. Encryptioninvolves the **key interfaceAndCrypto Interface EncryptorImplementation in SW BCCSP. The key interface is implemented as described above. The cryptographic interface encryptor is defined in Internals.go in the same directory, implemented in Aes.go (only AES, because only AES is used for encryption): Aescbcpkcs7encryptor. See the Encryptors Assignment section of the SW BCCSP dedicated generation function new, onlyAesprivatekey-aescbcpkcs7encryptorbe used. Over hereEncryptThe implementation is to obtain the type reflect from the Encryptors collection member of the BCCSP instance. TypeOf (k) is encrypted by Encryptor, and then directly calls Encryptor's interface encrypt, retroactively, aescbcpkcs7encryptor encrypted using the AES library encryption process.Decrypt-decryptionSimilar to encryption, the process is similar, and only AES is implemented, eventually using the AES library decryption process to decrypt.GetXXX-GetXXX Series interface, gets the data in the instance object, slightly.

In the FABIRC source code parsing 12--peer MSP Service text, the 3rd and 4 points of the endorsement inspection section, involving BCCSP object members contained in the MSP, using the BCCSP object gethashopt, Hash, Keyimport, Interfaces such as verify are used to generate identities objects or identities some of their own interface implementations. Here you can see. PKCS11 Implementation Method

BCCSP's PKCS11 implementation form is mainly used in the same library as the SW implementation, but with a github.com/miekg/pkcs11 library, it is best to refer to its documentation to familiarize yourself with PKCS11 's brief operations. PKCS11 (Pkcs,public-key Cryptography Standards) is a very common set of interface standards, which can be said to be pkcs11 with BCCSP, but also for the fabric to support hot-swappable and personal security hardware modules to provide services. This can be seen from the BCCSP PKCS11 implementation instance of the dedicated generation function new (see below) called the Loadlib function can see: loadlib loaded a system of dynamic library, can load the system's dynamic library, can and drive, hot plug, Connect the computer's character devices together. For example, in the future, we have developed a kind of personal identity or secure trading hardware module or chip which is similar to the U shield used by internet banking in the area chain, and these hardware modules or chips need to follow pkcs11,fabric to support and extend.

For the interface provided by PKCS11, there are two document addresses available here, which the reader can learn a little bit about: https://www.ibm.com/developerworks/cn/security/s-pkcs/,/HTTP/ Docs.oracle.com/cd/e19253-01/819-7056/6n91eac56/index.html#chapter2-9. These documents are not related to the fabric and area chain, but because PKCS11 is a common interface, it has some reference value. The explanations in the PKCS11 library are relatively simplistic.

directory structure :/FABRIC/BCCSP/PKCS11
IMPL.GO-BCCSP PKCS11 Implementation Impl Conf.go-Defines the configuration of the BCCSP service and pkcs11opts, filekeystoreopts, dummykeystoreopts options Pkcs11.go -based on the PKCS11 library , it wraps various PKCS11 functions, realizes Impl PKCS11-based tune function, and the independent tune function used by some BCCSP services ——————————————————— ———— –aes.go-Implementation of AES type generation key, encryption, decryption function Ecdsa.go-Implement IMPL signature function Signecdsa and authentication function VERIFYECDSA in ECDSA technology ——————————————————————— –aeskey.go-Implementation of the AES type key interface, only to implement the private key Aesprivatekey ecdsakey.go-Implementation of the ECDSA type key interface, the realization of the public key Ecdsapublickey, private key Ecdsaprivatekey Rsakey.go-Implements the RSA type key interface, realizes the public key Rsapublickey, the private key Rsaprivatekey ——————————————————————— –dummyks.go- The KeyStore interface of the dummy type implements the KeyStore interface implementation of the Dummykeystore Fileks.go-file type Filebasedkeystore

BCCSP Interface Implementation :

Type impl struct {
    conf *config                       //configuration
    ks   BCCSP. KeyStore                //key Storage System object, stores and gets the key object
    ctx      *pkcs11. CTX               //The PKCS11 context of the standard library
    sessions Chan Pkcs11. SessionHandle//Essence is UINT, session identifier channel, default 10 cache
    slot     UINT                      //security hardware Peripheral Connection Slot identification number
    lib          string                // Load Library path
    noprivimport bool                  //Prohibit import of private key ID
    softverify   bool                  //Use software method to identify signature identity
}
// The dedicated generate function
func New (opts pkcs11opts, KeyStore BCCSP. KeyStore) (BCCSP. BCCSP, error) {...}
The interface implements the
func (CSP *impl) KeyGen (opts BCCSP. keygenopts) (k BCCSP. Key, err Error) {...}
...

BCCSP PKCS11 implementation of the skeleton in the impl.go with the implementation of the SW is basically consistent, only to trace back to the final implementation of the statement, the SW implementation is to use the crypto library under the various packages for signature, encryption, key import, etc. Instead, PKCSLL uses the PKCS11 package to handle the data in layers, using the PKCS11 provided context (PKCS11. CTX) and session (SessionHandle) on the management of signatures, keys, encryption, and so on, which is also the role of pkcs11.go files . The biggest difference between the two is a software-oriented, hardware-oriented, PKCS11 itself is very jumbled, so in this only PKCS11 with security hardware modules to establish a connection loadlib function.

The loadlib function is defined in Pkcs11.go for use by the dedicated build function new. In order to establish the communication with the security hardware module, the following steps are taken: loading the dynamic library (such as Opencryptoki Dynamic Library) According to the given system dynamic Library path, calling PKCS11. New (Lib) establishes Pkcs11 instance ctx. CTX corresponds to a bridge between fabric and the secure hardware module: Thebccsp<–>ctx<–> drives the lib<–> security hardware module , as long as the drive Lib is developed in accordance with the PKCS11 standard. CTx. Initialize () is initialized. From CTX. Getslotlist (True) gets the slot that is specified by the label in the returned list of slots (the slots here can be easily understood as the slots that the computer hosts insert into the security hardware module, such as USB jacks, which may be more than one, each with a name and identification number in the system kernel). Try to invoke CTX 10 times. Opensession Open a Conversation session (the session is a communication path with the security hardware module to establish a connection, you can easily understand as Pkcs11 Chan). Login Session CTX. Login. Returns the Session object Ctx,slot, which is used to assign a value to the Impl instance member Ctx,slot, sending the session to sessions.

About PKCS11, there is one more thing to say, is the SOFTHSM library, it is a simulation of hardware implementation of PKCSLL, The corresponding system dynamic library can be referred to in the Findpkcs11lib test function in Impl.go, such as Libsofthsm2.so under Linux. At this stage, there is no security hardware module can be tested with, so only use SOFTHSM simulation test, libsofthsm2.so import Pkcs11 object. BCCSP Factory

For two BCCSP implementations, there are also two BCCSP plants:pkcs11factory.go and swfactory.go. Once a module in fabric involves a factory factory, the module is basically provided by the Factory "window functions" for other modules to invoke. Here, take swfactory as an example to explain.

directory structure :/fabric/bccsp/factory/
Factory.go-Declares the default BCCSP instance defaultbccsp, BCCSP the instance store map Bccspmap and other global variables and the Get function GetXXXfor those variables, Defines the BCCSP factory interface. Nopkcs11.go/pkcs11.go-defines two versions of the factory option factoryopts, the initial chemical plant function initfactories and gets the specified BCCSP instance function getbccspfromopts. NOPKCS11 is the default version, and conditional compilation specifies which version to use (add NOPKCS11 or!NOPKCS11 option at compile time). The differences between the two versions are focused on whether to use PKCS11. Opts.go-Defines the default factory option defaultopts. The PKCS11FACTORY.GO-PKCS11 type of BCCSP factory implements Pkcs11factory. The SWFACTORY.GO-SW type of BCCSP factory implements Swfactory. The BCCSP option for the SW version is also defined.

Swfactory interface and implementation :

Define//
interface in Factory.go
type Bccspfactory interface {

    //return factory name
    () string
    // Returns the BCCSP instance
    Get (opts *factoryopts) (BCCSP) that complies with the factory option opts. BCCSP, error)
}

//Swfactory.go in the definition
//implementation of
type Swfactory struct{}
func (f *swfactory) Name () string {
    return softwarebasedfactoryname
}
func (f *swfactory) Get (config *factoryopts) (BCCSP. BCCSP, error) {...}

The implementation of the code itself is relatively simple, get is finally called the SW of the dedicated generation function new to generate opts-compliant BCCSP instances. The name returns a "SW" constant directly.

In each Chaincode example, such as/fabric/examples/e2e_cli/examples/chaincode/go/chaincode_example02/chaincode_ Example02.go, the start function in the Chaincode gasket shim is used. Do not know in Fabirc source code parsing 7--peer Chaincodesupport Service article whether said, in this said, Chaincode "gasket" shim core code in/fabric/core/chaincode/shim, The gasket "Cushion" is the task of communication with each node, also known as Chaincodesupport service. Chaincode forms the communication information, distributed through the shim to the various nodes, and then shim is responsible for collecting information from each node, summarizing the return to Chaincode, complete chaincode function. Where Shim's start function is used to start a chaincode, defined in/fabric/core/chaincode/shim/chaincode.go. In the function of start, err: = Factory is called. Initfactories (&factory. defaultopts) to initialize a default BCCSP factory, where you can see the default factory options used here (see OPTS.GO), which is the swfactory used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.