java验证公钥和证书 验证签名 验证签名 项目需求:通过私钥签名,公钥验证判断公钥和私钥是否配对
下面代码是通过私钥(公钥)加密,公钥(私钥)解密,通过前后对比加密数据是否一致得出配对结果。与项目需求不一致,因此重新改动一些。
项目在加入验证签名之后会出现Signature length not correct错误,是由于在转换格式的过程中出现使用getBytes函数,使得签名长度发生改变导致。 修改Signature length not correct错误 错误原因
介绍一下编码格式
本节主要介绍密钥和证书中常见的编码规则 DER和由 DER 衍生出的密钥文件格式 PEM。
DER (Distinguished Encoding Rules)DER (Distinguished Encoding Rules)
DER 是用二进制DER编码的证书,DER格式常见于java语言
PEM格式是在DER格式的基础上采用base64编码得到,PEM is Base64-encoded DER。PEM格式是采用openssl生成密钥和证书的格式。 下面是经典的PEM格式
PEM = "-----BEGIN PUBLIC KEY-----"
encode_base64(decode_hex(DER))
"-----END PUBLIC KEY-----"
公钥密码学标准 PKCS (Public Key Cryptography Standards) 和公钥基础设施 PKIX(Public-Key Infrastructure X.509) 等使用 ASN.1 的类型定义密钥和证书的格式和编码,以描述公私钥和证书属性。 需要注意,PKCS 虽然名字是公钥密码学标准,它其实也包括私钥格式标准。
PKCS#1 格式
使用openssl genrsa生成的密钥对即是PKCS#1格式
-----BEGIN RSA PRIVATE KEY-----
....
-----END RSA PRIVATE KEY-----
PKCS#8 格式
-----BEGIN PRIVATE KEY-----
....
-----END PRIVATE KEY-----
package cc.weno.util;
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;
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";
private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
private static final int KEY_SIZE = 1024;
private static final int MAX_ENCRYPT_BLOCK = KEY_SIZE / 8 - 11;
private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / 8;
private static Logger logger = Logger.getLogger(OpensslUtils.class);
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();
if (pemObject.getType().endsWith("RSA PRIVATE KEY")) {
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")) {
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;
}
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();
;
byte[] privKeyByte = Base64.decodeBase64(strPrivateKey);
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;
}
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;
}
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();
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;
}
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) {
}
}
}
public static String encrypt(PublicKey key, String plainText) {
byte[] encodeBytes = encrypt(key, plainText.getBytes(DEFAULT_CHARSET));
return Base64.encodeBase64String(encodeBytes);
}
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) {
}
}
}
public static String decrypt(PrivateKey key, String encodedText) {
byte[] bytes = Base64.decodeBase64(encodedText);
return decrypt(key, bytes);
}
public static String validateCert(File cert){
if (cert == null) {
return "证书CRT文件不能为空";
}
PublicKey publicKey = getPublicKeyFromCert(cert);
if (publicKey == null) {
return "无法读取证书公钥,证书CRT文件格式错误";
}
return null;
}
public static String validatePrivateKey( File privateKey){
if (privateKey == null) {
return "证书私钥不能为空";
}
PrivateKey privKey = getPrivateKey(privateKey);
if (privKey == null) {
return "无法读取证书私钥,证书私钥文件格式错误";
}
return null;
}
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 = "你好";
String encryptStr = OpensslUtils.encrypt(publicKey, str);
String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);
System.out.println(decryptStr);
if(!str.equals(decryptStr)){
return "证书与私钥不匹配";
}
return "ok";
}
public static void main(String[] args) {
File privateKeyFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\rootca.key");
File certFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\rootca.pem");
String validateResult = validate(certFile,privateKeyFile);
System.out.println("validateResult:" + validateResult);
}
}
下面是根据项目需求新增加的改动,通过私钥签名,公钥签名验证
public static boolean checkSign( String message, String sign, File cert )
{
boolean ret = false;
{
try {
ret = OpensslUtils.verify( message, sign, getPublicKeyFromCert(cert));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
private static PublicKey getKey( File keyPath )
throws NoSuchAlgorithmException, IOException, InvalidKeySpecException
{
final KeyFactory keyFactory = KeyFactory.getInstance( "RSA");
final PemReader reader = new PemReader( new FileReader( keyPath ) );
final byte[] pubKey = reader.readPemObject( ).getContent( );
final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec( pubKey );
return keyFactory.generatePublic( publicKeySpec );
}
private static boolean verify( String message, String sign, PublicKey publicKey )
throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException
{
final Signature sig = Signature.getInstance("MD5withRSA");
sig.initVerify( publicKey );
sig.update( message.getBytes("utf-8") );
byte[] signByte = Base64.decodeBase64(sign);
return sig.verify(signByte );
}
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateK);
signature.update(data);
return Base64.encodeBase64String(signature.sign());
}
public static void main(String[] args) {
File certFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\client.pem");
String str = "sdifhjksabdnkfbasdjhhh";
File privateKeyFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\client.key");
PrivateKey privKey = getPrivateKey(privateKeyFile);
String encryptStr = OpensslUtils.encrypt(privKey, str);
String sign = null;
{
try {
sign = OpensslUtils.sign(encryptStr.getBytes(StandardCharsets.UTF_8), Base64.encodeBase64String(privKey.getEncoded()));
} catch (Exception e) {
e.printStackTrace();
}
}
boolean bl = checkSign(encryptStr, sign, certFile);
System.out.println(bl);
}
|