We can use encryption techniques to save our data. Encryption is the method by which information is converted into secret code that hides the information’s true meaning. The science of encrypting and decrypting information is called cryptography. In computing, unencrypted data is also known as plaintext, and encrypted data is called ciphertext. The formulas used to encode and decode messages are called encryption algorithms, or ciphers.
Let us do go through essentials, in brief, to get a better understanding of the standard practices for protecting sensitive data in Java applications.
- Encryption is a way of scrambling data so that only authorized parties can understand the information. In technical terms, It is the process of converting the human-readable plaintext to the incomprehensible text known as ciphertext.
- Decryption is taking encoded or encrypted text or other data and converting it back into the text so that you and the computer can understand.
- Cipher, any method of transforming a message to conceal its meaning. The term is also used synonymously with ciphertext or cryptogram in reference to the encrypted form of message.
- Secured Random class provides a cryptographically strong random number generator. A cryptographically strong random number minimally complies with statistical random number generator tests specified in FIPS 140-2, Security Requirements for cryptographic modules.
Example: SecureRandom class is used to generate a cryptographically strong pseudo-random number by using a PRNG Algorithm. The following are the advantages of using SecureRandom over Random. 1. SecureRandom produces a cryptographically strong pseudo-random number generator. 2. SecureRandom produces cryptographically strong sequences as described in RFC 1750: Randomness Recommendations for Security
Now let us come onto important methods of SecureRandom class
1. generateSeed() method returns the given number of seeds, computed using the seed generation.
Syntax:
generateSeed()
Return type: Byte array (returns the given number of seeds, computed using the seed generation).
2. setSeed() method reseeds the random object
Return type: Void
Example:
Java
// Java Program Demonstrating How Can We Get Secured // Random Numbers from SecureRandom class // Importing required classes import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; // Main class class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Initialize a secure random number generator SecureRandom secureRandom = SecureRandom.getInstance( "SHA1PRNG" ); // Method 1 // Calling nextBytes method to generate Random // Bytes byte [] bytes = new byte [ 512 ]; secureRandom.nextBytes(bytes); // Printing the SecureRandom number by // calling secureRandom.nextDouble() System.out.println( " Secure Random # generated by calling nextBytes() is " + secureRandom.nextDouble()); // Method 2 // Using setSeed(byte[]) to reseed a Random // object int seedByteCount = 10 ; byte [] seed = secureRandom.generateSeed(seedByteCount); secureRandom.setSeed(seed); System.out.println( " Secure Random # generated using setSeed(byte[]) is " + secureRandom.nextDouble()); } // Catch block to handle the exceptions catch (NoSuchAlgorithmException noSuchAlgo) { // Display message if it occurs System.out.println( " No Such Algorithm exists " + noSuchAlgo); } } } |
Output:
Secure Random # generated by calling nextBytes() is 0.8849167225465367 Secure Random # generated using setSeed(byte[]) is 0.7542495384908446
AES Encryption
AES-128 uses a 128-bit key length to encrypt and decrypt a block of messages, while AES -192 uses a 192-bit key length and AES-256 a 256-bit key length to encrypt and decrypt messages. Each cipher encrypts and decrypts data in blocks of 128 bits using cryptographic keys of 128,192 and 256 bits, respectively. Symmetric, also known as a secret key, ciphers use the same key for encrypting and decrypting, so the sender and the receiver must both know and use the same secret key.
Example
Java
// Java Program to Illustrate AES Encryption // Importing required classes import java.io.*; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; // Main class class GFG { // Encryption function // function 1 public static void encryptEcb(String filenamePlain, String filenameEnc, byte [] key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // Creating cipher instance OF AES encryption Cipher cipher = Cipher.getInstance( "AES/ECB/PKCS5PADDING" ); // Specifying the algorithm SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES" ); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); // Try block to check for exceptions try (FileInputStream fis = new FileInputStream(filenamePlain); // Creating objects of BufferedInputStream, // FileOutputStream and BufferedOutputStream BufferedInputStream inputstream = new BufferedInputStream(fis); FileOutputStream outputstream = new FileOutputStream(filenameEnc); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputstream)) { // Defining the buffer byte [] ibufffer = new byte [ 1024 ]; int length; // Reading while read buffer has data while ((length = inputstream.read(ibufffer)) != - 1 ) { // Creating cipher with buffer byte [] obuffer = cipher.update(ibufffer, 0 , length); if (obuffer != null ) // Writing encrypted text to buffer bufferedOutputStream.write(obuffer); } byte [] obuffer = cipher.doFinal(); if (obuffer != null ) bufferedOutputStream.write(obuffer); } } // Method 3 // Decryption method public static void decryptEcb(String filenameEnc, String filenameDec, byte [] key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // Try block to check for exceptions try (FileInputStream inputStream = new FileInputStream(filenameEnc); FileOutputStream outputStream = new FileOutputStream(filenameDec)) { // Defining buffer byte [] ibuffer = new byte [ 1024 ]; int length; // Creating cipher instance OF AES decryption Cipher cipher = Cipher.getInstance( "AES/ECB/PKCS5PADDING" ); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES" ); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); // While input stream not empty while ((length = inputStream.read(ibuffer)) != - 1 ) { // Reading into the buffer byte [] obuffer = cipher.update(ibuffer, 0 , length); if (obuffer != null ) // Now writing to output buffer outputStream.write(obuffer); } byte [] obuffer = cipher.doFinal(); if (obuffer != null ) outputStream.write(obuffer); } } // Method 3 // Main driver method public static void main(String[] args) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException , IllegalBlockSizeException, InvalidKeyException { // Display message System.out.println( "/****AES Encryption*******/" ); // Placing the PDF path String pFileName = "/home/aniket/IdeaProjects/Gfg Programs/MAD FINAL.pdf" ; String cFileName = "your pdf.enc" ; // Placing the PDF name String decFileName = "your pdf.pdf" ; // Creating cipher key 56 bit key length byte [] cipher_key = "12345678901234561234567890123456" .getBytes( "UTF-8" ); encryptEcb(pFileName, cFileName, cipher_key); decryptEcb(cFileName, decFileName, cipher_key); // Print and display the file credentials System.out.println( "file of encryption: " + pFileName + "\n" + "created encrypted file : " + cFileName + "\n" + "created decrypted file : " + decFileName); } } |
Output:
/****AES Encryption*******/ file of encryption: MAD FINAL.pdf created encrypted file : MAD FINAL.enc created decrypted file : MAD FINAL.pdf