Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static byte[] encrypt(char[] pass, byte[] toEncrypt) throws Exception {
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", new BouncyCastleProvider());
- byte[] bytes = new byte[8];
- bytes[0] = (byte)0xC7;
- bytes[1] = (byte)0x73;
- bytes[2] = (byte)0x21;
- bytes[3] = (byte)0x8C;
- bytes[4] = (byte)0x7E;
- bytes[5] = (byte)0xC8;
- bytes[6] = (byte)0xEE;
- bytes[7] = (byte)0x99;
- // Generating IV.
- int ivSize = 16;
- byte[] iv = new byte[ivSize];
- SecureRandom random = new SecureRandom();
- random.nextBytes(iv);
- IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
- SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
- KeySpec spec = new PBEKeySpec(pass, bytes, 65536, 128);
- SecretKey tmp = factory.generateSecret(spec);
- SecretKeySpec skey = new SecretKeySpec(tmp.getEncoded(), "AES");
- cipher.init(Cipher.ENCRYPT_MODE, skey, ivParameterSpec);
- byte[] encrypted = cipher.doFinal(toEncrypt);
- // Combine IV and encrypted part.
- byte[] encryptedIVAndText = new byte[ivSize + encrypted.length];
- System.arraycopy(iv, 0, encryptedIVAndText, 0, ivSize);
- System.arraycopy(encrypted, 0, encryptedIVAndText, ivSize, encrypted.length);
- return encryptedIVAndText;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement