俗话说的好前人种树后人乘凉,最近用到加密解密相关,根据前辈们的文章做个记录,方便以后直接使用
MD5加密
package com.qingxu.extension.util;
import java.security.MessageDigest;
/**
* 编码工具类
* Created by Administrator on 2018/1/25.
*/
public class MD5Util {
/**
* MD5加密
*/
public static String MD5(String key) {
char hexDigits[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
try {
byte[] btInput = key.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
}
其中hexDigits[] 中的字符大小写可以根据自己需要调换
二、Base64 加密解密,因为java新增的很好实现
package com.qingxu.extension.util;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.*;
/**
* BASE64编码解码工具包
* 依赖javabase64-1.3.1.jar
*/
public class Base64Utils {
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/**
* BASE64字符串解码为二进制数据
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
/**
* 二进制数据编码为BASE64字符串
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
/**
* 将文件编码为BASE64字符串
* 大文件慎用,可能会导致内存溢出
* @param filePath
* 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/**
* BASE64字符串转回文件
* @param filePath
* 文件绝对路径
* @param base64
* 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/**
* 文件转换为二进制数组
* @param filePath
* 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/**
* 二进制数据写文件
* @param bytes
* 二进制数据
* @param filePath
* 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
三、RSA加密
package com.qingxu.extension.encode;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
/**
* RSA公钥/私钥/签名工具包
* 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
*
*/
public class RSAUtils {
/**
* 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* 签名算法MD5withRSA
*/
public static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
/**
* 获取公钥的key
*/
private static final String PUBLIC_KEY = "RSAPublicKey";
/**
* 获取私钥的key
*/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 生成密钥对(公钥和私钥)
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 用私钥对信息生成数字签名
* @param data 已加密数据
* @param privateKey 私钥(BASE64编码)
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64Utils.encode(signature.sign());
}
/**
* 校验数字签名
* @param data 已加密数据
* @param publicKey 公钥(BASE64编码)
* @param sign 数字签名
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64Utils.decode(sign));
}
/**
* 私钥解密
* @param encryptedData 已加密数据
* @param privateKey 私钥(BASE64编码)
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
* 公钥解密
* @param encryptedData 已加密数据
* @param publicKey 公钥(BASE64编码)
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
* 公钥加密
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* 私钥加密
* @param data 源数据
* @param privateKey 私钥(BASE64编码)
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* 获取私钥
* @param keyMap 密钥对
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64Utils.encode(key.getEncoded());
}
/**
* 获取公钥
* @param keyMap 密钥对
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64Utils.encode(key.getEncoded());
}
}
其中的签名算法可以根据自己需求做改动,在底层源码中有记载四、示例
package com.qingxu.extension.encode;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class Rsa {
private String priKey;
private String pubKey;
public static void main(String[] args) {
Rsa rsa = new Rsa();
String str = "我要加密这段文字。";
System.out.println("原文:"+"我要加密这段文字。");
String crypt = rsa.encryptByPrivateKey(str);
System.out.println("私钥加密密文:"+crypt);
String result = rsa.decryptByPublicKey(crypt);
System.out.println("原文:"+result);
System.out.println("---");
str = "我要加密这段文字。";
System.out.println("原文:"+"我要加密这段文字。");
crypt = rsa.encryptByPublicKey(str);
System.out.println("公钥加密密文:"+crypt);
result = rsa.decryptByPrivateKey(crypt);
System.out.println("原文:"+result);
System.out.println("---");
str = "我要签名这段文字。";
System.out.println("原文:"+str);
String str1 = rsa.signByPrivateKey(str);
System.out.println("签名结果:"+str1);
if(rsa.verifyByPublicKey(str1, str)){
System.out.println("成功");
} else {
System.out.println("失败");
}
}
public Rsa(){
priKey = readStringFromFile("java_private.pem");
pubKey = readStringFromFile("java_public.pem");
}
/**
* 使用私钥加密
* @see decByPriKey
*/
public String encryptByPrivateKey(String data) {
// 加密
String str = "";
try {
byte[] pribyte = base64decode(priKey.trim());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);
KeyFactory fac = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);
Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c1.init(Cipher.ENCRYPT_MODE, privateKey);
str = base64encode(c1.doFinal(data.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 使用私钥解密
* @see decByPriKey
*/
public String decryptByPrivateKey(String data) {
// 加密
String str = "";
try {
byte[] pribyte = base64decode(priKey.trim());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);
KeyFactory fac = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);
Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c1.init(Cipher.DECRYPT_MODE, privateKey);
byte[] temp = c1.doFinal(base64decode(data));
str = new String(temp);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 使用公钥加密
* @see decByPriKey
*/
public String encryptByPublicKey(String data) {
// 加密
String str = "";
try {
byte[] pubbyte = base64decode(pubKey.trim());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte);
KeyFactory fac = KeyFactory.getInstance("RSA");
RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);
Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c1.init(Cipher.ENCRYPT_MODE, rsaPubKey);
str = base64encode(c1.doFinal(data.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 使用公钥解密
* @see decByPriKey
*/
public String decryptByPublicKey(String data) {
// 加密
String str = "";
try {
byte[] pubbyte = base64decode(pubKey.trim());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte);
KeyFactory fac = KeyFactory.getInstance("RSA");
RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);
Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c1.init(Cipher.DECRYPT_MODE, rsaPubKey);
byte[] temp = c1.doFinal(base64decode(data));
str = new String(temp);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 本方法使用SHA1withRSA签名算法产生签名
* @param String src 签名的原字符串
* @return String 签名的返回结果(16进制编码)。当产生签名出错的时候,返回null。
*/
public String signByPrivateKey(String src) {
try {
Signature sigEng = Signature.getInstance("SHA1withRSA");
byte[] pribyte = base64decode(priKey.trim());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);
KeyFactory fac = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);
sigEng.initSign(privateKey);
sigEng.update(src.getBytes());
byte[] signature = sigEng.sign();
return base64encode(signature);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 使用共钥验证签名
* @param sign
* @param src
* @return
*/
public boolean verifyByPublicKey(String sign, String src) {
try {
Signature sigEng = Signature.getInstance("SHA1withRSA");
byte[] pubbyte = base64decode(pubKey.trim());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte);
KeyFactory fac = KeyFactory.getInstance("RSA");
RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);
sigEng.initVerify(rsaPubKey);
sigEng.update(src.getBytes());
byte[] sign1 = base64decode(sign);
return sigEng.verify(sign1);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* base64加密
* @param bstr
* @return
*/
@SuppressWarnings("restriction")
private String base64encode(byte[] bstr) {
String str = new sun.misc.BASE64Encoder().encode(bstr);
str = str.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
return str;
}
/**
* base64解密
* @param str
* @return byte[]
*/
@SuppressWarnings("restriction")
private byte[] base64decode(String str) {
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}
return bt;
}
/**
* 从文件中读取所有字符串
* @param fileName
* @return String
*/
private String readStringFromFile(String fileName){
StringBuffer str = new StringBuffer();
try {
File file = new File(fileName);
FileReader fr = new FileReader(file);
char[] temp = new char[1024];
while (fr.read(temp) != -1) {
str.append(temp);
}
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str.toString();
}
}