对称算法及AES算法简介:https://blog.csdn.net/ws_kfxd/article/details/105818257
package test;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AES {
public static void main(String[] args) {
String key = "1234567890123456";//定义密钥
String context = "这是要加密的明文!!!123456***";
//处理密钥(不一定用这种方法)
byte[] finKey = dealKey(key);
//加密
String ciphertext = encrypt(context,finKey);
//解密
String plaintext = decrypt(ciphertext,finKey);
//输出数据
System.out.print("处理后的密钥:");
for (int i = 0; i < finKey.length; i++) {
System.out.print(finKey[i]);
}
System.out.println();
System.out.println("加密后:"+ciphertext);
System.out.println("解密后:"+plaintext);
}
/**
* 处理密钥
* @param key初始密钥
* @return
*/
public static byte[] dealKey(String key) {
//生成安全随机数
SecureRandom secureRandom = null;
byte[] enCodeFormat = null;
try {
secureRandom = SecureRandom.getInstance("SHA1PRNG");//指定算法,目前只支持SHA1PRNG
secureRandom.setSeed(key.getBytes());//设置种子,替代系统默认随机源
KeyGenerator kgen = KeyGenerator.getInstance("AES");//构造密钥生成器,指定为AES算法,不区分大小写
kgen.init(128, secureRandom);//通过指定大小和随机源的方式产生
SecretKey secretKey = kgen.generateKey();//生成秘钥,返回SecertKey对象
enCodeFormat = secretKey.getEncoded();
} catch (Exception e) {
e.printStackTrace();
}
return enCodeFormat;
}
/**
* AES加密并使用base64编码
* @param context明文
* @param finKey密钥
* @return
*/
public static String encrypt(String context,byte[] key) {
SecretKeySpec skeySpec = null;
Cipher cipher = null;
byte[] encrypted = null;
try {
skeySpec = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encrypted = cipher.doFinal(context.getBytes("utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
return new Base64().encodeToString(encrypted);//使用base64编码
}
/**
* AES解密
* @param context base64编码后的密文
* @param finKey密钥
* @return
*/
public static String decrypt(String context,byte[] key) {
SecretKeySpec skeySpec = null;
Cipher cipher = null;
byte[] encrypted = new Base64().decode(context);//base64解码
byte[] encryptedRet = null;
String ret = null;
try {
skeySpec = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
encryptedRet = cipher.doFinal(encrypted);
ret = new String(encryptedRet,"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
}
运行结果: