Last active
August 29, 2015 14:04
-
-
Save lenamuit/b50a65a78d7643e37fce to your computer and use it in GitHub Desktop.
encryptAES with iv parameter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HogeCipher { | |
private static final String keyString = "<your secret key>" | |
public static String encryptString(String ivString, String input) | |
throws | |
java.io.UnsupportedEncodingException, | |
NoSuchAlgorithmException, | |
NoSuchPaddingException, | |
InvalidKeyException, | |
InvalidAlgorithmParameterException, | |
IllegalBlockSizeException, | |
BadPaddingException { | |
byte[] ivBytes; | |
ivBytes = new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; | |
if (ivString !=null) | |
ivBytes = ivString.getBytes("UTF-8"); | |
byte[] keyBytes = keyString.getBytes("UTF-8"); | |
return Base64.encodeToString(encryptAES(ivBytes, keyBytes, input.getBytes("UTF-8")), Base64.DEFAULT); | |
} | |
private static byte[] encryptAES(byte[] iv, byte[] key, byte[] enc) | |
throws | |
NoSuchAlgorithmException, | |
NoSuchPaddingException, | |
InvalidKeyException, | |
InvalidAlgorithmParameterException, | |
IllegalBlockSizeException, | |
BadPaddingException{ | |
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); | |
SecretKeySpec newKey = new SecretKeySpec(key, "AES"); | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); | |
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec); | |
return cipher.doFinal(enc); | |
} | |
private static byte[] decryptAES(byte[] iv, byte[] key, byte[] dec) | |
throws | |
NoSuchAlgorithmException, | |
NoSuchPaddingException, | |
InvalidKeyException, | |
InvalidAlgorithmParameterException, | |
IllegalBlockSizeException, | |
BadPaddingException{ | |
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); | |
SecretKeySpec newKey = new SecretKeySpec(key, "AES"); | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); | |
cipher.init(Cipher.DECRYPT_MODE, newKey); | |
return cipher.doFinal(dec); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment