A great strength of Java is the rich set of predefined software that programmers can re-use.
Java security technology includes a large set of APIs, tools, and implementations of commonly used security algorithms, mechanisms, and protocols. The Java security APIs span a wide range of areas, including cryptography, public key infrastructure, secure communication, authentication, and access control. Java security technology provides the developer with a comprehensive security framework for writing applications, and also provides the user or administrator with a set of tools to securely manage applications.
Here we shall be concerned with encryption/decryption using the JCA (Java Cryptography Architecture). The Java Cryptography Architecture (JCA) specifies the design patterns and architecture for defining cryptographic concepts and algorithms. The JCA, like all other Java API’s was designed to make available to the programmer cryptography and security concepts, without having to worry about the implementations.
The JCA is implemented in the classes contained in the packages java.security and javax.crypto.
Part I – Using JCA for symmetric cryptography
The following Java class encrypts and decrypts text using the DES algorithm:
// Import the required java classes
import javax.crypto.*;
import java.security.*; // Required for RSA
import java.io.*;
public class DES {
public DES() {
}
public static void main(String args[]){
// Set up object for getting input stream from keyboard
BufferedReader ch = new BufferedReader(new InputStreamReader(System.in));
try{
// Display prompting message on screen
System.out.print(“Enter message to encode: “);
// Get message to be encoded from keyboard and store it in a string
String toEncode = ch.readLine();
// **************** Stage 1 ****************************************
/*
In order to perform the encryption the string containing the message must first be converted into a byte array. This is done in two steps: (a) the string is converted into an array of characters;
(b) each character is type cast into a byte.
*/
// Convert string into character array
char[] toCodeChars = toEncode.toCharArray();
// Set up byte array to hold char array
byte[] toCodeBytes = new byte[toCodeChars.length];
// Type cast each character in the character array into a byte
for(int i=0;i<toCodeChars.length;i++)
{
toCodeBytes[i] = (byte)toCodeChars[i];
}
// **************** Stage 2 ****************************************
/*
The message is now ready to be encrypted. For this to be done: (a) an appropriately parameterized key must be generated; (b) an appropriately parameterized cipher object must be created and initialized.
*/
// Create object that will be used for generating the symmetric key
KeyGenerator keyGen = KeyGenerator.getInstance(“DES”);
// Use the above created object to generate the symmetric key
SecretKey desKey = keyGen.generateKey();
// Create object that will be used for ciphering
Cipher desCipher = Cipher.getInstance(“DES”);
// Initialize cipher object with the key and set it to encrypt mode
desCipher.init(Cipher.ENCRYPT_MODE, desKey);
/*
We are now ready to proceed with the encryption…
*/
// Set up byte array that will hold the encrypted text
byte[] Coded = new byte[toCodeBytes.length];
// Encrypt…
Coded = desCipher.doFinal(toCodeBytes);
/*
The following loop converts the key in human-readable form and stores it in hexCipher. Required for display purposes only – not necessary for the encryption.
*/
StringBuffer hexKey = new StringBuffer();
for (int i=0;i<desKey.getEncoded().length;i++)
{
hexKey.append(Integer.toHexString(0xFF & desKey.getEncoded()[i]));
}
// Display key on screen
System.out.println(“Here is the key used: ” + hexKey);
/*
The following loop converts the encrypted text in human-readable form and stores it in hexCipher. Required for display purposes only – not necessary for the encryption.
*/
StringBuffer hexCipher = new StringBuffer();
for (int i=0;i<Coded.length;i++)
{
hexCipher.append(Integer.toHexString(0xFF & Coded[i]));
}
// Display cipher text on screen
System.out.println(“Cipher Text: ” + hexCipher);
// **************** Stage 3 ****************************************
// Now it’s time to decrypt…
// Create object that will be used for decrypting
Cipher desCipher2 = Cipher.getInstance(“DES”);
// Initialize cipher object with key and set it to decrypt mode
desCipher2.init(Cipher.DECRYPT_MODE, desKey);
/*
The following code decrypts the encrypted message and stores it into a byte array. In order to display it on screen, this byte array will have to be converted into a character array.
*/
byte[] Decoded = desCipher2.doFinal(Coded);
// Set up char array to hold decoded text
char[] DecodedChars = new char[Decoded.length];
// Convert byte array into char array in or
for(int i=0;i<Decoded.length;i++)
{
DecodedChars[i] = (char)Decoded[i];
}
// Display deciphered text on screen
System.out.println(“Deciphered Text: ” + new String(DecodedChars));
}
catch(Exception e){
System.out.println(e);
}
}
}
Tasks
Study carefully the above program. Make sure that you understand each of the steps followed in order to encode/decode a string.
Copy this code and save it into a file called DES.java
At the command line type:
javac DES.java
This will perform a syntax check and if there are no errors it creates a new file containing the Java
bytecodes.
The bytecodes will be interpreted to execute the program by typing:
java DES
The following code allows time stamps (measured in ms) to be placed at any two points during the execution of a program; it then calculates the time elapsed between the two time stamps.
// Start timing…
long start = System.currentTimeMillis();
// Stop timing
long end = System.currentTimeMillis();
// Calculate elapsed time and display it on screen
System.out.println(“Execution time was “+(end-start)+” ms.”);
Re-edit the DES.java file by inserting this code at appropriate points in stage 2 to time the encryption
process. Then re-compile and execute the program.
Exercise1: Provide a similar Java class that will allow text encryption/decryption using the AES algorithm. Create it in a file called AES.java.
Make detailed notes in your logbook of the actions performed in each step and of what they achieve.
(Hint: in “Stage 2” and “Stage 3” of the above example code the key generation object and the two cipher objects must be parameterised to work with the AES algorithm. Search Tools in gedit might help)
Exercise2: Record the time required to encode a message using the DES and AES algorithms. What do you observe? Repeat the measurement a number of times and record the average time required for each algorithm.
Part II – Using JCA for asymmetric cryptography
Asymmetric cryptography uses a pair of keys: one for encrypting a message and one for decrypting it. The following code produces a pair of keys for use with the RSA algorithm:
// Generate a pair of keys
KeyPairGenerator kpg = KeyPairGenerator.getInstance(“RSA”);
kpg.initialize(1024); //1024 is the keysize in bits
KeyPair kp = kpg.genKeyPair();
// Separate the two keys into public and private
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
Exercise 1: Provide a Java class that will allow text encryption/decryption using the RSA algorithm. (Hint: use the above code to make the necessary amendments to the example program of Part I. The above code should replace the key generation code in “Stage 2” of the example program; the cipher objects of the example program must also be appropriately parameterized to work with the RSA algorithm.) Use the public key to encrypt and the private key to decipher text.
Exercise 2: Measure the times required to encode and decode a message using the RSA algorithm. Repeat the measurement a number of times and record the average time. What do you observe in relation to symmetric-key algorithms?
Exercise 3: Measure the times required to encode and decode a message with RSA using different key sizes. (See code above to amend key size.) What do you observe?
Explain how cryptography can provide some defence against a malicious attack.
Use the order calculator below and get started! Contact our live support team for any assistance or inquiry.
[order_calculator]