KEMBAR78
Introduction To Cryptography | PDF | Key (Cryptography) | Cryptography
0% found this document useful (0 votes)
26 views34 pages

Introduction To Cryptography

The document provides an overview of cryptography, its historical development, and its significance in blockchain technology. It discusses the two main types of cryptographic systems: private key (symmetric) and public key (asymmetric) cryptography, detailing their mechanisms, advantages, and challenges. Additionally, it touches on the emerging field of quantum cryptography and its potential to enhance security in information transmission.

Uploaded by

Mahan Ziyari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views34 pages

Introduction To Cryptography

The document provides an overview of cryptography, its historical development, and its significance in blockchain technology. It discusses the two main types of cryptographic systems: private key (symmetric) and public key (asymmetric) cryptography, detailing their mechanisms, advantages, and challenges. Additionally, it touches on the emerging field of quantum cryptography and its potential to enhance security in information transmission.

Uploaded by

Mahan Ziyari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction to Cryptography

in Blockchain

Javier Bermejo Higuera, Juan Ramón Bermejo Higuer,


Juan Antonio Sicilia Montalvo, and Rubén González Crespo

1 What is Cryptography?

Since ancient times, there has been a need to protect information considered confi-
dential or secret, with the aim of keeping it out of the reach of a possible enemy
or adversary. This has been done in various ways: by preventing physical access to
it, by disguising its nature, or by using cryptographic procedures to transform it to
prevent access to its content. The aim of cryptography is not to hide the existence of
a message, but rather to hide its meaning, a process known as encryption.
Against the use of cryptographic procedures and methods, the opposite side will
use cryptanalysis procedures. Cryptanalysis consists of compromising the security
of a cryptosystem. This can be done by decrypting a message without knowing the
key, or by obtaining from one or more cryptograms the key that has been used in its
encryption.
The discovery of a secret encryption algorithm is not considered cryptanalysis;
instead, we must assume that algorithms are always known. In general, cryptanal-
ysis is usually carried out by studying large numbers of message-cryptogram pairs
generated with the same key. The mechanism used to obtain them is indifferent and
can be the result of listening to a communications channel, or the possibility that
the object of our attack responds with a cryptogram when a message is sent to it.

J. Bermejo Higuera · J. R. Bermejo Higuer · J. A. Sicilia Montalvo (B) · R. González Crespo


Escuela Superior de Ingeniería y Tecnología, Universidad Internacional de La Rioja, Avda. de La
Paz 137, 26006 Logroño, La Rioja, Spain
e-mail: juanantonio.sicilia@unir.net
J. Bermejo Higuera
e-mail: javier.bermejo@unir.net
J. R. Bermejo Higuer
e-mail: juanramon.bermejo@unir.net
R. González Crespo
e-mail: ruben.gonzalez@unir.net

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2022 1
B. S. Rawal et al. (eds.), Implementing and Leveraging Blockchain Programming,
Blockchain Technologies, https://doi.org/10.1007/978-981-16-3412-3_1
2 J. Bermejo Higuera et al.

Obviously, the greater the number of pairs, the more likely the cryptanalysis will be
successful.
Cryptography has been used since ancient times, David Kahn, “The Codebreak-
ers” [1], states that the origins of cryptography date back to around 1900 BC. In
the fifth century BC, the Macedonians, an ancient Greek people, used the “escítala”
method to encrypt their messages. This period from time immemorial to the middle
of the twentieth century is called “classical cryptography”. The adjective clas-
sical, as opposed to modern, is due both to the techniques used, basically character
substitution and transposition operations, with or without a key but always linked to
the concept of a secret key, and to the use of symmetric cryptography in machines
dedicated to encryption.
The figure below summarizes some of the major cryptographic milestones in
chronological order.
From Fig. 1, the following significant events mark a turning point in the world of
cryptography:
• In 1883, a fundamental work appeared: Cryptographie Militaire, by Kerckhoffs,
[2] in which the author formulated a series of principles that would become the
basis of today’s cipher. One of them, the best known, determines that all the
strength of the cipher must rest on the secrecy of the key, so that knowledge of
the encryption procedure does not give any advantage when attacking the cryptos.
This means that the procedures can be public and can therefore be commercialised,
being shared by different users who will keep their respective keys secret in order

• The Macedonians, an ancient Greek people, used the "escítala" method to encrypt their messages.
V a.c.

• Appearance of the so-called Julius Caesar alphabet or procedure.


III a.c.

• Arabs begin to develop and use the first secret codes and dic onarie.
XI

• The grid procedures, then known as la ces, were developed by Jerónimo Cardano.
XVI

• Use of a table of displaced alphabets, devised by Blaise de Vigenère and published in 1586.
XVI

• Thomas Jefferson, president of the United States of America, used a device to encrypt his correspondence. It is known today as the
XVIII Jefferson wheel

• Fundamental work: Cryptographie Militaire, by Auguste Kerckhoffs, where the author formulates a series of principles that will be the
XIX basis of today's cipher.

• 1917 Vernan encryp on


XX • 1920. Appearance of the ENIGMA encryp on machine

• 1948 Claude E. Shannon publishes his theory of perfect secrecy


XX

• 1975 Diffie and Hellman establish the theore cal founda ons of public key algorithms.
XX

Fig. 1 Major cryptographic milestones


Introduction to Cryptography in Blockchain 3

to maintain security. Furthermore, the fact of publishing the procedures means


that they are subjected to theoretical studies by the scientific community and their
weaknesses are eventually published.
• The studies carried out by Shannon on the theory of information and cryptology
[3]. From that moment on, cryptology ceased to be considered as a mere art. He
established the principles of symmetric encryption, which is a cipher that uses
the same key k for both encryption and decryption. It has the disadvantage that to
be used in communications, the key k must be possessed by both the sender and
the receiver. This requires the secure transmission of the key.
• The third event is the publication of a paper by Diffie and Hellman [4] in which
they propose a new method of asymmetric encryption, creating public-key
cryptosystems.
In the second half of the nineteenth century, with the development of computer
science and the increasingly widespread use of computer networks and mass storage
of information, a great step in the study of cryptographic systems took place.
“Modern cryptography” began, in which systems made use of certain mathematical
properties such as, for example, the difficulty of calculating the discrete logarithm
or the problem of factoring large numbers, together with the binary representation
of information.
However, many modern systems that are still in use today are based on concepts
that could be considered a classic, such as transposition and substitution with a
private key, although in these systems the operation is carried out on a string of
bits and not on characters. It can be divided into two large blocks according to the
relationship between the encryption and decryption keys: private key cryptography
and public-key cryptography.
Currently under development, although the technology is not yet mature,
“quantum cryptography” [5], which uses principles of quantum mechanics to guar-
antee absolute confidentiality of transmitted information. Current quantum cryptog-
raphy techniques allow two people to securely create a unique property of quantum
physics to encrypt and decrypt the message.
One of the most important properties of quantum cryptography is that if a third
party attempts to eavesdrop during the creation of the secret key, the process is
altered. This is a consequence of the Heisenberg uncertainty principle, which tells
that the process of measuring in a quantum system disturbs that system. The security
of quantum cryptography is based on the foundations of quantum mechanics, unlike
traditional public-key cryptography which is based on assumptions of the unproven
computational complexity of certain mathematical functions.
Quantum cryptography is nearing a mass production stage, using lasers to emit
information in the constituent elements of light, the photon, and conducting this
information through optical fibres.
To conclude, modern cryptographic systems require sufficient mathematical
foundations to provide utilities to measure and quantify their resistance to
eventual attacks and, why not, to find the “Holy Grail” of cryptography: the
unconditionally secure system.
4 J. Bermejo Higuera et al.

