Created
August 12, 2016 10:06
-
-
Save JobsDong/56a7a4ede2044e4fffe5437cf6da2770 to your computer and use it in GitHub Desktop.
aes java encrypt
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
class AES { | |
public static void main(String[] args) throws NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, IOException, InvalidKeyException, Base64DecodingException, InvalidAlgorithmParameterException { | |
String content = "this is a test"; | |
String password = "1234567812345678"; | |
System.out.println("before:" + content); | |
// encrypt | |
String encrypt = encode(content, "1234567812345678", password); | |
System.out.println("encrypt:" + encrypt); | |
// decrypt | |
String decrypt = decode(encrypt, "1234567812345678", password); | |
System.out.println("decrypt:" + decrypt); | |
} | |
public static final String decode(String content, String initVector, String password) throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException, Base64DecodingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { | |
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes()); | |
SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES"); | |
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); | |
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); | |
byte[] encrypted = new BASE64Decoder().decodeBuffer(content); | |
byte[] original = cipher.doFinal(encrypted); | |
return new String(original); | |
} | |
public static final String encode(String content, String initVector, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { | |
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); | |
int blockSize = cipher.getBlockSize(); | |
byte[] bytes = content.getBytes(); | |
int plainTextLength = bytes.length; | |
if (plainTextLength % blockSize != 0) { | |
plainTextLength = plainTextLength + (blockSize - (plainTextLength % blockSize)); | |
} | |
byte[] plainText = new byte[plainTextLength]; | |
System.arraycopy(bytes, 0, plainText, 0, bytes.length); | |
SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES"); | |
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes()); | |
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); | |
byte[] encrypted = cipher.doFinal(plainText); | |
return new BASE64Encoder().encode(encrypted); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment