USD

Build Security into Blockchain Applications: Part 2 – Rapid Deployment with a Turnkey Solution

By Stephen Evanczuk

Contributed By Digi-Key's North American Editors

Editor’s Note: The details of blockchain technology and its transaction methods are complex. Part 1 of this two-part series provides an overview of blockchain structure and its transaction process. This gives context toward an understanding of why protection of private keys lies at the core of blockchain security and leads into the introduction of a turnkey solution for securing private keys. Here, Part 2 will show how developers can more easily protect blockchain transactions using this turnkey, hardware-based solution.

Beyond its familiar use in cryptocurrencies, blockchain technology can offer developers a secure infrastructure with broad applicability. Its decentralized architecture eliminates the need for a central authority, relying instead on private keys and cryptography methods to protect assets and their exchange between parties. Consequently, the security of a blockchain system depends critically on the security of keys and their proper use in robust algorithms.

Although appropriate algorithms are readily available, implementation requires significant expertise and experience to develop a secure solution and integrate it in the target application. Without the proper tools for building blockchain into the core of their application, developers can find their efforts stalled or even vulnerable to cyberthieves.

This article shows how developers can more easily protect blockchain transactions using a turnkey, hardware-based solution for blockchain security from Infineon Technologies.

Private key security

Blockchains eliminate the need for a central authority for approval of transactions. Instead, this technology relies on consensus mechanisms to maintain integrity of a blockchain continually extended with a set of transactions signed and verified using cryptography and a private/public key pair. In fact, private keys serve as ownership credentials in blockchain systems. Their loss or exposure through accident or theft has already resulted in significant cryptocurrency losses. As a result, the security of private keys is of paramount concern in deploying blockchain applications.

Earlier approaches based on software or limited hardware security can leave private keys vulnerable to a wide range of attacks. In contrast, more robust solutions are built on security controllers designed with deep protection against diverse direct and indirect threats. Using a solution based on this type of security controller, the Infineon Blockchain Security 2Go starter kit (BLOCKCHAINSTARTKITTOBO1) provides the deep protection required for blockchain security.

Rather than facing the challenges of implementing their own solution, developers can provide users with contactless smartcards with built-in support for blockchain security mechanisms including transaction signing, the critical first step in extending a blockchain (Figure 1).

Diagram of Infineon Blockchain Security 2Go smartcardFigure 1: The Infineon Blockchain Security 2Go smartcard simplifies deployment of blockchain security with built-in support for blockchain mechanisms including signing transactions used to extend a blockchain. (Image source: Infineon Technologies)

Secure platform

The Infineon Blockchain Security 2Go starter kit provides blockchain system integrators with a turnkey security solution that eliminates the need for non-disclosure agreements typically required for acquiring security devices.

Designed for rapid deployment using open-source software from Infineon, the kit includes five smartcards that implement key blockchain mechanisms including secure key generation, signature creation, and PIN authentication. The related Infineon Security 2Go 10 card package (BLOCKCHAIN10CARDSTOBO1) provides developers with an additional source of these smartcards.

The cards conform to the ISO/IEC 7810 ID-1 standard used for conventional payment cards and identity cards in some regions. For connectivity, the smartcards integrate a Class 1 antenna based on ISO/IEC 14443 for contactless cards using near-field communication (NFC).

Embedded in each card, a security controller provides hardware-based security for creation and storage of up to 255 private/public key pairs as well as cryptography algorithm execution. Along with an integrated true random number generator (TRNG), the cards support algorithms for both symmetric cryptography using 256-bit Advanced Encryption Standard (AES) and asymmetric cryptography using 256-bit elliptic-curve cryptography (ECC), preloaded with the secp256k1 ECC curve typically used in cryptocurrencies including Bitcoin and Ethereum.

With their dedicated support for blockchain security mechanisms, the cards provide an immediate solution for securing blockchain transactions. Rather than spend time building secure signing methods, blockchain system integrators can simply hand users smartcards to use when interacting with the deployed blockchain system.

Simpler interactions

