java中加AES解密的方式比较简单,本示例展示CBC模式AES在java中的加解密
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
public class AesTest {
public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static final String KEY_ALGORITHM = "AES";
public static void main(String[] args) throws IOException {
//key必须是16的倍数,过长会报错,与jre环境local_policy.jar, US_export_policy.jar有关
SecretKey key = restoreSecretKey("14785236963698521478523696369852");
byte[] iv = "1236547896325474".getBytes();
System.out.println(iv.length);
byte[] encodeBytes = AesCbcEncode("Hello World!".getBytes(), key, iv);
byte[] decodeBytes = AesCbcDecode(encodeBytes, key, iv);
System.out.println(new String(decodeBytes));
}
/**
* 还原密钥
* @param keyWord
* @return
*/
public static SecretKey restoreSecretKey(String keyWord) {
SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), KEY_ALGORITHM);
return key;
}
public static byte[] AesCbcEncode(byte[] plainText, SecretKey key, byte[] IVParameter) {
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);
Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
return cipher.doFinal(plainText);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* CBC 解密
* @param decodedText
* @param key
* @param IVParameter
* @return
*/
public static byte[] AesCbcDecode(byte[] decodedText, SecretKey key, byte[] IVParameter) {
IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);
try {
Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
return cipher.doFinal(decodedText);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}