2 Types of Encryption and Decryption Algorithms

As indicated in the previous paragraph, modern cryptography is divided into two


large blocks according to the relationship between the encryption and decryption
key:
• Private key cryptography (cryptosystem or symmetric algorithms).
• Public-key cryptography (cryptosystem or asymmetric algorithms).
A symmetric (secret key) cryptosystem is one where both sender and receiver
share the same key. The exchange of keys is one of the main challenges of this type
of system, as the sender and receiver share the same key, which must be “exchanged”
in some secure way: the dilemma, therefore, arises of how to exchange these keys
securely (Fig. 2).
An asymmetric (public key) cryptosystem is one where the sender and receiver
have different keys for encryption and decryption. One use of this type of system is
the ‘secure’ exchange of private keys (Fig. 3).
Secret key cryptography, also known as symmetric-key cryptography, is that
which uses the same key k for both encryption and decryption. It has the disadvantage
that, in order to be used in communications, the key k must be possessed by both
the sender and the receiver, for which it is necessary that the key can be transmitted
securely. A secret key encryption system is said to be secure if no known attack of
lower complexity than the exhaustive search over the keyspace yields better results
than it. Security depends on the sender and the receiver. There are two operations
for encryption transposition and substitution distinguishing two types of secret key
or symmetric encryption block cipher and stream cipher.
• Block ciphers. This type of cryptosystem divides the message to be encrypted
into several fragments, usually of fixed length, and applies a cryptographic trans-
formation to each fragment. Most of these algorithms are based on the concepts of
confusion and diffusion initially proposed by Shannon, which are used to cancel
out the redundancy of the source A good confusion mechanism will make it too

Fig. 2 Secret key cryptosystem


Introduction to Cryptography in Blockchain 5

Fig. 3 Criptosistema de clave pública

complicated to extract statistical relationships between the plaintext, the cipher-


text and the key. Diffusion, on the other hand, tries to spread the influence of each
bit of the original message over the cipher message as much as possible. What is
actually done to achieve strong algorithms, without the need to store huge tables,
is to interleave confusion, which involves simple substitutions with small tables,
with diffusion, which involves permutations. This combination is known as a
product cipher. Most algorithms are based on different layers of substitutions and
permutations, called a Substitution-Permutation Network.
• Stream ciphers. This type of cryptosystem divides the information to be
encrypted into characters, and then encrypt each character by applying a time-
varying function whose time dependence is governed by the variables defining
the state of the system. Thus, after the encryption of each character, the system
evolves to a new state according to a certain rule. As a result, identical characters
usually have different ciphers, which helps to increase the security of the system
(Fig. 4).
The most commonly used block cipher algorithms for the encryption process
include the following:
• DES (Data Encryption Standard): This is a 64-bit block cipher algorithm. It
was developed by IBM and accepted by NIST (National Institute of Standards
and Technology) in 1976. It is a 64-bit key algorithm of which 56 bits make up
the encryption key itself, while the remaining 8 bits are for parity and are used
for error correction.
• Triple-DES (Triple-Data Encryption Standard): Given the current computing
power and the relative ease of breaking the DES algorithm, TRIPLE DES was
developed. It consists of applying the DES algorithm three times in a specific
order. First, the data is encrypted with one key, the result of this is decrypted with
6 J. Bermejo Higuera et al.

Fig. 4 Classification of
cryptosystems
Current crypto
systems

Secret key Public key


cryptosystems cryptosystems

Stream ciphers Block ciphers


DIFFIE-HELLMAN
RSA
EL GAMAL

LFSR
NLFSR IDEA
FILTRADO NO DES
LINEAL TDES
COMBINACIÓN AES
NO LINEAL

another key and finally, the decryption result is encrypted again. The key used in
this last step can be the first key used or it can be a new key.
• AES (Advanced Encryption Algorithm): also known as Rijndael, is a block cipher
scheme adopted as an encryption standard for the US government. It is currently
one of the most popular algorithms used in symmetric cryptography.
• IDEA (International Data Encryption Algorithm): was created by Xuejia Lai
and James Massey in 1990. It is a block cipher, operating on 64-bit messages with
a 128-bit key. It consists of eight identical transformations (each called a round)
and one output transformation (called a half-round). Much of IDEA’s security
derives from the interleaving of three operations: Bit-by-bit exclusive OR (XOR)
operation, modulo 216 addition and modulo 216 + 1 multiplication.
The asymmetric cryptography, as discussed in previous paragraphs, was created
by Diffie and Hellman [4] in 1976, changing the paradigm of cryptography forever.
In essence, it consists of the following [6]:
• Each participant generates, following a public-key algorithm, a pair of related
keys. One is the so-called public key and the other is the so-called private key
of the participant. Deducing the private one, knowing the public one, must be
computationally very complicated.
• The public key is really public, everybody can know it.
Introduction to Cryptography in Blockchain 7

• The private key is really private, secret, only each participant knows his own
private key.
• Anyone who knows participant A’s public key can encrypt a message with it, but
only participant A can decrypt that message, using his private key.
Mathematically the algorithm is based on one-way functions with a dummy door.
Encryption is the easy part of the process. Decryption is the more complicated part,
without the private key it is practically impossible. The basic idea is to use a function
that is easy to calculate in one direction and very difficult in the other, such as integer
factorisation. Given two prime numbers, it is easy to multiply them and get their
product, but, given a single product, it may be impossible, from a practical point of
view, to factor the number and recover the two factors. This type of function involves
the use of modular arithmetic, exponentiation, and the use of large prime numbers
(of lengths of thousands of bits).
It is particularly remarkable how this type of method solves the key management
problem of symmetric cryptography. In that case, a key had to be secretly agreed
upon. In this case, anyone can obtain the public key, and only one participant must
know the private key. A typical way of using these methods for a network of users is
as follows:
1. Agreeing on a public cryptography system.
2. Creation of key pairs for each user.
3. All public keys are stored in a database accessible to all users.
4. When participant A wants to send a message to participant B, he obtains B’s
public key from the database.
5. Participant A encrypts his message using B’s public key and sends it to B.
6. Participant B receives the message and decrypts it using his private key.
The strengths of public-key cryptographic systems include the following:
• They provide authentication and non-repudiation for many cryptographic proto-
cols.
• They are also often used in a hybrid system, in collaboration with any of the other
cryptographic methods.
• They allow for easy key management, as they do not require a secure key exchange.
Weaknesses include the following:
• They are slower algorithms than secret key algorithms and are therefore not
typically used for encrypting large amounts of data.
• Their implementations are commonly done in software systems.
• For a large network, they require a system to certify the authenticity of the public
keys.
Asymmetric algorithms use longer key lengths than symmetric algorithms. While
in the latter a 256-bit key is considered quite secure, in asymmetric algorithms,
except for those based on elliptic curves, keys of at least 2048 bits are recommended
8 J. Bermejo Higuera et al.

nowadays. Among the most commonly used public-key methods in cryptographic


