Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. public static byte[] encrypt(char[] pass, byte[] toEncrypt) throws Exception {
  2. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", new BouncyCastleProvider());
  3.  
  4. byte[] bytes = new byte[8];
  5. bytes[0] = (byte)0xC7;
  6. bytes[1] = (byte)0x73;
  7. bytes[2] = (byte)0x21;
  8. bytes[3] = (byte)0x8C;
  9. bytes[4] = (byte)0x7E;
  10. bytes[5] = (byte)0xC8;
  11. bytes[6] = (byte)0xEE;
  12. bytes[7] = (byte)0x99;
  13.  
  14. // Generating IV.
  15. int ivSize = 16;
  16. byte[] iv = new byte[ivSize];
  17. SecureRandom random = new SecureRandom();
  18. random.nextBytes(iv);
  19. IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
  20.  
  21. SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
  22. KeySpec spec = new PBEKeySpec(pass, bytes, 65536, 128);
  23. SecretKey tmp = factory.generateSecret(spec);
  24. SecretKeySpec skey = new SecretKeySpec(tmp.getEncoded(), "AES");
  25.  
  26. cipher.init(Cipher.ENCRYPT_MODE, skey, ivParameterSpec);
  27. byte[] encrypted = cipher.doFinal(toEncrypt);
  28.  
  29. // Combine IV and encrypted part.
  30. byte[] encryptedIVAndText = new byte[ivSize + encrypted.length];
  31. System.arraycopy(iv, 0, encryptedIVAndText, 0, ivSize);
  32. System.arraycopy(encrypted, 0, encryptedIVAndText, ivSize, encrypted.length);
  33.  
  34. return encryptedIVAndText;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement