在日常接口对接中,不可避免的要与各种加密算法打交道,AES也是较为常用的一种加密算法,下面直接上代码
加密算法:
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/NoPadding";
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static String encrypt(String content, String password)
{
try
{
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
int blockSize = cipher.getBlockSize();
byte[] dataBytes = content.getBytes("UTF-8");
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0)
{
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(password.getBytes(), KEY_ALGORITHM);
IvParameterSpec ivspec = new IvParameterSpec(password.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
byte[] msgBytes = Base64.encodeBase64(encrypted);
return new String(msgBytes);
}
catch (Exception ex)
{
ex.printStackTrace();
return null;
}
}
解密算法:
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/NoPadding";
/**
* 解密
*
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static String decrpyt(String content, String password)
{
try
{
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
int blockSize = cipher.getBlockSize();
byte[] dataBytes = Base64.decodeBase64(content);
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0)
{
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(password.getBytes(), KEY_ALGORITHM);
IvParameterSpec ivspec = new IvParameterSpec(password.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return new String(encrypted, "UTF-8");
}
catch (Exception ex)
{
ex.printStackTrace();
return null;
}
}
测试代码:
public static void main(String[] args) {
String content = "abcdefg";
String password ="1234567812345678";
String result = encrypt(content, password);
System.out.println("加密结果为:"+result);
String decrpyt = decrpyt(result, password);
System.out.println("解密结果为:"+decrpyt);
}
测试结果:
需要注意的一点是此处采用加密方式是CBC,加密的key要为16位