protocols and applications, the following can be highlighted:
• DIFFIE–HELLMAN [7]. It is an asymmetric algorithm, based on the Diffie–
Hellman problem, which is mainly used to agree on a common key between two
interlocutors, through an insecure communication channel.
• RSA [8]. It owes its name to its three inventors: Ronald Rivest, Adi Shamir and
Leonard Adleman. Subject to multiple controversies, since its birth, no one has
been able to prove or disprove its security, but it is considered one of the most
secure asymmetric algorithms.
• GAMAL [9]. It was originally designed to produce digital signatures, but was
later extended to encrypt messages. It is based on the discrete logarithm problem,
which is closely related to the factorisation problem, and the Diffie–Hellman
problem.
• DSA (Digital Signature Algorithm) [10]. It is a part of the DSS (Digital Signa-
ture Standard). This algorithm, proposed by NIST in 1991, is a variant of the
asymmetric El Gamal method.

3 Secure Hash Algorithms

One of the basic operations used in blockchain transactions is the execution of a


digest function of a few hundred bits of a message. Hash or Message Digest functions
perform a transformation of a message of arbitrary length into a message of constant
length by dividing the message into equal parts, applying a transformation function
to each part, and summing all the results obtained.

R = h(M)

They are called “one-way”, due to the one-way mathematical property that they
possess, where given a digest R, it is very difficult or nearly impossible to calculate
its associated message M (Fig. 5).

Fig. 5 Hash function


Introduction to Cryptography in Blockchain 9

In order to be applicable to the digital signature or other applications, hash


functions must fulfil a number of properties [11]:
• Unidirectionality. It must be computationally impossible to find M from a known
digest h(M).
• Compression. The digest h(M) must have a fixed length, whatever the length of
the message. Typically, the length of h(M) is smaller than the message M.
• Ease of calculation. It must be easy to compute h(M) from a message M.
• Diffusion. The digest h(M) must be a complex function of all the bits of the
message M: if a single bit of the message M is changed, the hash h(M) should
change about half of its bits.
• Collision. It will be computationally impossible to find another M such that h(M)
= h(M  ). This is known as collision resistance.
In this sense, to minimise the existence of collisions it is recommended to use
a digest of at least 128 bits, being 160 bits the most used value, since in principle
the probability of collision will be given by 1/2n (n = number of bits of the digest),
which implies that to find two messages having the same digest with a probability
greater than 50%, it would mean that the search space would be (1/2n)/2, which
reduces the complexity.
Most of the algorithms that implement a hash function are implemented based on
iterative processes of fixed-size blocks, obtained from a previous process of format-
ting the input to be a multiple of the size of these blocks. Figure 6 shows a generalised
Hash function model [12].
The general algorithm of the hash function presented in the figure accepts as input
a file or message m = x of finite and arbitrary length, which is divided into blocks of r
bits of fixed length x i . It then applies a pre-processing that involves adding additional
bits (padding) necessary to reach a length multiple of the length of the processing
block r. Each block x i obtained serves as input to an iterative compression function h
that internally implements an internal non-linear function f , which computes a new
intermediate partial result of fixed length n hi corresponding to stage i, the general
form model is

Hi = f (Hi−1 , xi), 1 ≤ i ≤ t, h(x) = g(Ht )

H i−1 serves as the n-bit chaining variable between stage i−1 and stage i, and
H 0 is a predefined initial value or initialisation value. The stage optionally uses a
transformation g, to map the n-bit chaining variable to an m-bit result g(H t ), which
is often the identity mapping g(H t ) = H t . The different algorithms implementing
particular hash functions are distinguished by the nature of the pre-processing,
the compression function and the output transform.
Los algoritmos disponibles en la actualidad para la realización de este tipo de
funciones tipo resumen son los siguientes:
• MD5 (Message-Digest Algorithm 5). Developed by Ron Rivest in 1992, it is an
improved evolution of the MD4 and MD2 algorithms, its main features are:
10 J. Bermejo Higuera et al.

Fig. 6 General hash


function algorithm [12]

• 128-bit digest length.


• Use for hashing user keys on UNIX and Linux systems.
• Widespread use on the Internet to verify the integrity of downloaded binary
files.
• Classification and identification of malware binaries.
• Methods have been discovered to generate collision.
• SHA (Secure Hash Algorithm). A set of cryptographic hash functions designed
by the US government’s National Security Agency (NSA) and published by the
National Institute of Standards and Technology (NIST). The components of this
family of published functions are:
• SHA-0. In 1998 an attack was found.
• SHA-1. Similar to MD5 but with a 160-bit digest.
Introduction to Cryptography in Blockchain 11

Table 1 Function maximum


Function Maximum length (bits)
length
MD2 128
MD4 128
MD5 128
WHIRLPOOL 512
SHA- 160
SHA-224 224
SHA-256 256
SHA-384 384
SHA-512 512
RIPEMD-128 128
RIPEMD-160 160
N-HASH 128
HAVAL 256

• SHA-2. There are four variants whose differences are based on a somewhat
modified design and increased output ranges: SHA-224, SHA-256, SHA-384,
and SHA-512.
• SHA-3 (Secure Hash Algorithm 3) is the latest member of the Secure
Hash Algorithm family of standards, published by NIST on 5 August 2015.
According to NIST, this new algorithm is not intended to replace the current
SHA-2, which has not yet demonstrated any vulnerabilities.
• RIPEMD (RACE Integrity Primitives Evaluation Message Digest). 160-bit
message digest function, developed in Europe and published in 1996. It is based
on the design principles of the MD4 algorithm and is similar in security and
performance to the more popular SHA-1.
• WHIRLPOOL. Hash function designed by Vincent Rijmen and Paulo S. L. M.
Barreto, based on a modification of the Advanced Encryption Standard (AES)
algorithm, which returns a 512-bit hash of an input message of size less than 2256
bits. It has been adopted by the International Organisation for Standardisation
(ISO) and the International Electrotechnical Commission (IEC) as part of the
international standard ISO/IEC 10118-3.
• N-Hash (Nippon Telephone and Telegraph). It is a hash function built by
Miyaguchi in 1990, based on the FEAL function. It is now considered insecure,
as its weaknesses were published a year later. It has a hash size of 128 bits.
• Haval. It is a hash function built by Miyaguchi in 1990, based on the FEAL
function. It is now considered insecure, as its weaknesses were published a year
later.
Table 1 shows the different functions treated and the maximum length of each of
them.
12 J. Bermejo Higuera et al.

4 Cryptography in Blockchain

Normally, all the information shared in Blockchain is transmitted through insecure


networks, such as the Internet, passing through innumerable processing machines,
without following any kind of order or hierarchy. Therefore, cryptography and its
different algorithms is a fundamental technology in Blockchain, as it allows the confi-
dentiality, integrity, authentication and non-repudiation of the information processed
and stored by the network nodes and transmitted in transactions to be safeguarded.
Blockchain makes use of cryptography in different ways by implementing a
number of cryptographic services including non-repudiation, origin authentication
and data integrity. The algorithms and cryptosystems most commonly used by these
services in blockchain are the following:
• Hash functions.
• Public-key cryptography. The most commonly used public-key algorithms in
blockchain are Rivest–Shamir–Adleman (RSA) and Elliptic Curve Cryptography
(ECC) although mainly the latter [13].
• Digital Signature. It is a fundamental part of Blockchain as each block contains a
set of representative transactions to spend funds or interact with smart contracts.
Each transaction consists of two parts, a digital signature on the previous trans-
mission and a public key of the new owner to whom the right/value is intended to
be transferred. The most commonly used algorithm is the Elliptic Curve Digital
Signature Algorithm (ECDSA).

4.1 Secure Hash Algorithm

