java数字证书_Java数字证书对文件/加密/解密/签名/校验签名

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import java.security.KeyStore;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.Signature;

import java.security.cert.Certificate;

import java.security.cert.CertificateFactory;

import java.security.cert.X509Certificate;

import java.util.Date;

import javax.crypto.Cipher;/**

*

* 数字签名/加密解密工具包

*

*

* @author IceWee

* @date 2012-4-26

* @version 1.0*/public class CertificateUtils {/**

* Java密钥库(Java 密钥库,JKS)KEY_STORE*/public static final String KEY_STORE= "JKS";

public static final String X509= "X.509";/**

* 文件读取缓冲区大小*/private static finalint CACHE_SIZE = 2048;/**

* 最大文件加密块*/private static finalint MAX_ENCRYPT_BLOCK = 117;/**

* 最大文件解密块*/private static finalint MAX_DECRYPT_BLOCK = 128;/**

*

* 根据密钥库获得私钥

*

*

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/private static PrivateKey getPrivateKey(String keyStorePath, String alias, String password)

throws Exception {

KeyStore keyStore=getKeyStore(keyStorePath, password);

PrivateKey privateKey=(PrivateKey) keyStore.getKey(alias, password.toCharArray());returnprivateKey;

}/**

*

* 获得密钥库

*

*

* @param keyStorePath 密钥库存储路径

* @param password 密钥库密码

* @return

* @throws Exception*/private static KeyStore getKeyStore(String keyStorePath, String password)

throws Exception {

FileInputStreamin = newFileInputStream(keyStorePath);

KeyStore keyStore=KeyStore.getInstance(KEY_STORE);

keyStore.load(in, password.toCharArray());in.close();returnkeyStore;

}/**

*

* 根据证书获得公钥

*

*

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/private static PublicKey getPublicKey(String certificatePath)

throws Exception {

Certificate certificate=getCertificate(certificatePath);

PublicKey publicKey=certificate.getPublicKey();returnpublicKey;

}/**

*

* 获得证书

*

*

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/private static Certificate getCertificate(String certificatePath)

throws Exception {

CertificateFactory certificateFactory=CertificateFactory.getInstance(X509);

FileInputStreamin = newFileInputStream(certificatePath);

Certificate certificate= certificateFactory.generateCertificate(in);in.close();returncertificate;

}/**

*

* 根据密钥库获得证书

*

*

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/private static Certificate getCertificate(String keyStorePath, String alias, String password)

throws Exception {

KeyStore keyStore=getKeyStore(keyStorePath, password);

Certificate certificate=keyStore.getCertificate(alias);returncertificate;

}/**

*

* 私钥加密

*

*

* @param data 源数据

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/public staticbyte[] encryptByPrivateKey(byte[] data, String keyStorePath, String alias, String password)

throws Exception {//取得私钥

PrivateKey privateKey =getPrivateKey(keyStorePath, alias, password);

Cipher cipher=Cipher.getInstance(privateKey.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, privateKey);int inputLen =data.length;

ByteArrayOutputStream out= newByteArrayOutputStream();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();returnencryptedData;

}/**

*

* 文件私钥加密

*

*

* 过大的文件可能会导致内存溢出

* >

*

* @param filePath 文件路径

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/public staticbyte[] encryptFileByPrivateKey(String filePath, String keyStorePath, String alias, String password)

throws Exception {byte[] data =fileToByte(filePath);returnencryptByPrivateKey(data, keyStorePath, alias, password);

}/**

*

* 文件加密

*

*

* @param srcFilePath 源文件

* @param destFilePath 加密后文件

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @throws Exception*/public staticvoidencryptFileByPrivateKey(String srcFilePath, String destFilePath, String keyStorePath, String alias, String password)

throws Exception {//取得私钥

PrivateKey privateKey =getPrivateKey(keyStorePath, alias, password);

Cipher cipher=Cipher.getInstance(privateKey.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, privateKey);

File srcFile= newFile(srcFilePath);

FileInputStreamin = newFileInputStream(srcFile);

File destFile= newFile(destFilePath);if (!destFile.getParentFile().exists()) {

destFile.getParentFile().mkdirs();

}

destFile.createNewFile();

OutputStream out= newFileOutputStream(destFile);byte[] data = new byte[MAX_ENCRYPT_BLOCK];byte[] encryptedData; //加密块

while (in.read(data) != -1) {

encryptedData=cipher.doFinal(data);

out.write(encryptedData,0, encryptedData.length);

out.flush();

}

out.close();in.close();

}/**

*

* 文件加密成BASE64编码的字符串

*

*

* @param filePath 文件路径

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/public static String encryptFileToBase64ByPrivateKey(String filePath, String keyStorePath, String alias, String password)

throws Exception {byte[] encryptedData =encryptFileByPrivateKey(filePath, keyStorePath, alias, password);returnBase64Utils.encode(encryptedData);

}/**

*

* 私钥解密

*

*

* @param encryptedData 已加密数据

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/public staticbyte[] decryptByPrivateKey(byte[] encryptedData, String keyStorePath, String alias, String password)

throws Exception {//取得私钥

PrivateKey privateKey =getPrivateKey(keyStorePath, alias, password);

Cipher cipher=Cipher.getInstance(privateKey.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, privateKey);//解密byte数组最大长度限制: 128

int inputLen =encryptedData.length;

ByteArrayOutputStream out= newByteArrayOutputStream();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();returndecryptedData;

}/**

*

* 公钥加密

*

*

* @param data 源数据

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/public staticbyte[] encryptByPublicKey(byte[] data, String certificatePath)

throws Exception {//取得公钥

PublicKey publicKey =getPublicKey(certificatePath);

Cipher cipher=Cipher.getInstance(publicKey.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, publicKey);int inputLen =data.length;

ByteArrayOutputStream out= newByteArrayOutputStream();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();returnencryptedData;

}/**

*

* 公钥解密

*

*

* @param encryptedData 已加密数据

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/public staticbyte[] decryptByPublicKey(byte[] encryptedData, String certificatePath)

throws Exception {

PublicKey publicKey=getPublicKey(certificatePath);

Cipher cipher=Cipher.getInstance(publicKey.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, publicKey);int inputLen =encryptedData.length;

ByteArrayOutputStream out= newByteArrayOutputStream();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();returndecryptedData;

}/**

*

* 文件解密

*

*

* @param srcFilePath 源文件

* @param destFilePath 目标文件

* @param certificatePath 证书存储路径

* @throws Exception*/public staticvoiddecryptFileByPublicKey(String srcFilePath, String destFilePath, String certificatePath)

throws Exception {

PublicKey publicKey=getPublicKey(certificatePath);

Cipher cipher=Cipher.getInstance(publicKey.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, publicKey);

File srcFile= newFile(srcFilePath);

FileInputStreamin = newFileInputStream(srcFile);

File destFile= newFile(destFilePath);if (!destFile.getParentFile().exists()) {

destFile.getParentFile().mkdirs();

}

destFile.createNewFile();

OutputStream out= newFileOutputStream(destFile);byte[] data = new byte[MAX_DECRYPT_BLOCK];byte[] decryptedData; //解密块

while (in.read(data) != -1) {

decryptedData=cipher.doFinal(data);

out.write(decryptedData,0, decryptedData.length);

out.flush();

}

out.close();in.close();

}/**

*

* 生成数据签名

*

*

* @param data 源数据

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/public staticbyte[] sign(byte[] data, String keyStorePath, String alias, String password)

throws Exception {//获得证书

X509Certificate x509Certificate =(X509Certificate) getCertificate(keyStorePath, alias, password);//获取私钥

KeyStore keyStore =getKeyStore(keyStorePath, password);//取得私钥

PrivateKey privateKey =(PrivateKey) keyStore.getKey(alias, password.toCharArray());//构建签名

Signature signature =Signature.getInstance(x509Certificate.getSigAlgName());

signature.initSign(privateKey);

signature.update(data);returnsignature.sign();

}/**

*

* 生成数据签名并以BASE64编码

*

*

* @param data 源数据

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/public static String signToBase64(byte[] data, String keyStorePath, String alias, String password)

throws Exception {returnBase64Utils.encode(sign(data, keyStorePath, alias, password));

}/**

*

* 生成文件数据签名(BASE64)

*

*

* 需要先将文件私钥加密,再根据加密后的数据生成签名(BASE64),适用于小文件

*

*

* @param filePath 源文件

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/public static String signFileToBase64WithEncrypt(String filePath, String keyStorePath, String alias, String password)

throws Exception {byte[] encryptedData =encryptFileByPrivateKey(filePath, keyStorePath, alias, password);returnsignToBase64(encryptedData, keyStorePath, alias, password);

}/**

*

* 生成文件签名

*

*

* 注意:

* 方法中使用了FileChannel,其巨大Bug就是不会释放文件句柄,导致签名的文件无法操作(移动或删除等)

* 该方法已被generateFileSign取代

*

*

* @param filePath 文件路径

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return

* @throws Exception*/@Deprecated

public staticbyte[] signFile(String filePath, String keyStorePath, String alias, String password)

throws Exception {byte[] sign = new byte[0];//获得证书

X509Certificate x509Certificate =(X509Certificate) getCertificate(keyStorePath, alias, password);//获取私钥

KeyStore keyStore =getKeyStore(keyStorePath, password);//取得私钥

PrivateKey privateKey =(PrivateKey) keyStore.getKey(alias, password.toCharArray());//构建签名

Signature signature =Signature.getInstance(x509Certificate.getSigAlgName());

signature.initSign(privateKey);

File file= newFile(filePath);if(file.exists()) {

FileInputStreamin = newFileInputStream(file);

FileChannel fileChannel= in.getChannel();

MappedByteBuffer byteBuffer= fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());

signature.update(byteBuffer);

fileChannel.close();in.close();

sign=signature.sign();

}returnsign;

}/**

*

* 生成文件数字签名

*

*

*

* 注意:

* 生成签名时update的byte数组大小和验证签名时的大小应相同,否则验证无法通过

*

*

* @param filePath

* @param keyStorePath

* @param alias

* @param password

* @return

* @throws Exception*/public staticbyte[] generateFileSign(String filePath, String keyStorePath, String alias, String password)