For users, the smartcards provide a straightforward method for performing blockchain transactions while fully securing their private keys. The cards are designed to work with software running on an interface device such as an NFC smartphone or computer equipped with a standalone NFC smartcard reader. While running their blockchain application, users activate the card's features by placing the card on the interface device (Figure 2).

Image of NFC reader on the back of a Google Pixel smartphoneFigure 2: Users invoke smartcard functionality by bringing it near the NFC reader antenna such as the glossy area on the back of a Google Pixel smartphone, as shown here. (Image source: Infineon Technologies)

For immediate evaluation of the Security 2Go smartcards, Infineon provides an Android mobile app that demonstrates their use in typical scenarios. After it launches on an NFC-capable smartphone, the mobile app invites the user to place the card against the smartphone's NFC antenna area, enabling the full mobile app interface (Figure 3).

Diagram of Coinfinity GmbH for the Blockchain Security 2Go starter kitFigure 3: Developed by Coinfinity GmbH for the Blockchain Security 2Go starter kit, a pre-built Android app shows how after the card requests contact with the smartcard (left), it uses smartcard features to demonstrate different usage scenarios (right). (Image source: Infineon Technologies)

Behind the scenes in this mobile app and other deployments, software running on the smartphone or other interface device issues commands to perform functions such as to generate a new key pair or get information about an existing key pair. Throughout these and other command sequences, the private key never leaves the smartcard. In response to commands that involve private keys, the smartcard at most returns a key handle to the interface device. In turn, the interface device software uses that handle to execute related commands such as retrieving the public key paired with a particular private key (Figure 4).

Using this approach, software running on the interface can fully complete operations required to interact with the blockchain system without compromising the secret data.

Diagram of key generation request to an Infineon Blockchain Security 2Go smartcardFigure 4: An interface device such as a smartphone or smartcard reader issues commands such as this key generation request to an Infineon Blockchain Security 2Go smartcard, which creates a private/public key pair and returns the public key without revealing the private key. (Image source: Infineon Technologies)

The interface device software retains responsibility for performing application-specific functions such as transforming the public key into the (typically unique) blockchain address used for each transaction. For example, a Bitcoin address uses the public key as input to a one-way hashing algorithm, which generates an address that depends on the public key but cannot be used to recreate the public key.

For signing a transaction request, the interface similarly issues a command and accompanying hash result to the smartcard. In response, the smartcard returns the signature to the interface device (Figure 5).

Diagram of Infineon Blockchain Security 2Go smartcard signatureFigure 5: Signing a transaction requires use of a private key, but with the Infineon Blockchain Security 2Go smartcard, an interface device receives the signature without exposure of the all-important private key. (Image source: Infineon)

Application Protocol Data Units

For each command and response, an interface device and smartcard interact using Application Protocol Data Units (APDUs), defined in part 4 of the ISO/IEC 7816 standard. For every interaction with the smartcard, the interface device issues service requests in the ISO/IEC-7816 standard command APDU format and receives (optional) responses in the standard response APDU format (Figure 6).

Table of ISO/IEC 7816 standard formats for command APDUs and response APDUsFigure 6: ISO/IEC 7816 standard formats for command APDUs and response APDUs form the basis of communications between interface devices and conforming smartcards such as the Infineon Blockchain Security 2Go smartcard. (Image source: Infineon Technologies)

Within a command APDU, the supported instructions and parameters are defined by the smartcard provider in conformance with industry standards used in the target application area. For its Blockchain Security 2Go smartcards, Infineon defines a core set of commands needed to take advantage of the smartcard's functional capabilities (Table 1).

Table of command set for the Infineon Blockchain Security 2Go smartcardTable 1: Command set for the Infineon Blockchain Security 2Go smartcard. (Table source: created by Digi-Key Electronics from Infineon Technologies data)

For example, to start a new session, the interface device software constructs the SELECT APPLICATION command APDU with a data value for the fixed application identifier (AID) provided by Infineon for the Blockchain Security 2Go starter kit. After receiving that command APDU, the smartcard initializes itself for a new session and transmits the corresponding response APDU, which includes some smartcard metadata (Figure 7).