The SHA algorithm is the most widely used cryptographic algorithm in the
Blockchain architecture, namely, it is mainly used for address creation, for ensuring
data integrity, data encryption, consensus computing and for linking blocks together.
Of all of them the most used in the different parts in the blockchain is SHA-256 [13]
for its trade-off between security and computational cost of generation, as it is a very
efficient algorithm for the high collision resistance it has:
• To ensure the integrity of the registers included in the blocks and to maintain the
chaining of the transactions contained in the blocks,
• In the Proof-of-Work (PoW) algorithm.
• To obtain secure public addresses, starting from the generated ECDSA public
key. The address is obtained from the public key through the use of one-way
cryptographic hashing. The algorithms used to create addresses are SHA256 and
RIPEMD160. From the public key K, the SHA256 hash and then the RIPEMD160
hash of the result is calculated, producing a number of 160 bits (20 bytes): where
K is the public key and A is the resulting address.
Introduction to Cryptography in Blockchain 13

4.2 Public-Key Cryptography

Elliptic curve cryptography (ECC) [14] is a variant of asymmetric or public-key


cryptography based on elliptic curves. Its authors argue that ECC can be faster and
use shorter keys than older methods, such as RSA, while providing an equivalent level
of security. The use of elliptic curves in cryptography was independently proposed
by Neal Koblitz and Victor Miller in 1985.
As you know, asymmetric or public-key cryptography systems use two different
keys: one of them can be public and the other is private. Possession of the public key
does not provide sufficient information to determine which is the private key. This
type of system is based on the difficulty of finding the solution to certain mathematical
problems. One such problem is the so-called discrete logarithm. Finding the value
of b given the equation:

ab = c

where a and c are known values, it can be an exponential complexity problem for
certain large finite groups; while the inverse problem, discrete exponentiation, can
be efficiently evaluated using for example binary exponentiation. An elliptic curve
is a plane curve defined by an equation of the form:

y 2 = x 3 + ax + b

With the set of points G forming the curve (i.e. all the solutions of the equation
plus a point O, called point at infinity) plus an additive operation + , an abelian group
is formed. If the coordinates x and y are chosen from a finite body, then we are in the
presence of a finite abelian group. The Discrete Logarithm Problem (PLDCE) on this
set of points is believed to be more difficult to solve than the one for finite bodies.
Thus, key lengths in elliptic curve cryptography can be shorter with a comparable
level of security. An elliptic curve over a body K is the plane curve given by the
following equation:

y 2 + a1 x y + a3 y = x 3 + a4 x + a6 ; ai ∈ K

The elliptic curve of equation y 2 = x 3 − 7x + 1 over R is shown in Fig. 7.


If the body is finite, Kq, with q = pm elements, the point at infinity, O, is included.
The curve E(K 7 ): y2 = x 3 + 2x + 4 over the 7-element body, K 7 = Z 7 = {0; 1; 2;
3; 4; 5; 6}, has the following points: (Note that given a point on the curve (x, y), the
value (x, −y) (mod n) also belongs to it.

E(F7 ) = {O; (0; 2); (0; 5); (1; 0); (2; 3); (2; 4); (3; 3); (3; 4); (6; 1); (6; 6)}

Graphically, the sum of two points of an elliptic curve over an arbitrary body can
be interpreted as P + Q = R which is the intersection point of the curve with the
14 J. Bermejo Higuera et al.

Fig. 7 Elliptic curve of the


function y 2 = x 3 − 7x + 1

line passing through R and the point of infinity, i.e. the line passing through R and
parallel to the ordinate axis. This operation, called elliptic sum, gives the set E(K 7 )
the structure of an abelian group with neutral the point at infinity of the curve.
The points of a well-chosen elliptic curve over K, together with O, with the sum
of points are a finite abelian cyclic group. Consider the curve y2 = x3 + ax + b
mod(p) on a body of characteristic other than 2 and be P = (x 1 ; y1 ) y Q = (x 2 ; y2 )
two affine points. It is defined as

x 3 = λ2 − x 1 − x 2

y3 = λ(x1 − x3 ) − y1

And

⎨ y2− y1
, si P = Q
x2 −x1
λ=
⎩ 3x12 +a
, si P =Q
2y1

In the example, E(K 7 ):y 2 = x 3 + 2x + 4, for P(0; 2) and Q(1; 0) as they are
distinct points.

λ = (y_(2−) y_1)/(x_2 − x_1 ) = (0 − 2)/(1 − 0) = −2 mod (7) = 2

With this value of λ, it is calculated x 3

x3 = 32 − 0 − 1 = 9 − 1 = 8 mod (7) = 1

With this calculated value, λ, x1 and y1 it is calculated y3


Introduction to Cryptography in Blockchain 15

Fig. 8 Curva elíptica de la


función y 2 = x 3 − 7x + 1

y3 = 3 ∗ (0 − 3) − 2 = −9 − 2 = −11 mod (7) = 4

So the result of the sum of P + Q = R(3, 4).


Its use as a public-key cryptographic system would be by choosing a specific base
point G from the curve E(K). A random integer k is chosen as the private key, and
then the value P = k*G is made known as the public key (note that the supposed
difficulty of the PLDCE problem implies that k is difficult to deduce from P) (Fig. 8).

4.3 Digital Signature

The origin of the electronic signature arose from the need for a secure technical
response to the need to formalise the agreements reached in electronic transactions (e-
commerce, administrative procedures, etc.), in a similar way to that of the handwritten
signature in terms of giving assent and commitment to the signed document and with
even stronger conditions than the handwritten signature.
The digital signature can be defined as the set of data or electronic files associated
with the original document to protect its integrity and forgery, which uniquely iden-
tifies the signatory of the document and does not allow the possibility of denial of its
generation. It contains information about the original document, the signatory, the
date of signature, algorithms used and signature expiry. It is an information packet
of fixed size, dependent on the original document and can only be generated by the
holder of the signatory’s private key (Fig. 9).
The use of digital signatures provides the following security properties: informa-
tion integrity, authentication, non-repudiation, non-copyability and traceability.
16 J. Bermejo Higuera et al.

Fig. 9 Firma digital

Due to the problems or disadvantages of digital signatures with secret-key cryp-


tography, the digital signature is implemented with a public key. A digital signature
is usually composed by encrypting with the secret Key a digital digest of the original
message, obtained by hash functions, e.g. SHA.
To verify a signature, the receiver decrypts the signature with the sender’s public
key, compresses the original text received with the hash function and compares the
result of the decrypted part with the compressed part; if both matches, the sender
has a guarantee that the text has not been modified. As the sender uses his secret
key to encrypt the compressed part of the message, it can be proven to a third party
that the signature could only have been generated by the user who stores the secret
component.
Generally, the digital signature is implemented by means of a hash function,
which is responsible for obtaining a unique digest of the original message. The basic
procedure for its generation is as follows (Fig. 10 depicts this process):
1. Sender generates a digest of the message r(m).
2. Sender encrypts the digest r(m) with its private key.
3. Sender sends the cryptogram.
4. Receiver decrypts the signature using user A’s public key and then retrieves
the hash value. If the signature can be decrypted, user B knows that the data
originates from user A (or the owner of the private key).
5. Receiver applies the hash algorithm to the data to create a second hash value.
6. Receiver compares its hash value with the received hash value and if they match,
the message is authentic.
Currently, the most widely used and widespread digital signature algorithms are
the following:
Introduction to Cryptography in Blockchain 17

Fig. 10 Digital signature

• RSA. Designed by CCITT within the design of the authentication system for the
X.500 Directory.
• El Gamal. Developed by Taher ElGamal in 1984.
• DSS (Digital Signature Standard) used by the NIST) known as DSA.
The digital signature used in Blockchain is the Elliptic Curve Digital Signature
Algorithm (ECDSA), which is an evolution of the DSA public-key algorithm, whose
operation is based on solving the difficulty of factoring large numbers by using
properties of elliptic curves.
The algorithm uses operations on points of elliptic curves instead of exponentia-
tions like DSA. The public and private keys are calculated from a number obtained as
a product of two large prime numbers and are smaller. It is important to generate the
private key randomly, given the security problems detected in some implementations.
This algorithm being a cryptosystem based on elliptic curves using shorter keys
with a security level equivalent to RSA and an efficient implementation. It is used
to:
• Generate the key pairs of the wallets involved in a Blockchain-type monetary
system and,
• Conduct cryptocurrency transactions securely and anonymously.
18 J. Bermejo Higuera et al.

