

代码实例:
package com.demo;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import com.sun.xml.internal.messaging.saaj.util.Base64;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class aesdemo {
private static String name = "xiaoming";
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
//1.获取密钥
KeyGenerator aes = KeyGenerator.getInstance("AES");
aes.init(128);
SecretKey secretKey = aes.generateKey();
byte[] encoded = secretKey.getEncoded();
//2.密钥转换
Key key = new SecretKeySpec(encoded, "AES");
//3.加密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[] bytes = cipher.doFinal(name.getBytes());
System.out.println(new BASE64Encoder().encode(bytes));//加密完成后,再使用base64进行加密
//4.解密
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] bytes1 = cipher.doFinal(bytes);
System.out.println(new String(bytes1));
}
}
下面来放一张基于AES加解密的流程图。

PBE
PBE算法(Password Based Encryption,基于口令加密)是一种基于口令的加密算法,其特点是使用口令代替了密钥,而口令由用户自己掌管,采用随机数杂凑多重加密等方法保证数据的安全性。PBE算法在加密过程中并不是直接使用口令来加密,而是加密的密钥由口令生成,这个功能由PBE算法中的KDF函数完成。KDF函数的实现过程为:将用户输入的口令首先通过“盐”(salt)的扰乱产生准密钥,再将准密钥经过散列函数多次迭代后生成最终加密密钥,密钥生成后,PBE算法再选用对称加密算法对数据进行加密,可以选择DES、3DES、RC5等对称加密算法

以上这张图是PBE算法的实现方式

代码实例:
package com.demo;
import com.sun.xml.internal.messaging.saaj.util.Base64;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
public class pbedemo {
private static String name = "xiaoming";
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, BadPaddingException, IllegalBlockSizeException {
//1.初始化盐
SecureRandom secureRandom = new SecureRandom();
byte[] salt = secureRandom.generateSeed(8);
//2. 获取密钥
String password = "123456";
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
Key key = factory.generateSecret(pbeKeySpec);
//3.加密
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance("PBEWITHMD5andDES");
cipher.init(Cipher.ENCRYPT_MODE,key,pbeParameterSpec);
byte[] bytes = cipher.doFinal(name.getBytes());
System.out.println(new BASE64Encoder().encode(bytes));
//4.解密
cipher.init(Cipher.DECRYPT_MODE,key,pbeParameterSpec);
byte[] res = cipher.doFinal(bytes);
System.out.println(new String(res));
}
}