What is the relationship between cryptography and digital currencies?

Author: Zen and the Art of Computer Programming

1. Introduction

The word “encryption” has always attracted social attention, and it seems to be everywhere today. With the popularity of the Internet, all kinds of information, messages, and emails have been stolen, tampered with, and even spread without protection by unsuspecting people. This has become a real problem facing the global society.

“Encryption” is one of the most basic concepts in the field of information security. It processes data to transform information into a form that cannot be clearly seen. Only those who have mastered the relevant passwords can recover the information and achieve information security. Integrity. Of course, encryption is not free and comes with a price.

As a kind of cryptocurrency, digital currency has also attracted widespread attention due to its unique properties. In recent years, digital currencies have been increasingly used in payment, transactions, stored value and other scenarios.

So, what does crypto and digital currencies have to do with each other? If encryption technology is understood as a means of information hiding, then the connection between encryption technology and digital currency can be simply summarized as:

  1. Data encryption technology: Traditionally, encryption technology is mainly based on symmetric encryption algorithms, including DES, AES, RSA, etc. These algorithms encrypt information and can only be decrypted by people who know the password. However, with the popularization of computers and the development of the Internet, symmetric encryption algorithms can no longer meet the needs. Asymmetric encryption algorithms (such as RSA), public and private key algorithms (such as ECDSA, EdDSA), Hash functions, encoding, and hybrid encryption have emerged. wait.

  2. Digital currency: Digital currency is a type of cryptocurrency whose basic characteristics are decentralization, anonymity, traceability, and portability. At the same time, digital currency has unique characteristics such as scarcity, tradability, and unpredictability.

From an economic perspective, the combination of encryption technology and digital currency can effectively reduce the risk of information disclosure, promote the operation of the entire financial system, and promote the transformation of the real economy into the emerging blockchain economy or distributed ledger economy. From a legal perspective, the combination of encryption technology and digital currencies can also help promote the formulation and implementation of international trade regulations, enhance the transparency and efficiency of financial services, and improve the security of the financial system.

2.Basic concepts

2.1 symmetric encryption algorithm

Symmetric Encryption Algorithm is also known as shared key encryption algorithm, symmetric encryption algorithm, and single-key encryption algorithm. It refers to the method of using the same key for encryption and decryption. Because the same key is used for encryption and decryption, this encryption method is called a symmetric encryption algorithm.

Symmetric encryption algorithms are based on two aspects. First, both parties must know each other’s key; second, the encryption process must ensure the confidentiality of the key and cannot be leaked to any third party. The advantages of the symmetric encryption algorithm are fast speed, high encryption efficiency, and small amount of calculation, but it is weak in security and requires high data confidentiality.

Currently, symmetric encryption algorithms are mainly divided into two types: block encryption algorithm and stream encryption algorithm.

  1. Block Cipher: block cipher. The data is divided into fixed-size blocks and then encrypted block by block. The biggest advantage is that when the receiving end receives a block cipher, it can easily determine whether it has been modified. However, it also has a disadvantage, that is, the processing efficiency is relatively slow. In addition, even if the receiver decrypts the data correctly, he may not know the correct order because it is a block cipher.

  2. Stream Cipher: Stream cipher. It does not need to store the entire data in the memory, it only needs to continuously receive and send data. It produces random output, so it is impossible to tell whether the plaintext has been modified. Although its security is weak, its calculation speed is fast and it is suitable for encrypting large volumes of data.

2.2 Asymmetric encryption algorithm

Asymmetric Encryption Algorithm is also called public key encryption algorithm and public key encryption algorithm. It is an algorithm used to encrypt and sign messages. It can encrypt and decrypt information using public keys and private keys at the same time. The public key is used for encryption and the private key is used for decryption. Information encrypted by the public key can only be decrypted by the private key. , information encrypted with the private key can only be decrypted with the public key. The private key is kept by the owner and will not be disclosed. The public key can be released to the outside world and anyone can use it for encryption. The asymmetric encryption algorithm requires two keys during the communication process, one is the public key and the other is the private key.

In addition to its encryption function, asymmetric encryption algorithms can also be used as digital signatures. A digital signature refers to a string of values generated by a private key. This value is an authentication of the message. Once someone calculates the hash of a message and signs it with his or her private key, only the owner of the public key can verify its authenticity. This process is entirely based on asymmetric encryption algorithms.

Currently, commonly used asymmetric encryption algorithms include RSA, ECC (elliptic curve cryptography algorithm), and DSA (digital signature algorithm). The main difference between them is that RSA is currently the most common public key encryption algorithm, while ECC and DSA are digital signature algorithms.

2.3 Message Digest Algorithm

Message Digest Algorithm is also called hash function, hash function, and digest algorithm. It is an algorithm that calculates a fixed-length data string in order to discover whether the original data has been tampered with. Commonly used message digest algorithms include MD5, SHA-1, SHA-256, etc.

Using the message digest algorithm, the integrity of the data can be verified without transmitting the complete message. For example, Alice sends a file to Bob, Bob sends the MD5 value of the file to Alice, and Alice recalculates the file based on the MD5 value to check whether the two results are consistent. If they are consistent, it means that the file has not been modified, otherwise it may have been tampered with.

2.4 Signature Algorithm

Signature Algorithm refers to an encryption method that binds the signature result of the private key to the public key and sends the encrypted result of the public key. The recipient can decrypt the signature through the public key to verify whether the source of the message is valid and avoid the message being forged or tampered with. Commonly used signature algorithms include ECDSA, EDDSA, RSA, etc.

2.5 Digital Currency

Digital Currency usually refers to a virtual cash system built through encryption technology. Digital currency is a tool used for payment, the basis of which is cryptography. Every digital currency transaction is unpredictable and anonymous, and both parties to the transaction can confirm their identity, amount, and time.

2.6 Blockchain

Blockchain is a distributed database system used to store all transaction records of all users in the blockchain network. Blockchain was originally proposed by Satoshi Nakamoto in 2008 to solve the decentralization problem of the credit system. Blockchain is a decentralized peer-to-peer data exchange platform. Any node can join the network and participate in data sharing and value distribution. The distributed database at the bottom of the blockchain ensures the high availability, security and transparency of the system.

Blockchain consensus mechanism:

  1. POW (proof of work): proof of work mechanism. This mechanism consumes a lot of computing resources to create blocks and continuously accumulates eligible blocks. The difficulty value is usually set to a large integer, and as the performance of computing devices improves, the difficulty value can be reduced to ensure that the cost of block creation approaches zero. Currently, blockchain systems using POW mechanisms include Bitcoin, Ethereum, etc.

  2. POS (proof of stake): Voting equity proof mechanism. This mechanism relies on the votes of holders to choose which accounts participate in block production, rather than relying on the accumulation of computing power like the POW mechanism. The advantage of the voting proof-of-stake mechanism is that it is more resistant to attacks. As long as a certain number of miners vote, it is enough to overturn a block. Currently, blockchain systems using POS mechanisms include EOS, TRON, etc.

3. Core Algorithm Principle and Operation Steps

3.1 RSA algorithm

The RSA algorithm (Rivest-Shamir-Adleman algorithm) is an asymmetric encryption algorithm and it is also the first public key encryption algorithm. Its characteristic is that the public key and the private key are different. The public key can be released arbitrarily, but the private key must be kept strictly confidential. Content encrypted by the public key can only be decrypted by the private key. The RSA algorithm contains the following steps:

  1. Generate two prime numbers p and q, and calculate n=pq.
  2. According to Euler’s formula, find φ(n)=?=(p?1)(q?1).
  3. Choose any integer e, 1
  4. Choose any integer d, its value is the public key, it must satisfy gcd(d,φ(n))=1, and calculate de mod φ(n)=e.
  5. Publish the four parameters p, q, e, and d, and anyone who receives the public key can use them for encryption and decryption.

3.2 Encryption process of e-commerce payment

Suppose a bank wants to establish an e-commerce payment channel with a merchant and requires the merchant to provide a bank account number. The bank’s workflow is as follows:

  1. The merchant provides the bank with personal information such as merchant number, name, ID number, etc., and requires the bank to provide the public key.
  2. The bank creates an initial key pair based on the information provided by the merchant. The initial key pair contains a private key and another public key.
  3. The bank sends the public key to the merchant and requires the merchant to encrypt the order information with the private key.
  4. When the user pays successfully, the merchant sends the payment voucher and order information to the bank and requires the bank to use the private key to decrypt the payment voucher and order information.
  5. If the payment voucher and order information are successfully decrypted, the payment is successful and the bank will increase the corresponding balance.

3.3 Issuance of Digital Currency

Digital currency is a virtual cash system built using encryption technology. Let’s say a company wants to issue a new digital currency and wants support from the community. The company can take the following actions:

  1. The issuer generates a key pair (public key and private key), and the public key is published on the network.
  2. When a user purchases digital currency, a request is sent to the network to view available public keys.
  3. The buyer provides payment address, digital currency amount, private key signature, recipient address and other information, selects the payment method, and submits a payment request to the payment platform.
  4. The payment platform receives the payment request and checks whether the order information is complete.
  5. The payment platform obtains the private key corresponding to the payment address, uses this private key to encrypt the payment amount, and submits it to the network.
  6. After receiving the payment information, multiple nodes in the network generate a transaction record and record the transaction amount.
  7. If the payment amount is successfully decrypted, it means the payment is successful and the transaction information is recorded in the blockchain.
  8. When other users query transaction information, they can view the blockchain to verify the accuracy of the transaction information.

