Let's Create an Encryption Software
Hi, Everyone!
This tutorial is to demonstrate how to encrypt and decrypt in Java using the Java Cryptography Extension (JCE). Symmetric key and asymmetric key are the two basic types of cryptographic systems. They are also called as “secret key” and “public key” cryptography.
One of the success factors to Java is attributed to the strong security it provides to the platform and applications.In this tutorial, we will see a simple example on using the “secret key” cryptography with JCE.
Symmetric Key Cryptography
Symmetric (secret) key uses the same key for encryption and decryption. The main challenge with this type of cryptography is the exchange of the secret key between the two parties sender and receiver.
In the following example, we will use the encryption and decryption algorithm available as part of the JCE SunJCE provider.
AES Symmetric Key Encryption
In Java 8 we have got new classes in java.util package for Base64 encoding and decoding. It is important to encode the binary data with Base64 to ensure it to be intact without modification when it is stored or transferred.refer the code below.
package com.javapapers.java.security; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class EncryptionDecryptionAES { static Cipher cipher; public static void main(String[] args) throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); cipher = Cipher.getInstance("AES"); String plainText = "AES Symmetric Encryption Decryption"; System.out.println("Plain Text Before Encryption: " + plainText); String encryptedText = encrypt(plainText, secretKey); System.out.println("Encrypted Text After Encryption: " + encryptedText); String decryptedText = decrypt(encryptedText, secretKey); System.out.println("Decrypted Text After Decryption: " + decryptedText); } public static String encrypt(String plainText, SecretKey secretKey) throws Exception { byte[] plainTextByte = plainText.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedByte = cipher.doFinal(plainTextByte); Base64.Encoder encoder = Base64.getEncoder(); String encryptedText = encoder.encodeToString(encryptedByte); return encryptedText; } public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception { Base64.Decoder decoder = Base64.getDecoder(); byte[] encryptedTextByte = decoder.decode(encryptedText); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedByte = cipher.doFinal(encryptedTextByte); String decryptedText = new String(decryptedByte); return decryptedText; } }
Okay.This is it.hope u got understand about the encryption and decryption.use this tutorial for your further studying.
Thank you!
~CS

Comments
Post a Comment
If you got something from my writings, just put your thoughts out to words...