throws Exception {byte[] sign = new byte[0];//获得证书

X509Certificate x509Certificate =(X509Certificate) getCertificate(keyStorePath, alias, password);//获取私钥

KeyStore keyStore =getKeyStore(keyStorePath, password);//取得私钥

PrivateKey privateKey =(PrivateKey) keyStore.getKey(alias, password.toCharArray());//构建签名

Signature signature =Signature.getInstance(x509Certificate.getSigAlgName());

signature.initSign(privateKey);

File file= newFile(filePath);if(file.exists()) {

FileInputStreamin = newFileInputStream(file);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = in.read(cache)) != -1) {

signature.update(cache,0, nRead);

}in.close();

sign=signature.sign();

}returnsign;

}/**

*

* 文件签名成BASE64编码字符串

*

*

* @param filePath

* @param keyStorePath

* @param alias

* @param password

* @return

* @throws Exception*/public static String signFileToBase64(String filePath, String keyStorePath, String alias, String password)

throws Exception {returnBase64Utils.encode(generateFileSign(filePath, keyStorePath, alias, password));

}/**

*

* 验证签名

*

*

* @param data 已加密数据

* @param sign 数据签名[BASE64]

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/public staticboolean verifySign(byte[] data, String sign, String certificatePath)

throws Exception {//获得证书

X509Certificate x509Certificate =(X509Certificate) getCertificate(certificatePath);//获得公钥

PublicKey publicKey =x509Certificate.getPublicKey();//构建签名

Signature signature =Signature.getInstance(x509Certificate.getSigAlgName());

signature.initVerify(publicKey);

signature.update(data);returnsignature.verify(Base64Utils.decode(sign));

}/**

*

* 校验文件完整性

*

*

* 鉴于FileChannel存在的巨大Bug,该方法已停用,被validateFileSign取代

*

*

* @param filePath 文件路径

* @param sign 数据签名[BASE64]

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/@Deprecated

public staticbooleanverifyFileSign(String filePath, String sign, String certificatePath)

throws Exception {boolean result = false;//获得证书

X509Certificate x509Certificate =(X509Certificate) getCertificate(certificatePath);//获得公钥

PublicKey publicKey =x509Certificate.getPublicKey();//构建签名

Signature signature =Signature.getInstance(x509Certificate.getSigAlgName());

signature.initVerify(publicKey);

File file= newFile(filePath);if(file.exists()) {byte[] decodedSign =Base64Utils.decode(sign);

FileInputStreamin = newFileInputStream(file);

FileChannel fileChannel= in.getChannel();

MappedByteBuffer byteBuffer= fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());

signature.update(byteBuffer);in.close();

result=signature.verify(decodedSign);

}returnresult;

}/**

*

* 校验文件签名

*

*

* @param filePath

* @param sign

* @param certificatePath

* @return

* @throws Exception*/public staticbooleanvalidateFileSign(String filePath, String sign, String certificatePath)

throws Exception {boolean result = false;//获得证书

X509Certificate x509Certificate =(X509Certificate) getCertificate(certificatePath);//获得公钥

PublicKey publicKey =x509Certificate.getPublicKey();//构建签名

Signature signature =Signature.getInstance(x509Certificate.getSigAlgName());

signature.initVerify(publicKey);

File file= newFile(filePath);if(file.exists()) {byte[] decodedSign =Base64Utils.decode(sign);

FileInputStreamin = newFileInputStream(file);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = in.read(cache)) != -1) {

signature.update(cache,0, nRead);

}in.close();

result=signature.verify(decodedSign);

}returnresult;

}/**

*

* BASE64解码->签名校验

*

*

* @param base64String BASE64编码字符串

* @param sign 数据签名[BASE64]

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/public staticbooleanverifyBase64Sign(String base64String, String sign, String certificatePath)

throws Exception {byte[] data =Base64Utils.decode(base64String);returnverifySign(data, sign, certificatePath);

}/**

*

* BASE64解码->公钥解密-签名校验

*

*

*

* @param base64String BASE64编码字符串

* @param sign 数据签名[BASE64]

* @param certificatePath 证书存储路径

* @return

* @throws Exception*/public staticbooleanverifyBase64SignWithDecrypt(String base64String, String sign, String certificatePath)