4. Specific code examples and explanations

4.1 Python sample code: generate RSA key pair and encrypt/decrypt information

import random

def generate_rsa_keys():
    p = int(''.join([str(random.randint(0, 9)) for i in range(10)]))
    q = int(''.join([str(random.randint(0, 9)) for i in range(10)]))

    n=p*q
    phi = (p - 1) * (q - 1)

    eulers_totient = phi
    gcd = lambda a, b: a if not b else gcd(b, a % b)
    while True:
        d = random.randint(1, eulers_totient)
        if gcd(d, eulers_totient) == 1:
            break

    public_key = [n, e]
    private_key = [n, d]

    return public_key, private_key


public_key, private_key = generate_rsa_keys()
print("Public key:", public_key)
print("Private key:", private_key)


message = "hello world"
encrypted_msg = rsa_encrypt(message, public_key)
print("Encrypted message:", encrypted_msg)

decrypted_msg = rsa_decrypt(encrypted_msg, private_key)
print("Decrypted message:", decrypted_msg)

4.2 Java sample code: Implementation of Hashcash algorithm

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Random;

public class Hashcash {
    // Message to be protected with hashcash scheme
    static String message = "Hello World";

    public static boolean isValidProofOfWork(String nonce, long difficultyBits) throws Exception{

        StringBuilder sb = new StringBuilder();
        sb.append(message).append(nonce);

        byte[] inputBytes = sb.toString().getBytes();

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashedBytes = digest.digest(inputBytes);

        BigInteger hashedIntValue = new BigInteger(1, hashedBytes);

        BigInteger targetValue = getTargetValue(difficultyBits);

        System.out.println("Hashed Int Value : " + hashedIntValue.toString());
        System.out.println("Target Value : " + targetValue.toString());

        return hashedIntValue.compareTo(targetValue) <= 0;

    }

    public static BigInteger getTargetValue(long difficultyBits){

        Random rand = new Random();
        byte[] bytes = new byte[2];
        rand.nextBytes(bytes);
        int randomNumber = ByteBuffer.wrap(bytes).getInt();
        System.out.println("Random Number : " + randomNumber);

        double baseDifficulty = Math.pow(2, difficultyBits);
        BigInteger targetValue = new BigInteger(baseDifficulty + "" + randomNumber);

        return targetValue;


    }

    public static void main(String[] args) throws Exception {

        String proofOfWork = createNonce();
        printProofofWorkInfo(proofOfWork);

        boolean valid = isValidProofOfWork(proofOfWork, 20);

        if(valid){
            System.out.println("Valid Proof Of Work!");
        }else{
            System.out.println("Invalid Proof Of Work!");
        }

    }

    public static String createNonce(){

        Random rand = new Random();
        byte[] bytes = new byte[5]; // length is arbitrary
        rand.nextBytes(bytes);
        String nonce = BaseEncoding.base16().encode(bytes);

        return nonce;
    }

    public static void printProofofWorkInfo(String nonce){

        System.out.println("------------------Proof Of Work-------------------\
" +
                "\tMessage : " + message + "\
" +
                "\tNonce : " + nonce + "\
" +
                "\tDifficulty Bits: 20 bits");

    }

}

In recent years, digital currency has become an important means of payment and has become a mainstay in many fields. With the vigorous development of blockchain platforms such as Bitcoin and Ethereum, some traditional industries have also begun to pay attention to the application of digital currencies. For example, in the real estate field, many developers are exploring how blockchain technology can affect the real estate market. In the field of healthcare, many large hospitals have begun to adopt blockchain technology to manage doctor-patient relationships. In the consumer field, some companies have also begun to use blockchain technology to conduct payment and other services.

However, there are still some obstacles to the development of digital currencies. For example, the development of blockchain relies too much on centralized servers, which is not conducive to the protection and competition of the ecological environment. At the same time, different countries have uncertainties regarding financial regulatory policies, tax policies, payment channels, etc., which can easily lead to backlash. In addition, the value fluctuation of blockchain may cause social dissatisfaction and make politicians uneasy.

Therefore, digital currency technology still needs to continue to develop, and it needs to be combined with traditional financial technology to penetrate into more fields so that blockchain technology can better serve society.