• The public key of a wallet would be used to identify it, and the private key would
be used to sign a transaction.
• Maximum length of the hash function.

5 How to Implement Cryptography Using Java

The Java Cryptographic Architecture (JCA), as it aims to be flexible with respect to


implementations, introduces the concept of cryptographic providers, to refer to the
packages or libraries used in the development of a Java application. The first default
provider that comes with the language is called SUN. This provider, among others,
includes an implementation of the DSA standard signature algorithm, MD5 and
SHA-1 digest algorithm, SHA1PRNG pseudo-random number generator, certificate
creation and revocation lists, as well as certificate utilities with PKIX, conforming
to the X.509 standard, a keystore called JKS. Another provider that incorporates by
default the language is SunJCE, which already exists in other previous versions and
will give us DES, AES, TripleDES, RSA encryption, among others.
One or more default cryptographic providers can be used or third-party providers
can be used. The BouncyCastle provider, among others, also includes implemen-
tations of AES, ASN.1 (a standard format), Base64 (an encryption), certificates
and CRLs (revocation list), DES, tripleDES (also called DESede), DHKey, DSA,
ElGamal, Hex (hexadecimal data utilities), IDEA, PKCS (standards), PKI utilities.
Java cryptographic providers. To know the providers that the JDK distribution
comes with, it must use the javax.security package, in such a way that the Security
class will provide us with an array of providers:
Provider[] proveedoresCriptograficos = Security.getProviders();

The name of the provider is obtained with the getName method and if more
information is needed, such as the algorithms implemented by that provider it can
use the getInfo() method:
proveedoresCriptograficos[i].getName();
proveedoresCriptograficos[i].getInfo();

In this way, it is possible to verify that the JDK comes with several providers
and that they also have a certain order. This order is the one that prevails in case we
make reference to an algorithm that is implemented in two different cryptographic
providers. The symmetric encryption algorithms will be provided by a provider called
“SunJCE”, while the rest of the providers will give us algorithms that we will study
in the following topics of the course. Finally, we can comment that regardless of
the provider we can know which algorithms are provided by the platform, since this
information is collected by the Security class:
Security.getAlgorithms("Cipher");

JCA offers an API (application programming interface) that allows:


Introduction to Cryptography in Blockchain 19

• Key generation (secret keys and public/private key pairs).


• Symmetric encryption (DES, 3DES, IDEA, etc.).
• Asymmetric encryption (RSA, DSA, Diffie-Hellman, ElGamal…).
• Digest functions (MD5 and SHA1) and MAC algorithms (Message Authentication
Code).
• Signature generation and validation.
key agreement.
To use the JCA API classes and methods, applications must import, at a minimum,
the following packages:
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.interfaces.*;
import javax.crypto.spec.*;

5.1 Symmetric Encryption

The use of symmetric (and also asymmetric) ciphers is done through instances that
inherit from the class Cypher.

5.1.1 Creation of Instances

An instance is created by a factory method (not with new()). The provider will
create the specific object using its implementation of the corresponding algorithm.
A specification of the encryption scheme to be used must be indicated.
• As a minimum, this specification shall include the name (alias) of the encryption
algorithm.
• In cases where it is necessary (typically with block ciphers), it will also include the
specification of the operating mode (ECB, CBC, …) and the padding algorithm.
• The provider to be used is added.
• Security.addProvider (new BouncyCastleProvider()); // Cargar el provider BC
Optionally, the name of the provider can be specified to select the specific
implementation to be used:
static Cipher getInstance(String transformation)
static Cipher getInstance(String transformation, String provider)
20 J. Bermejo Higuera et al.

5.1.2 Creation of the Key

Keys are managed by objects that implement the SecretKey interface (which in turn
inherits from the Key interface). Keys are created using a KeyGenerator object.
1. The KeyGenerator instances are obtained through calls to a factory method, in
which the alias of the encryption algorithm with which the key will be used and,
optionally, the name of the provider must be specified.
KeyGenerator generadorAES = KeyGenerator.getInstance("AES","BC");
2. KeyGenerator configuration.
generadorAES.init(new SecureRandom());
3. Key creation.
SecretKey clave = generadorDES.generateKey();

5.1.3 Encryption and Decryption

Once the necessary key has been created, the encryption and decryption operations
are performed.
1. 1. The operating mode of the encryptor must be set (method init(…))
• DECRYPT_MODE: decrypted mode
• ENCRYPT_MODE: encrypted mode
• PRIVATE_KEY: key to indicate the “unpacking” of a private key
• PUBLIC_KEY: key to indicate the “unpacking” of a public key
• SECRET_KEY: key to indicate the “unpacking” of a secret key (symmetric)
• UNWRAP_MODE: key unpacking mode (key decryption)
• WRAP_MODE: key “packing” mode (key encryption)

cifrador.init(Cipher.ENCRYPT_MODE, clave);
cifrador.init(Cipher.DECRYPT_MODE, clave);

2. The algorithm must be “fed” with the data to be encrypted/decrypted (using the
update() methods):
byte[] update(byte[] input)
byte[] update(byte[] input, int offset, int len)
Returns a byte array with the "partial" result of the encryption/decryption.
3. The encryption/decryption must be finalized by invoking the doFinal() method
that finalizes the operations (Important: it is always necessary to invoke it in
case padding has to be handled):
byte[] doFinal()
byte[] doFinal(byte[] input)
Introduction to Cryptography in Blockchain 21

byte[] doFinal(byte[] input, int inputOffset, int inputLen) // Combine


update() and doFinal()
Returns a byte array with the result of the encryption/decryption of the last
block.
Example of using the DES algorithm: ExampleAES:
$ javac ExampleAES.java
$ java ExampleAES fichero.txt

5.2 Asymmetric Encryption

Keys are managed by objects that implement the PublicKey and PrivateKey interface
(which in turn inherits from the Key interface). Keys are created using a specific
KeyPairGenerator object for each asymmetric algorithm:
1. Creation of the KeyPairGenerator using a factory method. The alias of the
encryption algorithm and the name of the provider must be indicated [initially
the default provider “SUN” did not include RSA due to limitations to the export
of encryption algorithms].
Security.addProvider(new BouncyCastleProvider()); // provider BC

KeyPairGenerator keyGenRSA = KeyPairGenerator.getInstance("RSA",
"BC"); //Use BouncyCastle
2. KeyPairGenerator configuration (usually key size specification)
gkeyGenRSA.initialize(1024); // clave RSA de 1024 bits.
3. Creation of the key pair (and recovery of the public and private keys).
KeyPair clavesRSA = keyGenRSA.generateKeyPair();
PrivateKey clavePrivada = clavesRSA.getPrivate();
PublicKey clavePublica = clavesRSA.getPublic();
The parameters of the RSA public and private keys can be inspected by
forcing a cast to the RSAPrivateKey and RSAPublicKey interfaces (import del
paquete java.security.interfaces.*).
RSAPrivateKey clavePrivadaRSA = (RSAPrivateKey) clavePrivada;
System.out.println("exponente descrifrado: "+ clavePri-
vadaRSA.getPrivateExponent().toString());
System.out.println("modulo: " + clavePrivadaRSA.getModulus().toString());

RSAPublicKey clavePublicaRSA = (RSAPublicKey) clavePublica;


System.out.println("exponente cifrado: “ + clavePubli-
caRSA.getPublicExponent().toString());
22 J. Bermejo Higuera et al.

System.out.println("modulo: " + clavePublicaRSA.getModulus().toString());

The Chiper object would then be used in encryption and decryption mode,
executing its methods getinstance, init, dofinal in sequence.
Example of the use of the RSA algorithm:
$ javac -classpath ".:bcprov-jdk15on-xxx.jar" EjemploRSA.java (en Linux)
$ java -classpath ".:bcprov-jdk15on-xxx.jar" EjemploRSA (en Linux)

5.3 Key Storage

Since JCA has a provider-based architecture where the provider implementation


classes are independent of the generic interfaces defined in the API and, in principle,
are not directly accessible, “intermediate steps” are necessary to store and retrieve
the internal key representations, especially in the case of asymmetric key pairs.
• All objects that encapsulate some kind of key (SecrectKey, PublicKey, PrivateKey)
have a getEncoded() method that returns a byte[] with an independent and
interoperable representation of the key itself (the [Spec] specification of the key).
• Use of KeyFactory and SecretKeyFactory objects to create keys (SecrectKey,
PublicKey, PrivateKey) from their specifications.
• Use of X509EncodedKeySpec to encapsulate the specification of a public key
(independent of the “real” algorithm type) to be stored according to the format
for X509 digital certificates.
• Use of PKCS8EncodedKeySpec to encapsulate the specification of a private key
(independent of the “real” algorithm type) to be stored according to the PKCS8
cryptographic content format.
• For secret keys, the binary representation of the key itself is used directly.

5.4 Digital Signatures

JCA offers Signature objects to simplify the generation and validation of digital
signatures. Another alternative is to combine “by hand” the use of HASH functions
with Cypher objects:
• Using the encrypted mode with the private key to generate the digital signature
from the HASH of the data.
• Using the decrypted mode with the public key to extract the signed HASH to later
compare it with the HASH calculated to validate the signature.
Introduction to Cryptography in Blockchain 23

5.4.1 Instance Creation

They are created using a factory method (not with new()), since it will be the
provider who creates the specific object with its implementations of the corre-
sponding algorithms. The name (alias) of the combination of the HASH algorithm and
asymmetric algorithm to be used (MD5withRSA, MD5withDSA, SHA1withRSA,
SHA1withDSA, SHA256withECDSA), etc. must be specified. Depending on the
case, it is usually necessary to indicate the name of the provider as well.
static Signature getInstance(String algorithm)
static Signature getInstance(String algorithm, String provider)

5.4.2 Signature Generation

The “signature” mode of the Signature object is configured, by means of an initSign


method to which the signature private key is specified.
void initSign(PrivateKey privateKey)
void initSign(PrivateKey privateKey, SecureRandom random)
The data to be signed is fed by passing a byte array through the update methods.
void update(byte[] data)
void update(byte[] data, int off, int len)
The signature is generated and retrieved with the sign() methods.
byte[] sign().
int sign(byte[] outbuf, int offset, int len)

5.4.3 Verification of Signatures

The “verification” mode of the Signature object is configured by means of an


initVerify method which is given the public key to validate the signature.
void initVerify(PublicKey publicKey)
void initVerify(Certificate certificate)
The data to be validated is fed by passing a byte array through the methods update.
void update(byte[] data)
void update(byte[] data, int off, int len)
The signature is verified by checking the validity of the signature with the verify()
methods passing as an argument a byte array with the signature to validate. It returns
a boolean value indicating the result of the verification (coincidence or not of the
HASHES).
boolean verify(byte[] signature)
24 J. Bermejo Higuera et al.

boolean verify(byte[] signature, int offset, int length)

6 Blockchain Block Hashing

A block is a particular grouping of data chained to other data by means of a hash.


It includes a set of transactions that have been confirmed along with additional
information for inclusion in the blockchain. This forms a blockchain, which is a
distributed database that functions as a registry where these transactions are stored.
They usually have a maximum or fixed amount of data depending on the type
of blockchain network and store all the network information chronologically in the
nodes. Within the block are the transactions, which are validated and confirmed
within the block itself. Each block is made up of five sections as shown in Table 2.
All the block data indicated in the table above are represented in the Fig. 11 below:

Table 2 Fields of a blocks


1. Magic number. This is a constant number used to identify the format of a file or protocol. In
the case of a blockchain, this number is used to identify when a block starts and when it ends.
In Bitcoin, it is always the same: 0xD9B4BEF9, and occupies 4 bytes
2. Block size. Number in bytes (in bitcoin it is 4 bytes) that indicates the size of the block
3. Header
• Index. This is a unique number for each block. The index of the first block is 0, the index of
the second block is 1, the index of the third block is 2 and so on
• Difficulty. Sets the number of zeros that the hash of that block should start with (with the
goal of generating a block every 10 min)
• Hash of the previous block. The first block in the chain, called genesis, has no previous
block, so the hash of the previous block is NULL
• Hash of the block itself
• Timestamp. The timestamp is the date and time the block was created, and the nonce is a
32-bit integer (4 bytes) whose value controls the result of the calculated hash of the block
• Nonce. A random number used to find a valid hash for the block
• Merkel root. All transactions in the block are merged into a single hash, which is this root
• Version: this is the number that indicates the level of development of the software at the
time the block was mined
4. Transaction counter. A positive number of variable lengths. In Bitcoin, it ranges in size
from 1 to 9 bytes
5. Transactions.
• The list of valid transactions from the previous block
• Transaction ID
• Public keys of the sender and receiver of the transaction
• Data specific to the type of transaction. Example amount of money sent
Signature of the transaction (signed by the sender with his private key) and an
auto-incremental number called “sequence”, which simply serves to prevent the ID of a
transaction from being repeated
Introduction to Cryptography in Blockchain 25

Fig. 11 Block data

Each block is connected to the previous block through the hash of the previous
block, so all blocks are connected to each other forming a chain. Each block calculates
its own hash based on the block header data such as the block index, the hash of
the previous block, its data, its timestamp and its nonce value using, typically, the
SHA-256 function as shown in the Fig. 12 below:

Fig. 12 Calculation of the current hash


26 J. Bermejo Higuera et al.

Blocks usually have a maximum or fixed amount of data depending on the type
of Blockchain network. Each block references a previous block (parent block) by
including that hash in its header. Once one is introduced into the chain, as it contains
the hash of the previous block it affects the hash of the current block. This causes a
cascade effect which ensures that, once a block has many subsequent generations, it
cannot be changed without forcing a recalculation in all subsequent blocks.
Therefore, the information contained in a block can only be removed, repudiated
or edited by modifying all subsequent blocks, which would require a new compu-
tation at an unfeasible computational cost. This makes malicious manipulation of
the information very difficult as it is completely traceable. This blockchain is a key
security feature of blockchain technology.
One of the data in the header of a block is the Merkle Root, which as indicated
above, its purpose is to unite all transactions in the block into a single hash in order
to efficiently verify the integrity of large data sets. For this purpose, it uses a binary
data structure called Merkle tree containing cryptographic hashes whose root value
is a summary of all leaf values.
This structure is divided into “leaves” or “nodes”. The leaf nodes and nodes at the
bottom are the transactions included in the block and the tree is generated upwards
by applying the corresponding hash function to pairs of nodes recursively until only
a single hash remains, which is called the Merkle Root. These nodes are tagged with
a hash of their child nodes. It produces a complete fingerprint of the entire set of
transactions, providing a very efficient process for verifying whether a transaction is
included in a block (Fig. 13).
Checking whether any data element is included in the tree is done with a maximum
of 2*log(N) operations, which means that it is a very efficient data structure. For

Fig. 13 Merkle tree


Introduction to Cryptography in Blockchain 27

example, if 1024 transactions are contained in a block, the Merkle tree would take
care of grouping them into 512 pairs, which would then be reduced to 256, then 128
and so on down to 2 and the last one. The 1024 hashes of transactions are represented
by only one. To prove that a specific transaction is included in a block, a node only
needs to produce log(N) hashes, producing an authentication path connecting the
specific transaction to the root of the tree.
Another important field in the block header is the nonce which consists of a
random number that can be used only once and is used in operations such as authen-
tication of data transfers between two or more parties. The value has to be random
as it is necessary to ensure that a previously generated value is not repeated.
In Blockchain, it is a 32-bit field whose value is set, after several attempts, until
the hash of the block contains a certain number of zeros equal to the mining difficulty
defined in the program. Any change in the data block will cause the hash of the block
to be completely different.

7 Blockchain Hashcode Using Java

As explained in Sect. 6, the header of a block contains its own signature and a
signature of the previous block, so that all blocks are chained together. According to
Sect. 5.4, a class called Sign is designed to implement the signature, which imple-
ments a method to generate public and private key pairs (genkeypair) and methods to
sign (using private key) and verify the signature using the public key and the signature
data itself. Elliptic curve with Digital Signature Algorithm (ECDSA) is designed for
implementing the digital signature. The algorithm used is SHA256 with ECDSA.
Signing and verification process is done with the SHA256 with ECDSA algorithm:
• The public and private keys are generated.
• The signature object for signature is created.
• The signature object is initialized.
• The data is signed.
• The signature object is created for signature verification.
• The signature object is initialized.
• The signature is verified.
Figure 14 shows the Sign class implemented with the key generation methods,
signature using the signing agent’s private key and signature verification from the
data and the signature itself using the signing agent’s public key.

8 Creation of Block and Hashes Using Java

In any blockchain, there are a number of structures that must always be defined:
28 J. Bermejo Higuera et al.

import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.InvalidKeyExcep on;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmExcep on;
import java.security.InvalidAlgorithmParameterExcep on;
import java.security.NoSuchProviderExcep on;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureExcep on;
import java.security.spec.InvalidKeySpecExcep on;
import java.security.spec.EncodedKeySpec;
import java.security.spec.ECGenParameterSpec;
import java.io.UnsupportedEncodingExcep on;
import java.u l.*;

/* Genera ng a pair of public-private keys with ECDSA (Elip c curves) */


public abstract class Sign {
public sta c KeyPair genkeypair() throws NoSuchAlgorithmExcep on, InvalidAlgorithmParameterExcep on,
InvalidKeyExcep on, UnsupportedEncodingExcep on, SignatureExcep on {

ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");


KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
g.ini alize(ecSpec, new SecureRandom());
KeyPair keypair = g.generateKeyPair();
return keypair;
}

public sta c boolean verify(byte[] info, byte[] firma, byte[] publickey) throws InvalidKeySpecExcep on,
NoSuchAlgorithmExcep on, InvalidAlgorithmParameterExcep on, InvalidKeyExcep on,
UnsupportedEncodingExcep on, SignatureExcep on {
Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA");
KeyFactory kf = KeyFactory.getInstance("EC");
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publickey));
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
ecdsaVerify.initVerify(publicKey);
ecdsaVerify.update(firma);
boolean result = ecdsaVerify.verify(Base64.getDecoder().decode(firma));
return result;
}
public sta c byte[] Signer(byte[] info, byte[] privatekey) throws Excep on {
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privatekey);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKeyObj = keyFactory.generatePrivate(keySpec);
ecdsaSign.initSign(privateKeyObj);
ecdsaSign.update(info.toString().getBytes("UTF-8"));
byte[] signature = ecdsaSign.sign();
Figura 1. Sign class
String sig = Base64.getEncoder().encodeToString(signature);
return sig.getBytes();
}
}

Fig. 14 Sign class


Introduction to Cryptography in Blockchain 29

• Transactions.
• Blocks.
• Blockchain.
• A transaction pool where to store transactions temporarily until they are added to
a block.
• Sign utils.
As explained in Sect. 6, the header of a block contains the creation of a blockchain,
it requires defining the data structures needed to implement the blockchain. The
header of a block at least includes:
• Hash of the block itself computed as the hash of the header.
• Hash for proof of work.
• Timestamp.
• Nonce or solution to the proof-of-work to mine that block.
• The root of the Merkle tree.
• The content of the block is basically the list of transactions added to the block.
Figure 15 shows the blockchain schema.
The Fig. 16 shows the block class.
The Transactions class needs to be created. Transactions are a fundamental part
of a blockchain. Everything surrounding the blockchain is designed to ensure that
transactions can be created, propagated across the network, validated and added to
the registry or blockchain.
The lifecycle of a transaction will begin with the creation of the transaction, which
is signed by the issuer with their private key and transmitted to a node in the network
that validates it and propagates it to the rest of the nodes. Finally, the transaction is

BlockChain Transac onPool

Block

Transac on

Sign

Fig. 15 Blockchain system


30 J. Bermejo Higuera et al.

import java.u l.*;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestU ls;
import org.apache.commons.lang3.ArrayU ls;
import com.google.common.primi ves.Longs;

