最近有一个需求上传ssl证书和私钥,但是上传之前需要验证ssl证书和私钥是否正确,其中的业务逻辑涉及到以下几点:

一、读取ssl证书,读取ssl证书公钥

      要实现该功能比较简单,java里面有现成的api支持。

证书格式:

-----BEGIN CERTIFICATE-----
MIICYTCCAcoCCQCs45mePIbzRTANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQGEwJV
UzENMAsGA1UECAwETWFyczETMBEGA1UEBwwKaVRyYW5zd2FycDETMBEGA1UECgwK
aVRyYW5zd2FycDETMBEGA1UECwwKaVRyYW5zd2FycDEYMBYGA1UEAwwPd3d3LjU5
MXdpZmkuY29tMB4XDTE4MTAxNzAyMTA0OFoXDTI4MTAxNDAyMTA0OFowdTELMAkG
A1UEBhMCVVMxDTALBgNVBAgMBE1hcnMxEzARBgNVBAcMCmlUcmFuc3dhcnAxEzAR
BgNVBAoMCmlUcmFuc3dhcnAxEzARBgNVBAsMCmlUcmFuc3dhcnAxGDAWBgNVBAMM
D3d3dy41OTF3aWZpLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtxtP
cxgppTHrbzWloh26fXfIyLZI+YpNMCnJ+4wcv3jnZZ6OZsvnoo0z/yl/A9kDY9r5
Rft9fwE4WKMSPNKlGd4psPLw1XNHAXhi8RAy1cHgkBMuwor6ZJhFgnsqKk4Xp68D
jaCI2oxu2SYIBU67Fxy+h7G5BsWKwARtj5kP8NECAwEAATANBgkqhkiG9w0BAQUF
AAOBgQC2Pko8q1NicJ0oPuhFTPm7n03LtPhCaV/aDf3mqtGxraYifg8iFTxVyZ1c
ol0eEJFsibrQrPEwdSuSVqzwif5Tab9dV92PPFm+Sq0D1Uc0xI4ziXQ+a55K9wrV
TKXxS48TOpnTA8fVFNkUkFNB54Lhh9AwKsx123kJmyaWccbt9Q==
-----END CERTIFICATE-----

相关代码:

/**
* 从证书文件获取公钥
*
* @param file
* @return
* @throws CertificateException
* @throws FileNotFoundException
*/
public static PublicKey getPublicKeyFromCert(File file) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream(file);
Certificate crt = cf.generateCertificate(in);
PublicKey publicKey = crt.getPublicKey();
return publicKey;
} catch (CertificateException e) {
logger.error("read public key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
logger.error("read public key fail,the reason is the file not exist");
e.printStackTrace(); }
return null;
}

二、读取ssl证书私钥

该功能实现有点困难,网上方法五花八门,需要对openssl生成私钥的格式和原理比较了解,openssl生成的RSA密钥默认是PEM格式,java包默认只支持DER格式,不能直接读取PEM格式文件,说了那么多,实际上PEM格式只是多了页面页脚,由于涉及到的知识点很多,网上资料很多,这里不在详细解释,我们只需要将页面页脚去掉然后进行base64位解码就可以正常读取了,推荐用第三方包Bouncycastle里面的pemReader工具类读取。

私钥格式:

-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQC3G09zGCmlMetvNaWiHbp9d8jItkj5ik0wKcn7jBy/eOdlno5m
y+eijTP/KX8D2QNj2vlF+31/AThYoxI80qUZ3imw8vDVc0cBeGLxEDLVweCQEy7C
ivpkmEWCeyoqThenrwONoIjajG7ZJggFTrsXHL6HsbkGxYrABG2PmQ/w0QIDAQAB
AoGBAIxvTcggSBCC8OciZh6oXlfMfxoxdFavU/QUmO1s0L+pow+1Q9JjoQxy7+ZL
lTcGQitbzsN11xKJhQW2TE6J4EVimJZQSAE4DDmYpMOrkjnBQhkUlaZkkukvDSRS
JqwBI/04G7se+RouHyXjRS9U76HnPM8+/IS2h+T6CbXLOpYBAkEA2j0JmyGVs+WV
I9sG5glamJqTBa4CfTORrdFW4EULoGkUc24ZFFqn9W4e5yfl/pCkPptCenvIrAWp
/ymnHeLn6QJBANbKGO9uBizAt4+o+kHYdANcbU/Cs3PLj8yOOtjkuMbH4tPNQmB6
/u3npiVk7/Txfkg0BjRzDDZib109eKbvGKkCQBgMneBghRS7+gFng40Z/sfOUOFR
WajeY/FZnk88jJlyuvQ1b8IUc2nSZslmViwFWHQlu9+vgF+kiCU8O9RJSvECQQCl
Vkx7giYerPqgC2MY7JXhQHSkwSuCJ2A6BgImk2npGlTw1UATJJq4Z2jtwBU2Z+7d
ha6BEU6FTqCLFZaaadKBAkEAxko4hrgBsX9BKpFJE3aUIUcMTJfJQdiAhq0k4DV8
5GVrcp8zl6mUTPZDaOmDhuAjGdAQJqj0Xo0PZ0fOZPtR+w==
-----END RSA PRIVATE KEY-----

相关代码:


/**
* 利用开源的工具类解析openssl私钥,openssl私钥文件格式为pem,需要去除页眉页脚后才能被java读取
*
* @param file
* @return
*/
public static PrivateKey getPrivateKey(File file) {
if (file == null) {
return null;
}
PrivateKey privKey = null;
PemReader pemReader = null;
try {
pemReader = new PemReader(new FileReader(file));
PemObject pemObject = pemReader.readPemObject();
byte[] pemContent = pemObject.getContent();
//支持从PKCS#1或PKCS#8 格式的私钥文件中提取私钥
if (pemObject.getType().endsWith("RSA PRIVATE KEY")) {
// 取得私钥 for PKCS#1
RSAPrivateKey asn1PrivKey = RSAPrivateKey.getInstance(pemContent);
RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
privKey= keyFactory.generatePrivate(rsaPrivKeySpec);
} else if (pemObject.getType().endsWith("PRIVATE KEY")) {
//取得私钥 for PKCS#8
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pemContent);
KeyFactory kf = KeyFactory.getInstance("RSA");
privKey = kf.generatePrivate(privKeySpec);
}
} catch (FileNotFoundException e) {
logger.error("read private key fail,the reason is the file not exist");
e.printStackTrace();
} catch (IOException e) {
logger.error("read private key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
logger.error("read private key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} catch (InvalidKeySpecException e) {
logger.error("read private key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} finally {
try {
if (pemReader != null) {
pemReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return privKey;
}

三、ssl证书公钥和私钥是否匹配

      读取证书公钥和私钥后,将测试的字符串经过证书公钥加密后,再根据证书私钥解密后能后还原,说明上传的证书和私钥是正确的。

 /**
* 加密
*
* @param key
* @param plainBytes
* @return
*/
public static byte[] encrypt(PublicKey key, byte[] plainBytes) { ByteArrayOutputStream out = null;
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key); int inputLen = plainBytes.length;
if (inputLen <= MAX_ENCRYPT_BLOCK) {
return cipher.doFinal(plainBytes);
}
out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 数据太长对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(plainBytes, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(plainBytes, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
return out.toByteArray();
} catch (NoSuchAlgorithmException e) {
logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage());
e.printStackTrace();
return null;
} catch (NoSuchPaddingException e) {
logger.error("rencrypt fail,the reason is :"+e.getMessage());
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (IllegalBlockSizeException e) {
logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (BadPaddingException e) {
logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage());
e.printStackTrace();
return null;
} finally {
try {
if (out != null) out.close();
} catch (Exception e2) {
}
}
} /**
* 根据公钥加密字符串
*
* @param key
* @param plainText 需要加密的字符串
* @return
*/
public static String encrypt(PublicKey key, String plainText) {
byte[] encodeBytes = encrypt(key, plainText.getBytes(DEFAULT_CHARSET));
return Base64.encodeBase64String(encodeBytes);
} /**
* 解密
*
* @param key
* @param encodedText
* @return
*/
public static String decrypt(PrivateKey key, byte[] encodedText) { ByteArrayOutputStream out = null;
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
int inputLen = encodedText.length; if (inputLen <= MAX_DECRYPT_BLOCK) {
return new String(cipher.doFinal(encodedText), DEFAULT_CHARSET);
} out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encodedText, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encodedText, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
return new String(out.toByteArray(), DEFAULT_CHARSET);
} catch (NoSuchAlgorithmException e) {
logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage());
e.printStackTrace();
return null;
} catch (NoSuchPaddingException e) {
logger.error("rencrypt fail,the reason is :"+e.getMessage());
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (IllegalBlockSizeException e) {
logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (BadPaddingException e) {
logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage());
e.printStackTrace();
return null;
} finally {
try {
if (out != null) out.close();
} catch (Exception e2) {
}
}
} /**
* 根据私钥解密加密过的字符串
*
* @param key
* @param encodedText 加密过的字符串
* @return 解密后的字符串
*/
public static String decrypt(PrivateKey key, String encodedText) {
byte[] bytes = Base64.decodeBase64(encodedText);
return decrypt(key, bytes);
} /**
* 验证证书
* @param cert
* @return
*/
public static String validateCert(File cert){
if (cert == null) {
return "证书CRT文件不能为空";
}
PublicKey publicKey = getPublicKeyFromCert(cert);
if (publicKey == null) {
return "无法读取证书公钥,证书CRT文件格式错误";
}
return null;
} /**
* 验证私钥
* @param privateKey
* @return
*/
public static String validatePrivateKey( File privateKey){
if (privateKey == null) {
return "证书私钥不能为空";
}
PrivateKey privKey = getPrivateKey(privateKey);
if (privKey == null) {
return "无法读取证书私钥,证书私钥文件格式错误";
}
return null;
} /**
* 验证证书私钥是否匹配,如果不匹配返回错误消息
* @param cert
* @param privateKey
* @return 错误消息
*/
public static String validate(File cert, File privateKey) {
String res = validateCert(cert);//验证证书
if((res!=null)&&(res.length()>0)){
return res;//返回错误消息
}
res = validatePrivateKey(privateKey);//验证私钥
if((res!=null)&&(res.length()>0)){
return res;//返回错误消息
}
PublicKey publicKey = getPublicKeyFromCert(cert);
PrivateKey privKey = getPrivateKey(privateKey);
String str = "haha";//测试字符串
String encryptStr = OpensslUtils.encrypt(publicKey, str);//根据证书公钥对字符串进行加密
String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);//根据证书私钥对加密字符串进行解密
if(!str.equals(decryptStr)){//字符串根据证书公钥加密,私钥解密后不能还原说明证书与私钥不匹配
return "证书与私钥不匹配";
}
return null;
}

四、完整代码

package com.shixun.ewifi.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.nio.charset.Charset;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.X509EncodedKeySpec; /**
* openssl 证书公钥私钥读取加密解密工具类,主要用于验证上传的openssl 生成的证书和私钥文件是否正确的问题
*
* @author yinliang 2018.12.13 add
* 主要逻辑:
* 1、根据私钥文件读取私钥
* 2、根据公钥文件读取公钥
* 3、根据证书文件读取公钥
* 4、根据证书公钥加密字符串
* 5、根据证书私钥解密字符串
* 6、如果字符串经过证书公钥加密后,再根据证书私钥解密后能后还原,说明上传的证书和私钥是正确的
*/
public class OpensslUtils {
private static final String DEFAULT_ENCODING = "UTF-8"; private static final Charset DEFAULT_CHARSET = Charset.forName(DEFAULT_ENCODING); private static final String KEY_ALGORITHM = "RSA";
/**
* 默认是RSA/NONE/PKCS1Padding
*/
private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding"; /**
* RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024
*/
private static final int KEY_SIZE = 1024; /**
* RSA最大加密明文大小:明文长度(bytes) <= 密钥长度(bytes)-11
*/
private static final int MAX_ENCRYPT_BLOCK = KEY_SIZE / 8 - 11; /**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / 8; private static Logger logger = Logger.getLogger(OpensslUtils.class);
/**
* 利用开源的工具类解析openssl私钥,openssl私钥文件格式为pem,需要去除页眉页脚后才能被java读取
*
* @param file
* @return
*/
public static PrivateKey getPrivateKey(File file) {
if (file == null) {
return null;
}
PrivateKey privKey = null;
PemReader pemReader = null;
try {
pemReader = new PemReader(new FileReader(file));
PemObject pemObject = pemReader.readPemObject();
byte[] pemContent = pemObject.getContent();
//支持从PKCS#1或PKCS#8 格式的私钥文件中提取私钥
if (pemObject.getType().endsWith("RSA PRIVATE KEY")) {
// 取得私钥 for PKCS#1
RSAPrivateKey asn1PrivKey = RSAPrivateKey.getInstance(pemContent);
RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
privKey= keyFactory.generatePrivate(rsaPrivKeySpec);
} else if (pemObject.getType().endsWith("PRIVATE KEY")) {
//取得私钥 for PKCS#8
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pemContent);
KeyFactory kf = KeyFactory.getInstance("RSA");
privKey = kf.generatePrivate(privKeySpec);
}
} catch (FileNotFoundException e) {
logger.error("read private key fail,the reason is the file not exist");
e.printStackTrace();
} catch (IOException e) {
logger.error("read private key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
logger.error("read private key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} catch (InvalidKeySpecException e) {
logger.error("read private key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} finally {
try {
if (pemReader != null) {
pemReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return privKey;
} /**
* 利用java自带的方法读取openssl私钥,openssl私钥文件格式为pem,需要去除页眉页脚后,再进行base64位解码才能被java读取
* 注意该方法有缺陷,只是简单的根据注释将页眉页脚去掉了,不是很完善,如果页眉页脚前面有空格和注释的情况的会有问题,保留此方法是为方便弄清楚openssl私钥解析原理
*
* @param file
* @return
*/
public static PrivateKey getPrivateKey1(File file) {
if (file == null) {
return null;
}
PrivateKey privKey = null;
try {
BufferedReader privateKey = new BufferedReader(new FileReader(
file));
String line = "";
String strPrivateKey = "";
while ((line = privateKey.readLine()) != null) {
if (line.contains("--")) {//过滤掉首尾页眉页脚
continue;
}
strPrivateKey += line;
}
privateKey.close();
;
//使用base64位解码
byte[] privKeyByte = Base64.decodeBase64(strPrivateKey);
//私钥需要使用pkcs8格式编码
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyByte);
KeyFactory kf = KeyFactory.getInstance("RSA");
privKey = kf.generatePrivate(privKeySpec);
return privKey;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return privKey;
} /**
* 从证书文件获取公钥
*
* @param file
* @return
* @throws CertificateException
* @throws FileNotFoundException
*/
public static PublicKey getPublicKeyFromCert(File file) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream(file);
Certificate crt = cf.generateCertificate(in);
PublicKey publicKey = crt.getPublicKey();
return publicKey;
} catch (CertificateException e) {
logger.error("read public key fail,the reason is :"+e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
logger.error("read public key fail,the reason is the file not exist");
e.printStackTrace(); }
return null;
} /**
* 从openssl公钥文件中读取公钥
* @param file
* @return
*/
public static PublicKey getPublicKey(File file) {
if (file == null) {
return null;
}
PublicKey pubKey = null;
PemReader pemReader = null;
try {
pemReader = new PemReader(new FileReader(file));
PemObject pemObject = pemReader.readPemObject();
byte[] pemContent = pemObject.getContent();
//公钥需要使用x509格式编码
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pemContent);
KeyFactory kf = KeyFactory.getInstance("RSA");
pubKey = kf.generatePublic(pubKeySpec);
return pubKey;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} finally {
try {
if (pemReader != null) {
pemReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return pubKey;
} /**
* 加密
*
* @param key
* @param plainBytes
* @return
*/
public static byte[] encrypt(PublicKey key, byte[] plainBytes) { ByteArrayOutputStream out = null;
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key); int inputLen = plainBytes.length;
if (inputLen <= MAX_ENCRYPT_BLOCK) {
return cipher.doFinal(plainBytes);
}
out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 数据太长对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(plainBytes, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(plainBytes, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
return out.toByteArray();
} catch (NoSuchAlgorithmException e) {
logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage());
e.printStackTrace();
return null;
} catch (NoSuchPaddingException e) {
logger.error("rencrypt fail,the reason is :"+e.getMessage());
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (IllegalBlockSizeException e) {
logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (BadPaddingException e) {
logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage());
e.printStackTrace();
return null;
} finally {
try {
if (out != null) out.close();
} catch (Exception e2) {
}
}
} /**
* 根据公钥加密字符串
*
* @param key
* @param plainText 需要加密的字符串
* @return
*/
public static String encrypt(PublicKey key, String plainText) {
byte[] encodeBytes = encrypt(key, plainText.getBytes(DEFAULT_CHARSET));
return Base64.encodeBase64String(encodeBytes);
} /**
* 解密
*
* @param key
* @param encodedText
* @return
*/
public static String decrypt(PrivateKey key, byte[] encodedText) { ByteArrayOutputStream out = null;
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
int inputLen = encodedText.length; if (inputLen <= MAX_DECRYPT_BLOCK) {
return new String(cipher.doFinal(encodedText), DEFAULT_CHARSET);
} out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encodedText, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encodedText, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
return new String(out.toByteArray(), DEFAULT_CHARSET);
} catch (NoSuchAlgorithmException e) {
logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage());
e.printStackTrace();
return null;
} catch (NoSuchPaddingException e) {
logger.error("rencrypt fail,the reason is :"+e.getMessage());
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (IllegalBlockSizeException e) {
logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage());
e.printStackTrace();
return null;
} catch (BadPaddingException e) {
logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage());
e.printStackTrace();
return null;
} finally {
try {
if (out != null) out.close();
} catch (Exception e2) {
}
}
} /**
* 根据私钥解密加密过的字符串
*
* @param key
* @param encodedText 加密过的字符串
* @return 解密后的字符串
*/
public static String decrypt(PrivateKey key, String encodedText) {
byte[] bytes = Base64.decodeBase64(encodedText);
return decrypt(key, bytes);
} /**
* 验证证书
* @param cert
* @return
*/
public static String validateCert(File cert){
if (cert == null) {
return "证书CRT文件不能为空";
}
PublicKey publicKey = getPublicKeyFromCert(cert);
if (publicKey == null) {
return "无法读取证书公钥,证书CRT文件格式错误";
}
return null;
} /**
* 验证私钥
* @param privateKey
* @return
*/
public static String validatePrivateKey( File privateKey){
if (privateKey == null) {
return "证书私钥不能为空";
}
PrivateKey privKey = getPrivateKey(privateKey);
if (privKey == null) {
return "无法读取证书私钥,证书私钥文件格式错误";
}
return null;
} /**
* 验证证书私钥是否匹配,如果不匹配返回错误消息
* @param cert
* @param privateKey
* @return 错误消息
*/
public static String validate(File cert, File privateKey) {
String res = validateCert(cert);//验证证书
if((res!=null)&&(res.length()>0)){
return res;//返回错误消息
}
res = validatePrivateKey(privateKey);//验证私钥
if((res!=null)&&(res.length()>0)){
return res;//返回错误消息
}
PublicKey publicKey = getPublicKeyFromCert(cert);
PrivateKey privKey = getPrivateKey(privateKey);
String str = "haha";//测试字符串
String encryptStr = OpensslUtils.encrypt(publicKey, str);//根据证书公钥对字符串进行加密
String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);//根据证书私钥对加密字符串进行解密
if(!str.equals(decryptStr)){//字符串根据证书公钥加密,私钥解密后不能还原说明证书与私钥不匹配
return "证书与私钥不匹配";
}
return null;
} /**
* 测试主方法
*
* @param args
*/
public static void main(String[] args) {
File privateKeyFile = new File("src/main/resources/test.private.key");
// PrivateKey privKey = OpensslUtils.getPrivateKey(privateKeyFile);
// System.out.println("privKey1:" + privKey);
// privKey = OpensslUtils.getPrivateKey1(privateKeyFile);
// System.out.println("privKey2:" + privKey);
// File publicKeyFile = new File("src/main/resources/test.public.key");
// PublicKey publicKey = OpensslUtils.getPublicKey(publicKeyFile);
// System.out.println("publicKey:" + publicKey);
File certFile = new File("src/main/resources/test.crt");
//publicKey = OpensslUtils.getPublicKeyFromCert(certFile);
// System.out.println("publicKey2:" + publicKey);
// String str = "haha";
// String encryptStr = OpensslUtils.encrypt(publicKey, str);
// System.out.println("encryptStr:" + encryptStr);
// String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);
// System.out.println("decryptStr:" + decryptStr);
String validateResult = validate(certFile,privateKeyFile);
System.out.println("validateResult:" + validateResult);
}
}

五:涉及到的第三方jar包

<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.58</version>
</dependency>

 六、参考资料

java验证openssl生成的ssl证书和私钥是否匹配的更多相关文章

  1. openssl 自己制作ssl证书:自己签发免费ssl证书,为nginx生成自签名ssl证书

    server { listen 80; listen 443 ssl; server_name ~^((cloud)|(demo-cloud)|(demo2-cloud)|(approval1))(( ...

  2. 用OpenSSL生成自签名证书在IIS上搭建Https站点(用于iOS的https访问)

    前提: 先安装openssl,安装有两种方式,第一种直接下载安装包,装上就可运行:第二种可以自己下载源码,自己编译.这里推荐第一种. 安装包:http://slproweb.com/products/ ...

  3. 使用Let's Encrypt生成免费SSL证书操作记录

    最近要做微信小程序,要求接口必须备案且是https,个人小站就直接准备使用免费的SSL证书,网上搜了一圈,发现Let's Encrypt是浏览器支持比较好的. 流程: 1. 首先去服务器上安装了Let ...

  4. 使用openssl生成双向加密证书(转)

    要生成证书的目录下建立几个文件和文件夹,有./demoCA/./demoCA/newcerts/./demoCA/private/./demoCA/index.txt (空文件,生成证书时会将数据记录 ...

  5. OpenSSL使用1(用OpenSSL生成自签名证书在IIS上搭建Https站点)(用于iOS的https访问)

    前提: 先安装openssl,安装有两种方式,第一种直接下载安装包,装上就可运行:第二种可以自己下载源码,自己编译.这里推荐第一种. 安装包:http://slproweb.com/products/ ...

  6. 如何在linux系统内用openssl 生成 过期的证书

    需求:验证过期的证书在系统中不能使用. 问题:如何生成过期的证书呢? 解决方法:1.调整系统时间 2.生成证书 3.验证证书startdate 和 enddate 是否符合你的预期 1.调整系统时间 ...

  7. Windows Server 快速生成免费SSL证书 (letsencrypt)

    最近官网需求部署个SSL证书,一番操作后把借鉴的网站与实际过程记录下来 Let's Encrypt,官网是https://letsencrypt.org/,它是一个由各大公司赞助的公益组织: 有趋势有 ...

  8. openssl生成自签名证书

    1.生成x509格式的CA自签名证书 openssl req -new -x509 -keyout ca.key -out ca.crt 2.生成服务端的私钥(key文件)及申请证书文件csr文件 o ...

  9. 绿色地址栏扩展验证(EV)SSL证书、支持SGC 强制最低128位

      Pro With EV SSL证书,最严格的域名所有权和企业身份信息验证,属于最高信任级别.最高安全级别的 EV SSL证书,该证书可以使地址栏变成高安全绿色,并且在地址栏内显示您公司的名称,提高 ...

随机推荐

  1. 离散化&&逆序数对

    题目:http://www.fjutacm.com/Problem.jsp?pid=3087 #include<stdio.h> #include<string.h> #inc ...

  2. Spring提供的iBatis的SqlMap配置

    1.    applicationContext.xml <!-- Spring提供的iBatis的SqlMap配置--> <bean id="sqlMapClient&q ...

  3. 4-Python数据类型之元组-字符串

    目录 1 元组概念 1.1 元祖的特点 1.2 元组的定义 1.3 元组的访问 1.4 元组的查询 2 命名元组 3 字符串 3.1 字符串的基本操作 3.1.1 字符串的访问 3.1.2 字符串的拼 ...

  4. 宋牧春: Linux设备树文件结构与解析深度分析(2) 【转】

    转自:https://mp.weixin.qq.com/s/WPZSElF3OQPMGqdoldm07A 作者简介 宋牧春,linux内核爱好者,喜欢阅读各种开源代码(uboot.linux.ucos ...

  5. Spring Cloud Feign 输出日志

    还需要在application 文件中配置: #feign调用日志输出logging.level.cn.XXX=DEBUG Logger.Level下面有几种级别. BASIC : 只输出 请求URL ...

  6. Linux命令之dig命令挖出DNS的秘密

    === [初次见面] 我相信使用nslookup的同学一定比使用dig的同学多,所以还是有必要花些时间给大家介绍一下dig的. dig,和nslookup作用有些类似,都是DNS查询工具. dig,其 ...

  7. Windows下 Tensorflow安装问题: Could not find a version that satisfies the requirement tensorflow

    Tensorflow 需要 Python 3.5/3.6  64bit 版本: 具体的安装方式可查看:https://www.tensorflow.org/install/install_window ...

  8. JS(vue iview)分页解决方案

    JS(vue iview)分页解决方案 一.解决思路 使用分页组件 使用组件API使组件自动生成页面数量 调用组件on-change事件的返回值page 将交互获得的数组存在一个数组list中 通过p ...

  9. WPF 获取计算机字体

    //加载计算机上可用的字体 public void LoadFonts(object ietfLanguageTag) { try { var sysFonts = Fonts.SystemFontF ...

  10. bzoj 1816 二分

    思路:二分答案,然后我们贪心地先不填最小的一堆,看在最小的一堆消耗完之前能不能填满其他堆. #include<bits/stdc++.h> #define LL long long #de ...