Table of Infineon specific APDU field values needed for commandsFigure 7: For its Blockchain Security 2Go smartcard, Infineon provides the specific APDU field values needed for commands and expected in responses and error codes such as this set for initializing the smartcard, which includes the fixed application identifier (AID) provided by Infineon. (Image source: Infineon Technologies)

Custom software

Developers do not need to work at this low level in creating new applications using Blockchain Security 2Go smartcards. In its Blockchain Security 2Go GitHub repository, Infineon provides sample applications and documentation on smartcard usage.

Infineon includes the complete Java source code for its Android mobile app in its BlockchainSecurity2Go Android code GitHub repository. By exploring this code base, software programmers can quickly learn key design patterns including initializing a smartcard session (selectApplication()), reading a public key from a smartcard (readPublicKeyFromCard()), and creating a new key pair (generateNewSecp256K1Keypair()) if a public key does not already exist on the card (Listing 1).

Copy
    /**
     * Read public key from card, or create a new one if it doesn't exist yet.
     *
     * @param card nfc card
     * @return public key as hexadecimal String
     * @throws IOException      on communication errors
     * @throws NfcCardException when card returns something other than 0x9000 or 0x61XX
     */
    public static GetKeyInfoResponseApdu readPublicKeyOrCreateIfNotExists(NfcTranceiver card, int keyIndex)
            throws IOException, NfcCardException {
        try {
            selectApplication(card);
            // try to read public key
            return readPublicKeyFromCard(card, keyIndex);
        } catch (NfcCardException e) {
            // if Public key is not available yet (Status words: 0x6A88)
            if (e.getSw1Sw2() == SW_KEY_WITH_IDX_NOT_AVAILABLE) {
                int newKeyIndex;
                do {
                    // create a new keypair
                    newKeyIndex = generateNewSecp256K1Keypair(card);
                } while (newKeyIndex <= keyIndex);
                // and ask for the pubkey of the newly created keypair
                return readPublicKeyFromCard(card, newKeyIndex);
            } else {
                // throw all other exceptions to our caller
                throw e;
            }
        }
    }

Listing 1: Infineon provides the complete source code for its Blockchain Security 2Go Android app, which demonstrates basic interactions such as reading a public key or creating a new private/public key pair. (Code source: Infineon Technologies)

Utility classes in the Java code base implement detailed interactions such as creating the SELECT APPLICATION APDU. Routines that call the member function shown in Listing 2 (below) pass an aid parameter holding the Infineon Blockchain Security 2Go AID, which is declared earlier in the package as follows:

Copy
        public static final byte[] AID_INFINEON_BLOCKCHAIN2GO = fromHexString("D2760000041502000100000001");
 
public class SelectApplicationApdu extends BaseCommandApdu {
 
    /**
     * Instruction byte for SELECT APPLICATION operation.
     */
    private static final int INS_SELECT_APPLICATION = 0xA4;
 
    /**
     * Constructs a SELECT APPLICATION command apdu.
     */
    public SelectApplicationApdu(byte[] aid) {
        this.ins = INS_SELECT_APPLICATION;
        this.p1 = 0x04;
        this.setData(aid);
        this.leIncluded = true;
    }
 
}

Listing 2: The Infineon Blockchain Security 2Go Android app source distribution illustrates creation of a command APDU for initializing the smartcard. (Code source: Infineon Technologies)

For rapid development, Infineon also provides a Blockchain Security 2Go Python library and a command line interface built on top of this library. As with the Java version, the Python code demonstrates the simple design pattern required to execute smartcard operations such as generating a key pair (Listing 3).

Copy
def select_app(reader):
    """ Sends command to select the Blockchain Security2GO application
 
    Needs to be called after reset to allow for access to
    blockchain commands.
 
    Returns:
        :obj:`tuple`: (pin_active, card_id, version).
        
        pin_active:
            bool: True if PIN is set on the card
        
        card_id:
            bytes: 10 byte unique card identifier
        
        version:
            str: card firmware version, following
            semantic versioning.
    
    Raises:
        CardError: If card indicates a failure.
        
        Any exceptions thrown by the reader wrapper are passed through.
    """
    logger.debug('SELECT Blockchain Security 2Go starter kit')
    aid = bytes.fromhex('D2760000041502000100000001')
    r = reader.transceive(b'\x00\xA4\x04\x00', aid).check()
 
    pin_active = True if r.resp[0] == 1 else False
    card_id = r.resp[1:11]
    version = r.resp[11:].decode('ASCII')
    return (pin_active, card_id, version)
 
