AES加密方法
package com.jefferson.utils.encrypt;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* @author 作者:jefferson
* @version 创建时间:2022年1月17日 上午15:30:36 类说明
*/
public class AESUti {
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @param iv 向量
* @return 加密后的字节数组
* @throws InvalidAlgorithmParameterException
*/
public static byte[] encrypt(String content, String password, String iv) throws Exception {
SecretKeySpec key = new SecretKeySpec(password.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
if (iv != null) {
IvParameterSpec ivp = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, key, ivp);// 初始化
} else {
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
}
byte[] result = cipher.doFinal(content.getBytes("UTF-8"));
return result; // 加密
}
/**
* 解密
*
* @param content
* 待解密内容
* @param password
* 解密密钥
* @return
* @throws Exception
*/
public static String decrypt(byte[] content, String password, String iv) throws Exception {
SecretKeySpec key = new SecretKeySpec(password.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
if (iv != null) {
IvParameterSpec ivp = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, key, ivp);// 初始化
} else {
cipher.init(Cipher.DECRYPT_MODE, key);
}
byte[] result = cipher.doFinal(content);
return new String(result, "UTF-8"); // 解密
}
public static void main(String[] args) throws Exception {
String realname = "张三";
String idcard = "";
String bankcard = "";
String mobile = "";
String password = "1234567896321456";
String openid = "";//用户的openid,在个人中心查询
String iv = Md5Util.getMD5(openid).substring(0, 16);
System.out.println("IV:" + iv);
System.out.println("realname:" + Base64.encode(encrypt(realname, password, iv)));
System.out.println("idcard:" + Base64.encode(encrypt(idcard, password, iv)));
System.out.println("bankcard:" + Base64.encode(encrypt(bankcard, password, iv)));
System.out.println("mobile:" + Base64.encode(encrypt(mobile, password, iv)));
System.out.println(decrypt(Base64.decode("1tXXjW7GLx9E1Ynr96R5O3v7oxOP8lM6IYtEQXF8BNc="), password, iv));
}
}
RSA加密方法
package com.jefferson.utils.encrypt.rsa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.jefferson.utils.test.net.Base64;
/**
* @author 作者:jefferson
* @version 创建时间:2022年1月27日
*/
public class RSAEncrypt2 {
/**
* 字节数据转字符串专用集合
*/
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static void main(String[] args) throws Exception {
String publicKey = "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA6jt4iPDyyK5pDqGDVbpJSThFXMkgG7eS0wbslACPpoy1b31XjbrHDRSD6KX8IeAeuHNuY+v8npGqqEjgI97H9VF/k7qoKjp+CMi+kWq7xUpPyXzwSXaHKuNZKD0Al+3va9QUvbswwYefNYoPk2G3whR+DrxCceBdKOkhhakOL5NN64LP86TemJCnyec0g2Nmp0YFlW1B+xZgsxEDs8ikW2RVSBWf6oAnfXSSj5TzOjkdwXbUhpobOELG3XW3KcDRYp9BSSFjG9zV7TxyumvjjZMJ1QsOnQbEuKlsTC6jdVTqWlFrkQY6/nO5+0+IN8DEhnXypPQLL/XS63GzuVlNJyjtEHjaJ1dvJc+KinPXPTTRd+x1dXyykJLY8iT69aUwID7RcTdHEoR65lUdm8cyQGqOE5mRkE4FZkad61aaKChy5dQeYqGOKM8Z61AVpqG1yvX31YCcKyZC/Fq2OQHbB3npHTSFC2XpxYWWZbsIa4l24iscpRl3gGbE7Dnmwp5XAgMBAAE=";
String param = "1234567896321456";//加密参数
byte[] encry = RSAEncrypt2.encrypt(loadPublicKeyByStr(publicKey), param.getBytes());
System.out.println(Base64.encode(encry));//打印加密结果base64
}
/**
* 从文件中输入流中加载公钥
*
* @param in
* 公钥输入流
* @throws Exception
* 加载公钥时产生的异常
*/
public static String loadPublicKeyByFile(String path) throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader(path + "/publicKey.keystore"));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
br.close();
return sb.toString();
} catch (IOException e) {
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥输入流为空");
}
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr
* 公钥数据字符串
* @throws Exception
* 加载公钥时产生的异常
*/
public static PublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode((publicKeyStr)));
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 公钥加密过程
*
* @param publicKey
* 公钥
* @param plainTextData
* 明文数据
* @return
* @throws Exception
* 加密过程中的异常信息
*/
public static byte[] encrypt(PublicKey publicKey, byte[] plainTextData) throws Exception {
if (publicKey == null) {
throw new Exception("加密公钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
}
}
/**
* 私钥加密过程
*
* @param privateKey
* 私钥
* @param plainTextData
* 明文数据
* @return
* @throws Exception
* 加密过程中的异常信息
*/
public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
if (privateKey == null) {
throw new Exception("加密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(plainTextData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
}
}
/**
* 私钥解密过程
*
* @param privateKey
* 私钥
* @param cipherData
* 密文数据
* @return 明文
* @throws Exception
* 解密过程中的异常信息
*/
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("解密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法");
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏");
}
}
/**
* 公钥解密过程
*
* @param publicKey
* 公钥
* @param cipherData
* 密文数据
* @return 明文
* @throws Exception
* 解密过程中的异常信息
*/
public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
if (publicKey == null) {
throw new Exception("解密公钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(cipherData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法");
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏");
}
}
}