Example of AES using JAVA :
Note : For base64 related method visit this post.
Note : For base64 related method visit this post.
import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * * @author : ThinkTank * * */ public class AESEncryption { private KeyGenerator keyGenerator; private SecureRandom secureRandom; private byte[] randomBytes = new byte[100]; private byte[] encryptedData = new byte[20000]; private byte[] decryptedData = new byte[20000]; private String encryptedDataAsBase64String; private SecretKey secretKey; private SecretKeySpec secretKeySpec; private Cipher cipher; private String originalData; /** * This method will encrypt data as our desired level * * @param data data to be encrypted * @param encryptionLevel level of encryption * @param secureRandomSeed seed value * @return encrypted string */ public String encrypt(byte[] data,int encryptionLevel,int secureRandomSeed) { try { keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(encryptionLevel); secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN"); secureRandom.setSeed(secureRandomSeed); secureRandom.nextBytes(randomBytes); secretKey = keyGenerator.generateKey(); byte[] primaryEncodedKey = secretKey.getEncoded(); secretKeySpec = new SecretKeySpec(primaryEncodedKey, "AES"); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); encryptedData = cipher.doFinal(data); encryptedDataAsBase64String = Util.byteToBase64(encryptedData); } catch (NoSuchProviderException e) { e.getStackTrace(); } catch (NoSuchAlgorithmException e) { e.getStackTrace(); } catch (NoSuchPaddingException e) { e.getStackTrace(); } catch (InvalidKeyException e) { e.getStackTrace(); } catch (BadPaddingException e) { e.getStackTrace(); } catch (IllegalBlockSizeException e) { e.getStackTrace(); } return encryptedDataAsBase64String; } /** * This method will return decrypted data * * @return decrypted data as string */ public String decrypt(byte[] encryptedData) { try { cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); decryptedData = cipher.doFinal(encryptedData); originalData = new String(decryptedData); } catch (InvalidKeyException e) { e.getStackTrace(); } catch (IllegalBlockSizeException e) { e.getStackTrace(); } catch (BadPaddingException e) { e.getStackTrace(); } return originalData; } }
No comments:
Post a Comment