def generate_keypair(reader):
    """ Sends command to generate new keypair
 
    A new keypair is generated and stored. The ID identifying this
    keypair is returned. A key using the `secp256k1`_ curve is generated.
 
    Args:
        reader (:obj:): object providing reader communication
 
    Returns:
        int: ID of the just generated keypair, to be used e.g. for
        future signatures using ``generate_signature``
    
    Raises:
        CardError: If card indicates a failure, e.g. if card is full.
        
        Any exceptions thrown by the reader wrapper are passed through.
    
    .. _secp256k1:
        http://www.secg.org/sec2-v2.pdf
    """
    logger.debug('GENERATE KEYPAIR')
    r = reader.transceive(b'\x00\x02\x00\x00').check()
 
    key_id = int(r.resp[0])
    logger.debug('generated key %d', key_id)
    return key_id

Listing 3: The Infineon Blockchain Security 2Go Python library and accompanying command line interface aids rapid development with a full set of service routines such as the select_app() function for initializing a Blockchain Security 2Go smartcard and generate_keypair(), which each demonstrate basic design patterns for smartcard interaction. (Code source: Infineon Technologies)

In characteristic Pythonic fashion, the Blockchain Security 2Go Python library builds on readily available third-party modules. In particular, the Infineon library uses the popular pyscard module, wrapping its functions in its own class definition. For example, the Blockchain Security 2Go Python library begins a smartcard session by finding a personal computer/smartcard (PC/SC) reader. For the Blockchain Security 2Go Python library's primary blocksec2go module, this discovery occurs using the function open_psycard(), which is a member function in a library class that wraps pyscard functions (Listing 4).

Copy
class PySCardReader:
    """ Wrapper to use PyScard with blocksec2go
    
    Abstracts communication into a simple function
    """
    def __init__(self, connection):
        self.connection = connection
        self.connection.connect()
    
    def transceive(self, header, data = b'', le = -1):
        apdu = Apdu(header, data, le)
        logger.debug(apdu)
        resp = self._transceive(bytes(apdu))
        logger.debug(resp)
        return resp
 
    def _transceive(self, data):
        resp, sw1, sw2 = self.connection.transmit(array.array('b', data).tolist())
        return ApduResponse(array.array('B', resp).tobytes(), (sw1 << 8) + sw2)

Listing 4: The Infineon Blockchain Security 2Go Python library wraps interactions with the third-party pyscard module in this class, using its member functions to invoke pyscard functions. (Code source: Infineon Technologies)

Conclusion

Blockchain technology offers a framework that broadens accessibility to information without compromising its integrity or authenticity. Rather than relying on a central authority, a blockchain system uses cryptography to verify transactions and protect them from modification. Pivotal to this approach, private keys need robust security mechanisms to prevent loss of control of users' transactions and the compromise of the blockchain system.

As shown, with its accompanying open-source software, the Infineon Blockchain Security 2Go starter kit provides blockchain system integrators with an immediate security solution and provides users with a simpler, more secure method of executing blockchain transactions.

Disclaimer: The opinions, beliefs, and viewpoints expressed by the various authors and/or forum participants on this website do not necessarily reflect the opinions, beliefs, and viewpoints of Digi-Key Electronics or official policies of Digi-Key Electronics.

About this author

Stephen Evanczuk

Stephen Evanczuk has more than 20 years of experience writing for and about the electronics industry on a wide range of topics including hardware, software, systems, and applications including the IoT. He received his Ph.D. in neuroscience on neuronal networks and worked in the aerospace industry on massively distributed secure systems and algorithm acceleration methods. Currently, when he's not writing articles on technology and engineering, he's working on applications of deep learning to recognition and recommendation systems.

About this publisher

Digi-Key's North American Editors