Java Cryptography Tutorial
Java Cryptography Tutorial
i
Java Cryptography
Audience
This tutorial has been prepared for beginners to make them understand the basics of JCA.
All the examples are given using the Java programming language therefore, a basic idea
on Java programming language is required.
Prerequisites
For this tutorial, it is assumed that the readers have a prior knowledge of Java
programming language.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Java Cryptography
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
What is Cryptanalysis?..................................................................................................................................... 1
ii
Java Cryptography
iii
1. Java Cryptography – Introduction Java Cryptography
Cryptography is the art and science of making a cryptosystem that is capable of providing
information security.
Cryptography deals with the securing of digital data. It refers to the design of mechanisms
based on mathematical algorithms that provide fundamental information security services.
You can think of cryptography as the establishment of a large toolkit containing different
techniques in security applications.
What is Cryptanalysis?
The art and science of breaking the cipher text is known as cryptanalysis.
Cryptanalysis is the sister branch of cryptography and they both co-exist. The
cryptographic process results in the cipher text for transmission or storage. It involves the
study of cryptographic mechanism with the intention to break them. Cryptanalysis is also
used during the design of the new cryptographic techniques to test their security strengths.
Cryptography Primitives
Cryptography primitives are nothing but the tools and techniques in Cryptography that
can be selectively used to provide a set of desired security services:
Encryption
Hash functions
Digital Signatures
Cryptography in Java
The Java Cryptography Architecture (JCA) is a set of APIs to implement concepts of modern
cryptography such as digital signatures, message digests, certificates, encryption, key
generation and management, and secure random number generation, etc.
Using JCA, developers can build their applications integrating security in them.
1
Java Cryptography
2
Java Cryptography
2. Java Cryptography — Message Digest
Hash functions are extremely useful and appear in almost all information security
applications.
A hash function is a mathematical function that converts a numerical input value into
another compressed numerical value. The input to the hash function is of arbitrary length
but output is always of fixed length.
Values returned by a hash function are called message digest or simply hash values.
The following picture illustrated hash function.
To convert a given message to a message digest, follow the steps given below:
MessageDigest md = MessageDigest.getInstance("SHA-256");
3
Java Cryptography
md.update(msg.getBytes());
Example
Following is an example, which reads data from a file, generates a message digest, and
prints it.
import java.security.MessageDigest;
import java.util.Scanner;
System.out.println(digest);
4
Java Cryptography
}
System.out.println("Hex format : " + hexString.toString());
}
}
Output
The above program generates the following output:
5
3. Java Cryptography — Creating a MAC Java Cryptography
The process of using MAC for authentication is depicted in the following illustration −
In Java, the Mac class of the javax.crypto package provides the functionality of message
authentication code. Follow the steps given below to create message authentication code
using this class.
Initialize the KeyGenerator object created in the previous step using this method.
//Creating/Generating a key
Key key = keyGen.generateKey();
Example
The following example demonstrates the generation of Message Authentication Code
(MAC) using JCA. Here, we take a simple message "Hi how are you" and, generate a Mac
for that message.
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
7
Java Cryptography
import javax.crypto.Mac;
//Creating/Generating a key
Key key = keyGen.generateKey();
System.out.println("Mac result:");
System.out.println(new String(macResult));
}
}
Output
The above program will generate the following output:
Mac result:
8
Java Cryptography
HÖ„^ǃÎ_Utbh…?š_üzØSSÜh_ž_œa0ŽV?
9
Java Cryptography
10
4. Java Cryptography — Keys Java Cryptography
Where,
Encryption Key is a value that is known to the sender. The sender inputs the
encryption key into the encryption algorithm along with the plaintext in order to
compute the cipher text.
Decryption Key is a value that is known to the receiver. The decryption key is
related to the encryption key, but is not always identical to it. The receiver inputs
the decryption key into the decryption algorithm along with the cipher text in order
to compute the plaintext.
Fundamentally there are two types of keys/cryptosystems based on the type of encryption-
decryption algorithms.
11
5. Java Cryptography — Storing Keys Java Cryptography
The Keys and certificates used/generated are stored in a database called the keystore. By
default, this database is stored in a file named .keystore.
You can access the contents of this database using the KeyStore class of the
java.security package. This manages the following three different entries:
PrivateKeyEntry
SecretKeyEntry
TrustedCertificateEntry
Create an object of the KeyStore class using the getInstance() method as shown below.
In general, the KeyStore is stored in the file named cacerts, in the location C:/Program
Files/Java/jre1.8.0_101/lib/security/ and its default password is changeit, load it
using the load() method as shown below.
12
Java Cryptography
Set the entry to the keystore using the setEntry() method as shown below.
Example
The following example stores keys into the keystore existing in the “cacerts” file (windows
10 operating system).
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
13
Java Cryptography
Output
The above program generates the following output:
System.out.println("data stored");
14
6. Java Cryptography — Retrieving Keys Java Cryptography
In this chapter, we will learn how to retrieve a key from the keystore using Java
Cryptography.
To retrieve a key from the keystore, follow the steps given below.
Create an object of the KeyStore class using this method as shown below.
In general, the KeyStore is stored in the file named cacerts, in the location C:/Program
Files/Java/jre1.8.0_101/lib/security/ and its default password is changeit; load it
using the load() method as shown below.
15
Java Cryptography
Set the entry to the keystore using the setEntry() method as shown below.
Create an object of the KeyStore.SecretKeyEntry class by passing the alias for required
key and the protection parameter object created in the previous steps, to the getEntry()
method as shown below.
16
Java Cryptography
Example
Following example shows how to retrieve keys from a key store. Here, we store a key in
a keystore, which is in the “cacerts” file (windows 10 operating system), retrieve it, and
display some of the properties of it such as the algorithm used to generate the key and,
the format of the retrieved key.
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.KeyStore.ProtectionParameter;
import java.security.KeyStore.SecretKeyEntry;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
17
Java Cryptography
Output
The above program generates the following output:
18
Java Cryptography
Generating Keys
19
7. Java Cryptography — KeyGenerator Java Cryptography
Java provides the KeyGenerator class. This class is used to generate secret keys and
objects of this class are reusable.
To generate keys using the KeyGenerator class, follow the steps given below.
Initialize the KeyGenerator object created in the previous step using the init() method.
Example
Following example demonstrates the key generation of the secret key using the
KeyGenerator class of the javax.crypto package.
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
20
Java Cryptography
//Creating/Generating a key
Key key = keyGen.generateKey();
System.out.println(key);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(cipher.ENCRYPT_MODE, key);
Output
The above program generates the following output:
com.sun.crypto.provider.DESKey@18629
[B@2ac1fdc4
21
8. Java Cryptography — KeyPairGenerator Java Cryptography
Java provides the KeyPairGenerator class. This class is used to generate pairs of public
and private keys. To generate keys using the KeyPairGenerator class, follow the steps
given below.
Initialize the KeyPairGenerator object created in the previous step using the initialize()
method as shown below.
You can get the public key from the generated KeyPair object using the getPublic()
method as shown below.
22
Java Cryptography
Example
Following example demonstrates the key generation of the secret key using the
KeyPairGenerator class of the javax.crypto package.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
Output
The above program will generate the following output:
Keys generated
23
Java Cryptography
Digital Signature
24
9. Java Cryptography — Creating Signature Java Cryptography
Digital signatures allow us to verify the author, date and time of signatures, authenticate
the message contents. It also includes authentication function for additional capabilities.
Authentication
Digital signatures help to authenticate the sources of messages. For example, if a bank’s
branch office sends a message to central office, requesting for change in balance of an
account. If the central office could not authenticate that message is sent from an
authorized source, acting of such request could be a grave mistake.
Integrity
Once the message is signed, any change in the message would invalidate the signature.
Non-repudiation
By this property, any entity that has signed some information cannot later deny having
signed it.
25
Java Cryptography
Initialize the KeyPairGenerator object created in the previous step using the initialize()
method as shown below.
Get the private key using the getPrivate() method as shown below.
26
Java Cryptography
Initialize the Signature object created in the previous step using the initSign() method
as shown below.
Update the initialized Signature object by passing the data to be signed to the update()
method in the form of byte array as shown below.
Example
Following Java program accepts a message from the user and generates a digital signature
for the given message.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Scanner;
27
Java Cryptography
}
}
28
Java Cryptography
Output
The above program generates the following output:
/yGL?i??a!?
29
10. Java Cryptography — Verifying Signature Java Cryptography
You can create digital signature using Java and verify it following the steps given below.
The KeyPairGenerator class provides the getInstance() method which accepts a String
variable representing the required key-generating algorithm and returns a
KeyPairGenerator object that generates keys
Initialize the KeyPairGenerator object created in the previous step using the initialize()
method as shown below.
Get the private key using the getPrivate() method as shown below.
30
Java Cryptography
Initialize the Signature object created in the previous step using the initSign() method
as shown below.
Update the initialized Signature object by passing the data to be signed to the update()
method in the form of byte array as shown below.
Therefore, initialize the Signature object for verification using the initVerify() method as
shown below.
31
Java Cryptography
Example
Following Java program accepts a message from the user, generates a digital signature
for the given message, and verifies it.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Scanner;
32
Java Cryptography
if(bool){
System.out.println("Signature verified");
}else{
System.out.println("Signature failed");
}
33
Java Cryptography
}
}
Output
The above program will generate the following output:
34
Java Cryptography
Cipher Text
35
11. Java Cryptography — Encrypting data Java Cryptography
You can encrypt the given data using the Cipher class of the javax.crypto package. Follow
the steps given below to encrypt the data using Java.
Initialize the KeyPairGenerator object created in the previous step using the initialize()
method as shown below.
36
Java Cryptography
Create the Cipher object using the getInstance() method as shown below.
Initialize the Cypher object using the init() method as shown below.
Update the initialized Cipher object by passing the data to the update() method in the
form of byte array as shown below.
Example
Following Java program accepts text from user, encrypts it using RSA algorithm and, prints
the encrypted format of the given text
import java.security.KeyPair;
37
Java Cryptography
import java.security.KeyPairGenerator;
import java.security.Signature;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
38
Java Cryptography
Output
The above program will generate the following output:
39
12. Java Cryptography — Decrypting Data Java Cryptography
You can decrypt the encrypted data using the Cipher class of the javax.crypto package.
Follow the steps given below to decrypt given data using Java.
Initialize the KeyPairGenerator object created in the previous step using the initialize()
method as shown below.
40
Java Cryptography
Create the Cipher object using the getInstance() method as shown below.
Initialize the Cypher object using the init() method as shown below.
Update the initialized Cipher object by passing the data to the update() method in the
form of byte array as shown below.
41
Java Cryptography
Example
Following Java program accepts text from user, encrypts it using RSA algorithm and, prints
the cipher of the given text, decrypts the cipher and prints the decrypted text again.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import javax.crypto.Cipher;
42
Java Cryptography
System.out.println(new String(decipheredText));
}
}
Output
The above program generates the following output:
Encrypted Text:
]/[?F3?D?p
v?w?!?H???^?A??????P?u??FA?
43
Java Cryptography
?
???_?? ???_jMH-??>??OP?'?j?_?n`
?_??'`????o??_GL??g???g_f?????f|???LT?|?Vz_TDu#??\?<b,,?$C2???Bq?#?lDB`??g,^??K
?_?v???`}?;LX?a?_5e???#???_?6?/B&B_???^?__Ap^#_?q?IEh????_?,??*??]~_?_?D?
_y???lp??a?P_U{
Decrypted Text:
Welcome to Tutorialspoint
44