java代码如下:

package sign;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration; import javax.crypto.Cipher; @SuppressWarnings({ "rawtypes", "unused" })
public class UtilTools { private static final String PKCS12 = "PKCS12";
private static final String CHARSET = "utf-8";
private final static String CertType = "X.509";
public final static String TrustStoreType = "JKS";
private static final String SHA1WithRSA = "SHA1WithRSA";
private final static String MD5withRSA = "MD5withRSA";
private static final String SHA224WithRSA = "SHA224WithRSA";
private static final String SHA256WithRSA = "SHA256WithRSA";
private static final String SHA384WithRSA = "SHA384WithRSA";
private static final String SHA512WithRSA = "SHA512WithRSA";
private static final String RSA = "RSA";
private static final String ECB = "ECB";
private static final String PCKCS1PADDING = "PCKCS1Padding"; /**
* generate the signature
*
* @param source
* @param pfxPath
* @param password
* @return
* @throws Exception
*/
public static String generateSignature(String source, String pfxPath, String password) throws Exception {
byte[] signature = null;
PrivateKey privateKey = getPrivateKeyInstance(pfxPath, password);
Signature sig = Signature.getInstance(SHA1WithRSA);
sig.initSign(privateKey);
sig.update(source.getBytes(CHARSET));
signature = sig.sign();
return Base64Util.encode(signature);
} /**
* check the signature
*
* @param datasource
* @param sign
* @param certificatePath
* @return
* @throws Exception
*/
public static boolean checkSignature(String datasource, String sign, String certificatePath) throws Exception {
try {
X509Certificate x509Certificate = (X509Certificate) getInstance(certificatePath);
Signature signature = Signature.getInstance(SHA1WithRSA);
signature.initVerify(x509Certificate);
signature.update(datasource.getBytes(CHARSET));
return signature.verify(Base64Util.decode(sign));
} catch (Exception e) {
System.out.println(e.getMessage());
}
return false;
} /**
* 加载私钥
*
* @param strPfx
* @param strPassword
* @return
*/
private static PrivateKey getPrivateKeyInstance(String strPfx, String strPassword) throws Exception {
FileInputStream fis = null;
try {
KeyStore ks = KeyStore.getInstance(PKCS12);
fis = new FileInputStream(strPfx);
char[] chars = null;
if ((strPassword == null) || strPassword.trim().equals("")) {
chars = null;
} else {
chars = strPassword.toCharArray();
}
ks.load(fis, chars);
fis.close();
Enumeration enumas = ks.aliases();
String keyAlias = null;
if (enumas.hasMoreElements()) {
keyAlias = (String) enumas.nextElement();
}
return (PrivateKey) ks.getKey(keyAlias, chars);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
} /**
* 获得证书
*
* @param certificatePath
* @return
*/
private static Certificate getInstance(String certificatePath) throws Exception {
InputStream is = null;
try {
is = new FileInputStream(certificatePath);
CertificateFactory certificateFactory = CertificateFactory.getInstance(CertType);
return certificateFactory.generateCertificate(is);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return null;
} /**
* 将pfx或p12的文件转为keystore
*
* @param pfxFile 原文件路径及名称
* @param pfxPsw 密码
* @param keyStoreFile 生成的文件名和路径
*/
public static void coverTokeyStore(String pfxFile, String pfxPsw, String keyStoreFile) throws Exception {
KeyStore inputKeyStore = null;
FileInputStream input = null;
FileOutputStream output = null;
String keyAlias = "";
try {
inputKeyStore = KeyStore.getInstance(PKCS12);
input = new FileInputStream(pfxFile);
char[] password = null; if ((pfxPsw == null) || pfxPsw.trim().equals("")) {
password = null;
} else {
password = pfxPsw.toCharArray();
}
inputKeyStore.load(input, password);
KeyStore outputKeyStore = KeyStore.getInstance(TrustStoreType);
outputKeyStore.load(null, pfxPsw.toCharArray());
Enumeration enums = inputKeyStore.aliases();
while (enums.hasMoreElements()) {
keyAlias = (String) enums.nextElement(); System.out.println("alias=[" + keyAlias + "]"); if (inputKeyStore.isKeyEntry(keyAlias)) {
Key key = inputKeyStore.getKey(keyAlias, password);
Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
outputKeyStore.setKeyEntry(keyAlias, key, pfxPsw.toCharArray(), certChain);
}
}
output = new FileOutputStream(keyStoreFile);
outputKeyStore.store(output, password);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
} /**
* 将keystore转为pfx
*
* @param keyStoreFile 生成的文件名和路径
* @param pfxPsw 密码
* @param pfxFile 原文件路径及名称
*/
public static void coverToPfx(String keyStoreFile, String pfxPsw, String pfxFile) throws Exception {
KeyStore inputKeyStore = null;
FileInputStream input = null;
FileOutputStream output = null;
String keyAlias = "";
try {
inputKeyStore = KeyStore.getInstance(TrustStoreType);
input = new FileInputStream(keyStoreFile);
char[] password = null;
if ((pfxPsw == null) || pfxPsw.trim().equals("")) {
password = null;
} else {
password = pfxPsw.toCharArray();
}
inputKeyStore.load(input, password);
KeyStore outputKeyStore = KeyStore.getInstance(PKCS12);
outputKeyStore.load(null, pfxPsw.toCharArray());
Enumeration enums = inputKeyStore.aliases();
while (enums.hasMoreElements()) {
keyAlias = (String) enums.nextElement();
System.out.println("alias=[" + keyAlias + "]");
if (inputKeyStore.isKeyEntry(keyAlias)) {
Key key = inputKeyStore.getKey(keyAlias, password);
Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
outputKeyStore.setKeyEntry(keyAlias, key, pfxPsw.toCharArray(), certChain);
}
}
output = new FileOutputStream(pfxFile);
outputKeyStore.store(output, password);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
} /**
* 使用公钥 进行 非对称加密数据
* @param certPath
* @param dataSource
* @return
* @throws Exception
*/
public static String certEncode(String certPath, String dataSource) throws Exception {
InputStream input = null;
try {
byte[] plainText = dataSource.getBytes(CHARSET);
// 证书格式为x509
CertificateFactory certificateFactory = CertificateFactory.getInstance(CertType);
// 读取证书文件的输入流
input = new FileInputStream(certPath);
Certificate certificate = certificateFactory.generateCertificate(input);
// 支持:RSA/ECB/PCKCS1Padding
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey());
cipher.update(plainText);
byte[] signByte = cipher.doFinal();
String sign = Base64Util.encode(signByte);
return sign;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return null;
} /**
* 使用私钥 进行非对称解密数据
* @param keyStorePath
* @param keyStorePass
* @param alias
* @param certPass
* @param decodeData
* @return
* @throws Exception
*/
public static String certDecode(String keyStorePath, String keyStorePass, String alias, String certPass, String decodeData) throws Exception {
InputStream input = null;
try {
// 密文数据Base64转换
byte[] cipherText = Base64Util.decode(decodeData);
// 提供密钥库类型
KeyStore keyStore = KeyStore.getInstance(TrustStoreType);
// 读取keystore文件的输入流
input = new FileInputStream(keyStorePath);
keyStore.load(input, keyStorePass.toCharArray());
// 加载证书
PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, certPass.toCharArray());
// 支持:RSA/ECB/PCKCS1Padding
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
cipher.update(cipherText);
byte[] sourceByte = cipher.doFinal();
String source = new String(sourceByte, CHARSET);
return source;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return null; } }

  

加解密工具类(含keystore导出pfx)的更多相关文章

  1. RSA加解密工具类RSAUtils.java,实现公钥加密私钥解密和私钥解密公钥解密

    package com.geostar.gfstack.cas.util; import org.apache.commons.codec.binary.Base64; import javax.cr ...

  2. Java中的AES加解密工具类:AESUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...

  3. Java中的RSA加解密工具类:RSAUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.utils.log.LogUtils; ...

  4. DES加解密工具类

    这两天在跟友商对接接口,在对外暴露接口的时候,因为友商不需要登录即可访问对于系统来说存在安全隐患,所以需要友商在调用接口的时候需要将数据加密,系统解密验证后才执行业务.所有的加密方式并不是万能的,只是 ...

  5. vue 核心加解密工具类 方法

    1 /* base64 加解密 2 */ 3 export let Base64 = require('js-base64').Base64 4 5 /* md5 加解密 6 */ 7 export ...

  6. C# 加解密工具类

    using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Clov ...

  7. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  8. Base64加密解密工具类

    使用Apache commons codec类Base64进行加密解密 maven依赖 <dependency> <groupId>commons-codec</grou ...

  9. XJar: Spring-Boot JAR 包加/解密工具,避免源码泄露以及反编译

    XJar: Spring-Boot JAR 包加/解密工具,避免源码泄露以及反编译 <?xml version="1.0" encoding="UTF-8" ...

随机推荐

  1. TP5手动引入PHPEXCEL的方法

    1.先在github里面下载PHPexcel这个类库 2.解压之后把它复制到extend里面 控制器代码如下: 1 <?php 2 /** 3 * Created by PhpStorm. 4 ...

  2. HTML常用标签及属性

    标签格式 格式: 双边:<标签名 属性1="值1" 属性2='值2' 属性3=值3>内容</标签名> 单边:<标签名 属性1="值1&quo ...

  3. 【读书笔记】iOS-多点触摸事件与界面几何

    边缘与中心检测: CGRectGetMinX 返回矩形左边缘的坐标. CGRectGetMinY 返回矩形底部边缘的坐标. CGRectGetMidX 返回矩形中心的x坐标. CGRectGetMid ...

  4. oracle执行先决条件检查失败的解决方法

    在安装oracle 11g时,出现执行先决条件失败的情况如下: 你可以忽略所有强制安装,一般不会影响功能,但如果你想知道为什么会产生这种错误, 并且当出现以上情况时又该如何解决呢?如下列出了原因和解决 ...

  5. Linux 学习笔记之超详细基础linux命令 Part 10

    Linux学习笔记之超详细基础linux命令 by:授客 QQ:1033553122 ---------------------------------接Part 9----------------- ...

  6. vue-cli快速原型开发

    我们知道vue-cli提供了一套如何快速搭建vue开发脚手架的工具,虽然好用,但是有的时候我们还是嫌麻烦,因为就想快速开发调试一个组件,这时我们就可以使用vue-cli 3.x以上版本的一个好特性: ...

  7. .NET 控制Windows文件和目录访问权限研究(FileSystemAccessRule)

    前一段时间学习了.net 控制windows文件和目录权限的相关内容,期间做了一些总结.想把这方面的研究跟大家分享,一起学习.其中不免得有些用词不太标准的地方,希望大家留言指正,我加以修改. 首先,我 ...

  8. JMeter 脚本开发(五)

    一.JMeter 元件运行顺序 执行顺序逻辑如下: 1.配置元件(如果存在) 2.前置处理器(如果存在) 3.定时器(如果存在) 4.取样器(如果存在) 5.后置处理器(如果存在且取样器的结果不为空) ...

  9. 洗礼灵魂,修炼python(15)--列表进阶话题—>列表解析/列表生成器

    是的,我是想到什么知识点就说什么,没有固定的主题,我的标题都是在写完博客再给的.本篇博文说说列表进阶话题.其实列表应该是比较熟悉的了,而毫不夸张的说,在实际的开发中,列表也是使用的最多的,以后你会体会 ...

  10. 第五章 绘图基础(ALTWIND)

    线上箭头表示画线的方向.WINDING模式和ALTERNATE模式都会填充三个封闭的L型区域,号码从1到3.两个更小的内部区域,号码为4和5,在ALTERNATE模式下不被填充.但是在WINDING模 ...