AES
是一种对称加密算法(即加密和解密使用的是相同的密钥)对称加密的速度快但安全性较差
AES的分组长度是128bit,三种可选密钥长度128bit,192bit和256bit。
密文 = 明文 + 密钥
明文 = 密文 - 密钥
package com.test.ASE;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class AESTest {
public static void main(String[] args) throws Exception {
//明文
String clearText = "hello world!";
System.out.println("加密前:" + clearText);
//密钥(必须是8的倍数)
String originKey = "1234567812345678";
//加密
byte[] cigherText = desEncript(clearText, originKey);
System.out.println("加密后1:" + cigherText);
System.out.println("加密后2:" + new String(cigherText));
System.out.println("加密后3:" + Base64.getEncoder().encodeToString(cigherText));
//解密
byte[] overText = desDecript(cigherText, originKey);
System.out.println("解密后:" + new String(overText));
}
private static byte[] desDecript(byte[] cigherText, String originKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//1.获取加密算法工作类对象
Cipher cipher = Cipher.getInstance("AES");
//2.对加密工具类进行初始化
//mode:加密/解密模式
//key:对原始密钥处理后的密钥
SecretKeySpec key = getKey(originKey);
cipher.init(Cipher.DECRYPT_MODE, key);
//3.用加密工具类对象对明文进行加密
byte[] deFinal = cipher.doFinal(cigherText);
return deFinal;
}
/**
* @param clearText
* @param originKey
* @return
* @throws NoSuchPaddingException : 填充异常
* @throws NoSuchAlgorithmException : 没有此算法异常
* @throws InvalidKeyException : 无效的密钥异常
* <p>
* 加密运算:就是通过对比特位进行一些数值运算
*/
private static byte[] desEncript(String clearText, String originKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//1.获取加密算法工作类对象
Cipher cipher = Cipher.getInstance("AES");
//2.对加密工具类进行初始化
//mode:加密/解密模式
//key:对原始密钥处理后的密钥
SecretKeySpec key = getKey(originKey);
cipher.init(Cipher.ENCRYPT_MODE, key);
//3.用加密工具类对象对明文进行加密
byte[] deFinal = cipher.doFinal(clearText.getBytes());
return deFinal;
}
private static SecretKeySpec getKey(String originKey) {
SecretKeySpec key = new SecretKeySpec(originKey.getBytes(), "AES");
return key;
}
}