Introduction To Cryptography
Introduction To Cryptography
in Blockchain
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.
© 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.
• 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.
• 1975 Diffie and Hellman establish the theore cal founda ons of public key algorithms.
XX
Fig. 4 Classification of
cryptosystems
Current crypto
systems
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.
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).
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.
• 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
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
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
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.
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.
x3 = 32 − 0 − 1 = 9 − 1 = 8 mod (7) = 1
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.
• 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.
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");
The use of symmetric (and also asymmetric) ciphers is done through instances that
inherit from the class Cypher.
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.
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();
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
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());
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)
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
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)
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:
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
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.
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.
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.*;
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();
}
}
• 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
Block
Transac on
Sign
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
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) + "}";
}
}
//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);
}
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
public BlockChain () {
}
return false;
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;
}
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