Guest User

AES enc/dec

a guest
Jan 21st, 2020
73
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.math.*;
  2. import java.security.*;
  3. import java.util.*;
  4. import javax.crypto.*;
  5. import javax.crypto.spec.*;
  6.  
  7. public class Test {
  8.     private static Key key;
  9.  
  10.     public static void main(String... args) {
  11.         key = getKey("1234567890$");
  12.         byte[] encrypted = encrypt("test");
  13.         String str = new String(encrypted);
  14.         System.out.println("encrypt: "+str);
  15.         System.out.println("decrypt arr: "+decrypt(encrypted));
  16.         System.out.println("decrypt str: "+decrypt(stringFromBytes(toHex(str))));
  17.     }
  18.    
  19.     public static byte[] stringFromBytes(String s) {
  20.         byte[] byteArray = new byte[s.length()/2];
  21.         String[] strBytes = new String[s.length()/2];
  22.         int k = 0;
  23.         for (int i = 0; i < s.length(); i=i+2) {
  24.             int j = i+2;
  25.             strBytes[k] = s.substring(i,j);
  26.             byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
  27.             k++;
  28.         }
  29.         return byteArray;
  30.     }
  31.    
  32.     private static String toHex(String s) {
  33.         return String.format("%2x", new BigInteger(1, s.getBytes()));
  34.     }
  35.    
  36.     private static String decrypt(byte[] enc) {
  37.         try {
  38.             Cipher cipher = Cipher.getInstance("AES");
  39.             cipher.init(Cipher.DECRYPT_MODE, key);
  40.             return new String(cipher.doFinal(enc));
  41.         } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {}
  42.         return null;
  43.     }
  44.    
  45.     private static byte[] encrypt(String text) {
  46.         try {
  47.             Cipher cipher = Cipher.getInstance("AES");
  48.             cipher.init(Cipher.ENCRYPT_MODE, key);
  49.             return cipher.doFinal(text.getBytes());
  50.         } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {}
  51.         return null;
  52.     }
  53.    
  54.     private static Key getKey(String pass) {
  55.         if (pass != null && !pass.isEmpty())
  56.             try {
  57.                 MessageDigest sha = MessageDigest.getInstance("SHA-1");
  58.                 byte[] key = pass.getBytes();
  59.                 key = sha.digest(key);
  60.                 key = Arrays.copyOf(key, 16);
  61.                 return new SecretKeySpec(key, "AES");
  62.             } catch (NoSuchAlgorithmException e) {}
  63.         return null;
  64.     }
  65. }
RAW Paste Data