public class Block {


// Hash of block
private byte[] hash;
// Hash of previous block.
private byte[] hashBloqueAnterior;
// Nonce (calculated as proof of work solu on)
private long nonce;
// block Timestamp
private long mestamp;
// Merkke tree Root calculated from blocks transac ons.
private byte[] raizArbolMerkle;
// block transac ons list
private List<Transaccion> transac ons;
public Block() {
}
public Block(byte[] hashBloqueAnterior, List<Transaccion> transac ons long nonce) {
this.hashBloqueAnterior = hashPreviousBlock;
this.transacciones = transac ons;
this.nonce = nonce;
this. mestamp = System.currentTimeMillis();
this.raizArbolMerkle = calculateRootMerkle();
this.hash = calcularHash();

//Méthods for ini aliza ng data, calculateHash and calculateRootMerkletree…



public byte[] calcularHash() {
byte[] hashableData = ArrayU ls.addAll(hashBloqueAnterior, raizArbolMerkle);
hashableData = ArrayU ls.addAll(hashableData, Longs.toByteArray(nonce));
hashableData = ArrayU ls.addAll(hashableData, Longs.toByteArray( mestamp));
return DigestU ls.sha256(hashableData);
}

public byte[] calculateRootMerkle tree() {
Queue<byte[]> HashesQueue = new LinkedList<>(
transac ons.stream().map(Transac on::getHash).collect(Collectors.toList()));
while (colaHashes.size() > 1) {
byte[] info = ArrayU ls.addAll(HashesQueue.poll(), HashesQueue.poll());
HashesQueue.add(DigestU ls.sha256(info)); // add to queue
}
return HashesQueue.poll();
}
}

Fig. 16 Block class

added to a block by the node that finds a solution to the proof of work and propagates
it to the other nodes. Each node in the network will validate that the new block is
valid and add it to its blockchain.
Figure 17 shows the Transaction class implementation.
The transaction pool is a container in which transactions are placed waiting to be
included in a block. It is implemented by means of a collection (Set) of transactions.
This type of structure will make it possible to avoid having duplicate transactions in
the pool. Figure 18 includes the definition of the TransactionPool class.
Introduction to Cryptography in Blockchain 31

import com.google.common.primi ves.Longs;


import org.apache.commons.codec.digest.DigestU ls;
import org.apache.commons.lang3.ArrayU ls;

import java.u l.Arrays;


import java.u l.Date;

public class Transac on {


private byte[] hash; //Transac on Hash
private byte[] sender; // Sender public key of transaction
private byte[] receiver; // Receiver public Key of transaction
private double data; // Data to transfer
private byte[] sing; // Sing with private key by sender
private long mestamp; // Timestamp of transac on from 1/1/1970
// Constructors
public Transaccion() {
}
public Transaccion(byte[] sender, byte[] receiver, double data, byte[] sign) {
this.sender = sender;
this.receiver = receiver;
this.data = data;
this.sign = sign;
this. mestamp = System.currentTimeMillis();
this.hash = Transac onHashCalculate();
}
// Ge ers y se ers

public byte[] getTransac onContent() {
byte[] content = ArrayU ls.addAll(String.valueOf(data).getBytes());
content = ArrayU ls.addAll(content, sender);
content = ArrayU ls.addAll(content, receiver);
content = ArrayU ls.addAll(content, sign);
content = ArrayU ls.addAll(content, Longs.toByteArray( mestamp));
return content;
}
public byte[] Transac onHashCalculate () {
return DigestU ls.sha256(getTransac onContent());
}
public boolean esValida() {
// verificar hash
if (!Arrays.equals(getHash(), Transac onHashCalculate ())) {
return false;
}
// Sign verify
try {
if (!Sign.verify(getTransac onContent(), getFirma(), sender)) {
return false;
}
} catch (Excep on e) {
return false;
}

return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Transac on tr = (Transac on) obj;
return Arrays.equals(hash, tr.hash);
}
@Override
public int hashCode() {
return Arrays.hashCode(hash);
}
@Override
public String toString() {
return "{" + hash + ", " + sender + ", " + receiver + ", " + data + ", " + sign + ", " + new Date( mestamp) + "}";
}
}

Fig. 17 Transaction class


32 J. Bermejo Higuera et al.

import java.u l.Collec on;


import java.u l.HashSet;
import java.u l.Set;

public class Transac onPool {


private Set pool = new HashSet<>();

//Add transac on
public synchronized boolean add(Transac on transac on) {
if (transaccion.isValid()) {
pool.add(transac on);
return true;
}
return false;
}

//Remove transac on
public void remove(Transac on transac on) {
pool.remove(transaccion);
}

//Check if the pool contains all transac ons in a transaction list


public boolean Transac onsContent(Collec on transac ons) {
return pool.containsAll(transac ons);
}
}

Fig. 18 TransactionPool class

9 Create a Blockchain

Finally, we have to define the structure of the blockchain. The blockchain is a series
of “blocks” that group transactions and that are linked following a temporal order.
We can implement our blockchain as a simple list of blocks that are added as they are
received. The position of a block in the chain is called the height. The implementation
of the BlockChain class is shown in Fig. 19.
Introduction to Cryptography in Blockchain 33

import java.u l.List;

public class BlockChain {

// Lista de bloques en la cadena ordenados por altura (posición en la cadena)


private List bloques;

public BlockChain () {
}

public BlockChain (List blocks) {


this.blocks = bloques;
}

public List getBlocks() {


return blocks;
}

public void setBlocks(List blocks) {


this.blocks = blocks;
}

public boolean equals(Object obj) {


if (this == o)
return true;
if (o == null || getClass() != obj.getClass())

return false;

BlockChain chain = (BlockChain) obj;

if(blocks.size() != chain.getBlocks().size())
return false;

for(int i=0;i<blocks.size();i++) {
if(blocks.get(i) != chain.getBlocks().get(i))
return false;
}

return true;
}

public String toString() {


return blocks.toString();
}
}

Fig. 19 Blockchain class

References

1. Khan D (1967) The codebreakers. The story of secret writing, 1st edn. Macmillan Publishing
Company, New York, pp 266–282. https://lost-contact.mit.edu/afs/adrake.org/usr/rkh/Books/
books/Kahn,%20David%20-%20The%20CodeBreakers.pdf
2. Kerckhoffs A (1883) La cryptographie militaire. J des sci militaires IX:5–38 (Janvier 1883)
161–191 (Février 1883). https://www.arcsi.fr/doc/cryptomilitaire.pdf
3. Shannon CE Communication theory of secrecy systems. Bell Syst Technical J 28:656–715.
http://netlab.cs.ucla.edu/wiki/files/shannon1949.pdf
34 J. Bermejo Higuera et al.

4. Diffie W, Hellman M (1976) New directions in cryptography. IEEE Trans Inf Theory 22:644–
654
5. Gisin G, Ribordy WT, Zbinden H (2002) Quantum cryptography. Rev Mod Phys 74:145–195.
arXiv:quant-ph/0101098
6. Orueta GD, Mur Pérez F, Ruiz ES (2004) seguridad en las comunicaciones y en la información.
Editorial: Uned ISBN13:9788436249750
7. Menezes AJ, van Oorschot y PC, Vanstone SA (1997) Handbook of applied cryptography, 1st
edn. CRC Press, Boca Raton, pp 1–816, FL. ISBN: 0-8493-8523-7. http://www.itl.nist.gov/fip
spubs/fip186.htm
8. Rivest R, Shamir A, Adleman L (1978) A method for obtaining digital signatures and public
key cryptosystems. Commun ACM 21:120–126
9. ElGamal T (1985) A public-key cryptosystem and a signature scheme based on discrete
logarithm. IEEE Trans Inf Theory 31:469–472
10. Information Technology Laboratory. (1994). Algoritmo asimétrico DSA del NIST. http://www.
itl.nist.gov/fipspubs/fip186.htm
11. Ramió Aguirre J (2006) Libro electrónico de seguridad Informática y Criptografía, 6th edn.
Universidad Politécnica de Madrid
12. Menezes A, Van Oorschot P, Vanstone S (2001) Handbook of applied cryptography, 2nd edn.
CRC Press
13. Pieroni A, Scarpato N, Felli L (2020) Blockchain and IoT convergence—a systematic survey
on technologies, protocols and security. Appl Sci 10(19):6749. https://doi.org/10.3390/app101
96749
14. Fuster Sabater A, de la Guía Martínez D, Hernández Encinas L, Montoya Vitini F, Muñoz
Masqué J (2004) Técnicas Criptográficas de Protección de datos 3ª Edición. Ed. RAMA.
ISBN:84-7897-594-2

You might also like