DEC加密和RSA加密(Java)
记录两种常用的加密方法
1.DES对称加密
( 加密解密用同一个密钥 )
说明:在开发中,url 地址栏有些敏感数据( 如一些id),不方便展示,故将这些字段加密成密文。
DesUtil工具类 ( 很详细,直接用)
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.Key;
import java.util.Base64;
/**
* @program: tec
* @description: Des加密
* @author: Kiki
* @create: 2021-12-14 16:52
*/
public class DesUtil {
/**
* 偏移变量,固定占8位字节
*/
private final static String IV_PARAMETER = "91370100";
/**
* 密钥算法
*/
private static final String ALGORITHM = "DES";
/**
* 加密/解密算法-工作模式-填充模式
*/
private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
/**
* 默认编码
*/
private static final String CHARSET = "utf-8";
/**
* 生成key
*
* @param password
* @return
* @throws Exception
*/
private static Key generateKey(String password) throws Exception {
DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
return keyFactory.generateSecret(dks);
}
/**
* DES加密字符串
*
* @param password 加密密码,长度不能够小于8位
* @param data 待加密字符串
* @return 加密后内容
*/
public static String encrypt(String password, String data) {
if (password== null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
if (data == null)
return null;
try {
Key secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
//JDK1.8及以上可直接使用Base64,JDK1.7及以下可以使用BASE64Encoder
//Android平台可以使用android.util.Base64
return new String(Base64.getUrlEncoder().encode(bytes));
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
/**
* DES解密字符串
*
* @param password 解密密码,长度不能够小于8位
* @param data 待解密字符串
* @return 解密后内容
*/
public static String decrypt(String password, String data) {
if (password== null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
if (data == null)
return null;
try {
Key secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return new String(cipher.doFinal(Base64.getUrlDecoder().decode(data.getBytes(CHARSET))), CHARSET);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
}
代码很详细,不过有个小细节。在加密 (encrypt) 和解密 (decrypt) 时,如果是url 地址栏。则方法里调用 getUrlEncoder 和 getUrlDecoder。
2.RSA非对称加密
( 该处是 公钥加密 私钥解密 )
在前后台交互的过程中,一些敏感数据不宜展示,很容易被抓包获取。比如在注册的表单提交时,账号密码就需要在前端加密,后端解密。
具体用到的 RSAUtil 和 jsencrypt.min.js(有点多不贴代码了,随便网上下个就行)
RSAUtil工具类 (注意Base64和IOUtils 需要maven 的 pom.xml文件引入或者导jar包)
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
/**
* @program: echarts
* @description:
* @author: Kiki
* @create: 2021-12-30 23:21
*/
public class RSAUtil {
public static final String CHARSET = "UTF-8";
public static final String RSA_ALGORITHM = "RSA";
private static final KeyPair keyPair = initKey();
/**
* 初始化方法,产生key pair,提供provider和random
* @return KeyPair instance
*/
private static KeyPair initKey() {
try {
//添加provider
Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(provider);
//产生用于安全加密的随机数
SecureRandom random = new SecureRandom();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);
generator.initialize(1024, random);
return generator.generateKeyPair();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
/**
* 产生public key(公钥)
* @return public key字符串
*/
public static String generateBase64PublicKey() {
PublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
return new String(Base64.encodeBase64(publicKey.getEncoded()));
}
/**
* 产生private key(私钥)
*
* @return private key字符串
*/
public static String generateBase64PrivateKey(){
PrivateKey privateKey = keyPair.getPrivate();
return new String(Base64.encodeBase64(privateKey.getEncoded()));
}
/**
* 私钥解密
* @param data 加密的数据
* @param privateKeyStr 密钥
* @return
*/
public static String privateDecrypt(String data,String privateKeyStr){
try{
RSAPrivateKey privateKey = getPrivateKey(privateKeyStr);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
}catch(Exception e){
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 得到私钥
* @param privateKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
//通过PKCS#8编码的Key指令获得私钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
int maxBlock = 0;
if(opmode == Cipher.DECRYPT_MODE){
maxBlock = keySize / 8;
}else{
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try{
while(datas.length > offSet){
if(datas.length-offSet > maxBlock){
buff = cipher.doFinal(datas, offSet, maxBlock);
}else{
buff = cipher.doFinal(datas, offSet, datas.length-offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
}catch(Exception e){
throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
}
具体使用
1.需加密字段的页面,调用 获取公钥私钥的方法,公钥返回给前台,私钥放在session中
/**
* 获取公钥(publicKey) 和私钥(base64PrivateKey)
* @param request
* @param response
*/
@RequestMapping("/getBase64PublicKey")
public void getBase64PublicKey(HttpServletRequest request, HttpServletResponse response){
PrintWriter writer;
try {
writer = response.getWriter();
String publicKey = RSAUtil.generateBase64PublicKey();
String base64PrivateKey = RSAUtil.generateBase64PrivateKey();
request.getSession().setAttribute("privateKeyStr",base64PrivateKey);
writer.write(publicKey);
} catch (IOException e) {
e.printStackTrace();
}
}
2.在js页面中,使用公钥publicKey对数据加密
var supBehaviorInfo = {};
//对 表单数据进行 RSA加密
function encryptionRSA() {
var encrypt = new JSEncrypt(); // 该对象来自 jsencrypt.min.js
encrypt.setPublicKey(publicKey); // publicKey(公钥) 从 /getBase64PublicKey 方法中获取
var entity = $("#registerInfo").serializeArray();
var data ;
for (var i = 0; i < entity.length; i++) {
if (entity[i].name == "userName" || entity[i].name == "userTel" || entity[i].name == "contactMail" || entity[i].name == "supPwd" || entity[i].name == "unitCode"){
data = encrypt.encrypt(entity[i]['value']) // 这里是对数据进行加密 entity[i]['value'] 是 要加密的数据 ,data 就是你加密之后的密文(数据传输就用这个)
supBehaviorInfo[entity[i].name] = data;
}else {
supBehaviorInfo[entity[i].name] = entity[i]['value'];
}
}
console.info(supBehaviorInfo)
return true;
}
3.解密
/**
* 添加供应商注册信息
*/
@RequestMapping("/getRegisterInformation")
@ResponseBody
public String getRegisterInformation(@RequestBody SupManageInfo supManageInfo,HttpServletRequest request){
// 从session中获取私钥
String privateKeyStr = (String) request.getSession().getAttribute("privateKeyStr");
boolean isInsert = false;
try {
//String userName = RSAUtil.privateDecrypt(supManageInfo.getUserName(), privateKeyStr)
// 解密 ,supManageInfo.getUserName() 加密后的密文,privateKeyStr 私钥 , userName 就是解密后的明文
supManageInfo.setUserName(RSAUtil.privateDecrypt(supManageInfo.getUserName(), privateKeyStr));
isInsert = aService.insert(supManageInfo);
} catch (Exception e) {
e.printStackTrace();
}
}