How to do cryptography in blockchain

Cryptography is the practice of hiding data using a set of techniques that changes the form of that data (encryption) so that only an authorized person can change it back to the original data form and read it (decryption). The goal of cryptography is to ensure the security, authenticity, and integrity of data.

In a blockchain, cryptography manages secure access to the blockchain network, verifies the integrity of transactions, maintains the immutability of blockchain records, and ensures the confidentiality of data stored inside a block of the blockchain network. A block is a container that holds and stores data in a blockchain.

In this Answer, we'll discover how cryptography is carried out in blockchain. To do that, we look at the two main types of cryptography in blockchain—symmetric-key cryptography also known as secret-key cryptography, and asymmetric-key cryptography also known as public-key cryptography. These two types of cryptography can be used to serve different purposes in blockchain. The symmetric-key cryptography is used to encrypt the data in each of the blocks in the blockchain, thereby maintaining the integrity of the data in the block. Asymmetric-key cryptography can be used in digital signatures and key management.

Symmetric-key cryptography

In symmetric-key cryptography, the same key used in encrypting the data is also used to decrypt it. Although it is not as secure as asymmetric-key cryptography, it is fast and efficient, which is why it is used to encrypt and decrypt a large amount of data. Some of the symmetric-key cryptography algorithms are Data Encryption Standard (DES), Advanced Encryption Standard (AES), and Triple Data Encryption Standard (3DES).

Symmetric-key cryptography illustration
Symmetric-key cryptography illustration

To perform symmetric-key cryptography in blockchain, follow the steps below:

  1. Symmetric-key generation: When generating a symmetric key, choose a key length. The longer the length, the more secure the key will be. A key length of 128 bits or 256 bits is usually advised. We can generate a symmetric key using tools that support symmetric key generation such as OpenSSL. We can also use the cryptography library in Python or the crypto module in JavaScript.

  2. Encrypt data with generated key: To encrypt the data, we have to select a symmetric encryption algorithm such as AES or DES that will be used along with the generated symmetric key for encrypting the data. This will change the data from its original form into a ciphertextCiphertext is what encryption algorithms transform an original message into., which is just a sequence of ambiguous characters. This ciphertext is then stored on the blockchain.

  3. Decrypt the stored encrypted data: When a block is retrieved from the blockchain, the key is needed to decrypt the encrypted data. In symmetric-key cryptography, the security of data on the blockchain largely depends on the integrity of the symmetric key. If not securely shared, the data can be compromised. One way to securely share the symmetric key is by using key exchange protocols. The authorized recipient then applies the same encryption algorithm and the symmetric key on the retrieved data to decrypt it. The decrypted data can now be used in the blockchain.

Code example

An example of symmetric-key cryptography using JavaScript's crypto module.

// Import the crypto module
const crypto = require('crypto');
// Generate a random symmetric key with length of 128 bits,
// which is the minimum length for a secure symmetric key.
const key = crypto.randomBytes(16);
// Use the key to encrypt data.
function encryptData(data) {
// The data is encrypted using the symmetric key and the AES encryption algorithm.
const cipher = crypto.createCipheriv("aes-128-cbc", key, new Uint8Array(16));
let encryptedData = cipher.update(data, "utf8", "base64");
encryptedData += cipher.final("base64");
// The encrypted data is returned.
return encryptedData;
}
// Use the key to decrypt data.
function decryptData(encryptedData) {
// The encrypted data is decrypted using the symmetric key.
const cipher = crypto.createDecipheriv("aes-128-cbc", key, new Uint8Array(16));
let decryptedData = cipher.update(encryptedData, "base64", "utf8");
decryptedData += cipher.final("utf8");
// The decrypted data is returned.
return decryptedData;
}
// Use the key to encrypt and decrypt some data.
const data = "How to do Cryptography in blockchain by oolawalebright";
const encryptedData = encryptData(data);
const decryptedData = decryptData(encryptedData);
// The data is encrypted and decrypted successfully.
console.log('Ciphertext: ', encryptedData);
console.log('Original data: ', decryptedData);

Code explanation

  • Line 2: We import the crypto module.
  • Line 6: We generate a random symmetric key with length of 128 bits.
  • Lines 9–17: We create a function encryptData that accepts the data as an argument. With the help of the createCipheriv method. The function encrypts data using the AES encryption algorithm and the symmetric key. It returns the encrypted data as a base64 string.
  • Lines 20–28: We create a function decryptData to decrypt the encrypted data. The function takes the encrypted data as an argument and uses the createDecipheriv method, which takes in the symmetric key as an argument for deciphering the parsed data. It returns the decrypted data, which is the original data as a utf-8 string.
  • Lines 31–37: Here, we have an example to encrypt and decrypt data using the created function before logging their values to the console.