throws Exception {byte[] encryptedData =Base64Utils.decode(base64String);byte[] data =decryptByPublicKey(encryptedData, certificatePath);returnverifySign(data, sign, certificatePath);

}/**

*

* 文件公钥解密->签名校验

*

*

* @param encryptedFilePath 加密文件路径

* @param sign 数字证书[BASE64]

* @param certificatePath

* @return

* @throws Exception*/public staticbooleanverifyFileSignWithDecrypt(String encryptedFilePath, String sign, String certificatePath)

throws Exception {byte[] encryptedData =fileToByte(encryptedFilePath);byte[] data =decryptByPublicKey(encryptedData, certificatePath);returnverifySign(data, sign, certificatePath);

}/**

*

* 校验证书当前是否有效

*

*

* @param certificate 证书

* @return*/public staticbooleanverifyCertificate(Certificate certificate) {return verifyCertificate(newDate(), certificate);

}/**

*

* 验证证书是否过期或无效

*

*

* @param date 日期

* @param certificate 证书

* @return*/public staticbooleanverifyCertificate(Date date, Certificate certificate) {boolean isValid = true;try{

X509Certificate x509Certificate=(X509Certificate) certificate;

x509Certificate.checkValidity(date);

}catch(Exception e) {

isValid= false;

}returnisValid;

}/**

*

* 验证数字证书是在给定的日期是否有效

*

*

* @param date 日期

* @param certificatePath 证书存储路径

* @return*/public staticbooleanverifyCertificate(Date date, String certificatePath) {

Certificate certificate;try{

certificate=getCertificate(certificatePath);returnverifyCertificate(certificate);

}catch(Exception e) {

e.printStackTrace();return false;

}

}/**

*

* 验证数字证书是在给定的日期是否有效

*

*

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return*/public staticbooleanverifyCertificate(Date date, String keyStorePath, String alias, String password) {

Certificate certificate;try{

certificate=getCertificate(keyStorePath, alias, password);returnverifyCertificate(certificate);

}catch(Exception e) {

e.printStackTrace();return false;

}

}/**

*

* 验证数字证书当前是否有效

*

*

* @param keyStorePath 密钥库存储路径

* @param alias 密钥库别名

* @param password 密钥库密码

* @return*/public staticbooleanverifyCertificate(String keyStorePath, String alias, String password) {return verifyCertificate(newDate(), keyStorePath, alias, password);

}/**

*

* 验证数字证书当前是否有效

*

*

* @param certificatePath 证书存储路径

* @return*/public staticbooleanverifyCertificate(String certificatePath) {return verifyCertificate(newDate(), certificatePath);

}/**

*

* 文件转换为byte数组

*

*

* @param filePath 文件路径

* @return

* @throws Exception*/public staticbyte[] fileToByte(String filePath) throws Exception {byte[] data = new byte[0];

File file= newFile(filePath);if(file.exists()) {

FileInputStreamin = newFileInputStream(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();

}returndata;

}/**

*

* 二进制数据写文件

*

*

* @param bytes 二进制数据

* @param filePath 文件生成目录*/public staticvoid byteArrayToFile(byte[] bytes, String filePath) throws Exception {

InputStreamin = newByteArrayInputStream(bytes);

File destFile= newFile(filePath);if (!destFile.getParentFile().exists()) {

destFile.getParentFile().mkdirs();

}

destFile.createNewFile();

OutputStream out= newFileOutputStream(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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值