Advertisement
Darano

AES.java

Feb 18th, 2019
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. package AesEncryption;
  2.  
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.util.Random;
  6.  
  7. public class AdvancedEncryptionStandard {
  8.     private byte[] key;
  9.     private static final String ALGORITHM = "AES";
  10.  
  11.     //     Encrypts the given plain text
  12.     public byte[] encrypt(String plainText) throws Exception {
  13.         SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
  14.         Cipher cipher = Cipher.getInstance(ALGORITHM);
  15.         cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  16.         byte[] encryptedData = cipher.doFinal(plainText.getBytes("UTF-8"));
  17.         return encryptedData;
  18.     }
  19.  
  20.     //    Decrypts the given byte array
  21.     public String decrypt(byte[] cipherText) throws Exception {
  22.         SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
  23.         Cipher cipher = Cipher.getInstance(ALGORITHM);
  24.         cipher.init(Cipher.DECRYPT_MODE, secretKey);
  25.         String decryptedData = new String(cipher.doFinal(cipherText));
  26.         return decryptedData;
  27.     }
  28.  
  29.     //    creates random key for aes encryption
  30.     public static byte[] createRandomKey(int size) {
  31.         String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz!ยง$%&/()=?*'#+-:;.,_";
  32.         StringBuilder salt = new StringBuilder();
  33.         Random rnd = new Random();
  34.         while (salt.length() < size) { // length of key
  35.             int index = (int) (rnd.nextFloat() * SALTCHARS.length());
  36.             salt.append(SALTCHARS.charAt(index));
  37.         }
  38.  
  39.         return salt.toString().getBytes();
  40.     }
  41.  
  42.     public AdvancedEncryptionStandard(byte[] key) {
  43.         this.key = key;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement