JAVA - AES Encryption and Decryption example - Symmetric cryptography
Advanced Encryption Standard which is a symmetric encryption algorithm. AES encryption is used by the U.S. to secure sensitive but unclassified material, so we can say it is secure enough.
Advanced Encryption Standard(AES) is a symmetric encryption algorithm. AES is the industry standard now as it allows 128-bit, 192-bit and 256-bit encryption. Symmetric encryption is very fast as compared to asymmetric encryption and is used in systems such as database systems.
The following illustration highlights how symmetric cryptography works:
Example:
import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.util.Arrays;import java.util.Base64;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.spec.SecretKeySpec;
public class AESDemo {
private static SecretKeySpec secretKey; private static byte[] key;
public static void main(String[] args) throws NoSuchAlgorithmException {
// key String secretKey = "your secret key"; // secret text String originalString = "knowledgefactory.net"; // Encryption String encryptedString = AESDemo.encrypt (originalString, secretKey); // Decryption String decryptedString = AESDemo.decrypt (encryptedString, secretKey); // OriginalString,encryptedString,decryptedString System.out.println("Original String:" + originalString); System.out.println("Encrypted value:" + encryptedString); System.out.println("Decrypted value:" + decryptedString); }
// set key public static void setKey(String myKey) { MessageDigest sha = null; try { key = myKey.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new SecretKeySpec(key, "AES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
// method to encrypt the secret text using key public static String encrypt (String strToEncrypt, String secret) { try { setKey(secret); Cipher cipher = Cipher. getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return Base64.getEncoder(). encodeToString(cipher. doFinal(strToEncrypt.getBytes("UTF-8"))); } catch (Exception e) { System.out.println("Error while encrypting: " + e); } return null; }
// method to decrypt the secret text using key public static String decrypt(String strToDecrypt, String secret) { try { setKey(secret); Cipher cipher = Cipher. getInstance("AES/ECB/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, secretKey); return new String(cipher. doFinal(Base64.getDecoder(). decode(strToDecrypt))); } catch (Exception e) { System.out.println("Error while decrypting: " + e); } return null; }}
Output:
Original String:knowledgefactory.net
Encrypted value:7W9JdoGEuWiV5EFdQxdyE+PYnj7WnkfeMhb3xU5uHgo=
Decrypted value:knowledgefactory.net
More...