Asymmetric-key cryptography

In asymmetric-key cryptography, one public key is used to encrypt the data, and a different key (private key) is used to decrypt it. It is a more secure type of cryptography since the public key is used by the sender to encrypt the information while the receiver uses the private key to decrypt that data, this is why it is used in digital signatures. The public key is shared with others while the private key is kept secret. Some of the asymmetric-key cryptographic algorithms are Rivest-Shamir-Adleman (RSA), Elliptic Curve Cryptography (ECC), and Diffie-Hellman. Here is an example of how it works:

  • James wants to send a message to Helen.

  • James has Helen's public key but not the private key so James encrypts the message using Helen's public key.

  • Helen receives the message in an encrypted form and uses the private key to decrypt it. So, only Helen reads the message since no one else has access to the private key for decrypting the message.

Asymmetric-key Cryptography
Asymmetric-key Cryptography

To perform symmetric-key cryptography in blockchain, follow the steps below:

  1. Asymmetric-key generation: To generate an asymmetric key pair, an asymmetric key generation algorithm such as RSA has to be chosen based on its key size and efficiency. A cryptographic tool like OpenSSL is then used to generate the pair. We can also use cryptographic libraries and modules to achieve this. A private key is first created then a public key is created from the private key. The private key can then be stored securely while the public key can be published or shared on the blockchain.

  2. Encrypt the data: To encrypt the data, the public key of the recipient is applied along with the appropriate encryption function or command of the tool being used. This would change the form of the original data into a ciphertext. We can now store this ciphertext and send it to the recipient on the blockchain.

  3. Decrypt the data: When the recipient receives this encrypted data, decryption is done by applying the corresponding private key to the public key used to encrypt the data. After using the private key along with the decryption function or command of the tool being used, the data becomes readable and understandable for the recipient only.

Code example

An example of symmetric-key cryptography using JavaScript's node-forge library. To run this code, we first need to open your terminal and install the library using npm install node-forge.

const forge = require('node-forge');
// Generate Key Pair
const keyPair = forge.pki.rsa.generateKeyPair({ bits: 2048 });
const privateKey = forge.pki.privateKeyToPem(keyPair.privateKey);
const publicKey = forge.pki.publicKeyToPem(keyPair.publicKey);
// Encrypt Data
function encryptData(data, publicKey) {
// Convert the public key from PEM format to a Forge public key object
const publicKeyObject = forge.pki.publicKeyFromPem(publicKey);
// Encrypt the data using the public key
const encryptedData = publicKeyObject.encrypt(forge.util.encodeUtf8(data));
// Return the encrypted data as base64 string
return forge.util.encode64(encryptedData);
}
// Decrypt Data
function decryptData(encryptedData, privateKey) {
// Convert the private key from PEM format to a Forge private key object
const privateKeyObject = forge.pki.privateKeyFromPem(privateKey);
// Decrypt the encrypted data using the private key
const decryptedData = privateKeyObject.decrypt(forge.util.decode64(encryptedData));
// Return the decrypted data as UTF-8 string
return forge.util.decodeUtf8(decryptedData);
}
// Usage example
const originalData = 'How to do asymmetric-key cryptography by Oolawalebright';
// Encrypt the original data using the public key
const encryptedData = encryptData(originalData, publicKey);
console.log('Encrypted Data:', encryptedData);
// Decrypt the encrypted data using the private key
const decryptedData = decryptData(encryptedData, privateKey);
console.log('Decrypted Data:', decryptedData);

Code explanation

  • Line 1: We import the node-forge module after installing the module onto your local machine.
  • Lines 4–6: We generate the key pair, both public and private key.
  • Line 3–18: We create a function encryptData that takes in the data to encrypt and the public key. This function encrypts the data using some of the methods provided by node-forge. It returns the encrypted data as a base64 string.
  • Lines 21–30: We create a function decryptData that takes the encrypted data and the private key as an argument. The private key is used by a node-forge method to decrypt the data. It returns the original data as a utf-8 string.
  • Lines 32–41: Here, we have an example to encrypt and decrypt data using the created function before logging their values to the console.

Conclusion

It is important to note that both symmetric-key and asymmetric-key cryptography are important in the blockchain. Symmetric-key cryptography is popularly used in encrypting the content of the block while asymmetric-key cryptography finds its use in digital signature and key management. When properly implemented, cryptography ensures the security of transactions and the confidentiality of sensitive information in the blockchain network. As the blockchain ecosystem continues to grow, cryptography will continue to secure and protect the future of the blockchain.

Copyright ©2024 Educative, Inc. All rights reserved