Advertisement
bruimafia

Untitled

Nov 18th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.70 KB | None | 0 0
  1. package sample;
  2.  
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.nio.ByteBuffer;
  7. import java.security.SecureRandom;
  8. import java.util.Arrays;
  9. import java.util.Random;
  10.  
  11. public class AesCipher {
  12.  
  13. //    private static final String INIT_VECTOR = "ItIsOurBigSecret";
  14. //    private static final String INIT_VECTOR = "dfgthyjukifredsr";
  15.  
  16.     // зашифрование
  17.     static byte[] encrypt(byte[] secretKey, byte[] plainText, String mode) {
  18.  
  19.         try {
  20.             if (!isKeyLengthValid(secretKey)) {
  21.                 throw new Exception("Длина ключа должна быть 128, 192 или 256 бит!");
  22.             }
  23.  
  24. //            IvParameterSpec ivParameterSpec = new IvParameterSpec(INIT_VECTOR.getBytes());
  25.             SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "AES");
  26.  
  27.             Cipher cipher = Cipher.getInstance("AES/" + mode + "/PKCS5Padding");
  28.  
  29.             SecureRandom secureRandom = new SecureRandom();
  30.             byte[] iv = new byte[cipher.getBlockSize()];
  31.             secureRandom.nextBytes(iv);
  32.             IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
  33.  
  34.             if (mode.equals("ECB"))
  35.                 cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
  36.             else
  37.                 cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
  38.  
  39.             byte[] c = cipher.doFinal(plainText);
  40.  
  41. //            return cipher.doFinal(plainText);
  42.             return ByteBuffer.wrap(new byte[iv.length + c.length]).put(iv).put(c).array();
  43.         } catch (Throwable cause) {
  44.             System.out.print(cause.getMessage());
  45.         }
  46.  
  47.         return null;
  48.     }
  49.  
  50.  
  51.     // дешифрование
  52.     static byte[] decrypt(byte[] secretKey, byte[] cipherText, String mode) {
  53.  
  54.         try {
  55.             if (!isKeyLengthValid(secretKey)) {
  56.                 throw new Exception("Длина ключа должна быть 128, 192 или 256 бит!");
  57.             }
  58.  
  59. //            IvParameterSpec ivParameterSpec = new IvParameterSpec(INIT_VECTOR.getBytes());
  60.             SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "AES");
  61.  
  62.             Cipher cipher = Cipher.getInstance("AES/" + mode + "/NoPadding");
  63.  
  64.             byte[] iv = new byte[cipher.getBlockSize()];
  65.             System.arraycopy(cipherText, 0, iv, 0, iv.length);
  66.             IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
  67.  
  68.             if (mode.equals("ECB"))
  69.                 cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
  70.             else
  71.                 cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
  72.  
  73.             byte[] cipherTextNew = new byte[cipherText.length - iv.length];
  74.             System.arraycopy(cipherText, 15, cipherTextNew, 0, cipherTextNew.length);
  75.  
  76.             return cipher.doFinal(cipherTextNew);
  77.         } catch (Throwable cause) {
  78.             System.out.print(cause.getMessage());
  79.             Controller.ShowMessage(cause.getMessage());
  80.         }
  81.  
  82.         return null;
  83.     }
  84.  
  85.  
  86.     // проверка длины ключа
  87.     private static boolean isKeyLengthValid(byte[] key) {
  88.         return key.length == 16 || key.length == 24 || key.length == 32;
  89.     }
  90.  
  91.  
  92.     // генерация инициализирующего вектора
  93.     private static String genInitVector() {
  94.  
  95.         Random r = new Random();
  96.         StringBuilder builder = new StringBuilder();
  97.  
  98.         for (int j = 0; j < 16; j++) {
  99.             char code = (char) (r.nextInt(94) + 33); // символы с кодами от 33 по 126
  100.             builder.append(Character.toString(code));
  101.         }
  102.  
  103.         return builder.toString();
  104.     }
  105.  
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement