java pkcs7 format signature tool

package com.xxx.util;

import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.*;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
org.bouncycastle.operator.ContentSigner Import;
Import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
Import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
Import org.bouncycastle.util.Store;

/ **
* PKCS7Tool.java pkcs7 format signature tool, read encrypted key certificate
*
* @version 1.0
* Written @author a Date: 2020-01-03
* the JDK
* /
public class PKCS7Tool {
/ ** signing certificate chain * /
static the X509Certificate [] certificates = null;
/ ** signature private key * /
static PrivateKey privateKey = null;
/ ** root certificate * /
// Private certificate rootCertificate = null;
/ ** certificate storage path * /
String keystorePath = static "C: \\ \\ cert.pfx Upload";
/ ** certificate Password * /
static String keystorePassword = "..";
/ ** the JVM provider * /
Private JVM static char = 0;
Private static AlgorithmID = null class;
Private static class derValue = null;
Private static class objectIdentifier = null;
Private static class x500Name = null;
Private static Boolean = Debug to false;
Private static BouncyCastleProvider bouncyCastleProvider = null;

static {
the try {
// If the filling is PKCS7Padding embodiment, this line must be added to the
IF (bouncyCastleProvider == null) {
bouncyCastleProvider new new BouncyCastleProvider = ();
}
Security.addProvider(bouncyCastleProvider);
init();
// 加载证书库
KeyStore keyStore = null;
if (keyStorePath.toLowerCase().endsWith(".pfx"))
keyStore = KeyStore.getInstance("PKCS12");
else
keyStore = KeyStore.getInstance("JKS");
FileInputStream fis = null;
try {
fis = new FileInputStream(keyStorePath);
keyStore.load(fis, keyStorePassword.toCharArray());
} finally {
if (fis != null)
fis.close();
}
// 在证书库中找到签名私钥
Enumeration aliases = keyStore.aliases();
String keyAlias = null;
if (aliases != null) {
while (aliases.hasMoreElements()) {
keyAlias = (String) aliases.nextElement();
Certificate[] certs = keyStore.getCertificateChain(keyAlias);
if (certs == null || certs.length == 0)
continue;
X509Certificate cert = (X509Certificate) certs[0];
if (matchUsage(cert.getKeyUsage(), 1)) {
try {
cert.checkValidity();
The catch} (a CertificateException E) {
Continue;
}
BREAK;
}
}
}
// no available signature secret key
IF (keyAlias == null)
the throw new new The GeneralSecurityException (
"None Certificate for the this Sign in the keystore");
IF (Debug)
the System .out.println (keyAlias);
IF (keyStore.isKeyEntry (keyAlias)) {
// check the certificate chain
certificate [] certs = keyStore.getCertificateChain (keyAlias );
for (int i = 0; i < certs.length; i++) {
if (!(certs[i] instanceof X509Certificate))
throw new GeneralSecurityException("Certificate[" + i
+ "] in chain '" + keyAlias
+ "' is not a X509Certificate.");
}
// 转换证书链
certificates = new X509Certificate[certs.length];
for (int i = 0; i < certs.length; i++)
certificates[i] = (X509Certificate) certs[i];
} else if (keyStore.isCertificateEntry(keyAlias)) {
// 只有单张证书
Certificate cert = keyStore.getCertificate(keyAlias);
if (cert instanceof X509Certificate) {
certificates = new X509Certificate[ { (X509Certificate) cert }];
}
} else {
throw new GeneralSecurityException(keyAlias
+ " is unknown to this keystore");
}
privateKey = (PrivateKey) keyStore.getKey(keyAlias,
keyStorePassword.toCharArray());
// 没有私钥抛异常
if (privateKey == null) {
throw new GeneralSecurityException(keyAlias
+ " could not be accessed");
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 签名
*
* @param data
* 数据
* @return signature 签名结果
* @throws GeneralSecurityException
* @throws IOException
* @throws IllegalArgumentException
*/
public static String sign(byte[] data) throws Exception {
X509Certificate cerx509 = certificates[0];
List<X509Certificate> certList = new ArrayList<X509Certificate>();
certList.add(cerx509);
Store certs = new JcaCertStore(certList);
ContentSigner contentSigner = new JcaContentSignerBuilder(cerx509.getSigAlgName()).setProvider("BC").build(privateKey);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC")
.build()).setDirectSignature(true).build(contentSigner, cerx509));
gen.addCertificates(certs);
CMSTypedData msg = new CMSProcessableByteArray(data);
CMSSignedData sigData = gen.generate(msg, false);
org.bouncycastle.asn1.cms.ContentInfo a = sigData.toASN1Structure();
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
{the try
DEROutputStream new new DEROutputStream DOUT = (Bout);
dOut.writeObject (A);
return Base64.encodeBase64String (bOut.toByteArray ());
} {the finally
IOUtils.closeQuietly (Bout);
}
}

/ **
* Signature verification (None the CRL)
*
* @param data
* is the signature data
* @param signature
* signature signature results
* @throws Exception
* /
public static Boolean Verify (byte [] data, byte [] signature) throws Exception {
CMSProcessable new new CMSProcessableByteArray Content = (data );
// New PKCS # 7 signature data to be processed
S = new new CMSSignedData CMSSignedData (Content, Signature);
Store of CertStore s = s.getCertificates ();
// get the signer information
SignerInformationStore Signers = s.getSignerInfos ();
Iterator IT = signers.getSigners () Iterator () <?>. ;
int verified = 0, size = 0;
// when there are a plurality of signatory information needed to verify all
the while (it.hasNext ()) {
size ++;
SignerInformation signer = (SignerInformation) it.next ();
// certificate chain
<?> = certStore.getMatches certCollection Collection (signer.getSID ());
<?> = certCollection.iterator certIt the Iterator ();
X509CertificateHolder CERT = (X509CertificateHolder) certIt.next ();
//验证数字签名
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
verified++;
}
}
if (verified >0 && size == verified) {
return true;
}
return false;
}


/**
* 匹配私钥用法
*
* @param keyUsage
* @param usage
* @return
*/
private static boolean matchUsage(boolean[] keyUsage, int usage) {
if (usage == 0 || keyUsage == null)
return true;
for (int i = 0; i < Math.min(keyUsage.length, 32); i++) {
if ((usage & (1 << i)) != 0 && !keyUsage[i])
return false;
}
return true;
}


private static void init() {
if (jvm != 0)
return;
String vendor = System.getProperty("java.vm.vendor");
if (vendor == null)
vendor = "";
String vendorUC = vendor.toUpperCase();
try {
if (vendorUC.indexOf("SUN") >= 0) {
jvm = 'S';
algorithmId = Class.forName("sun.security.x509.AlgorithmId");
derValue = Class.forName("sun.security.util.DerValue");
objectIdentifier = Class.forName("sun.security.util.ObjectIdentifier");
x500Name = Class.forName("sun.security.x509.X500Name");
} else if (vendorUC.indexOf("ORACLE CORPORATION") >= 0) {
jvm = 'O';
algorithmId = Class.forName("sun.security.x509.AlgorithmId");
derValue = Class.forName("sun.security.util.DerValue");
objectIdentifier = Class.forName("sun.security.util.ObjectIdentifier");
x500Name = Class.forName("sun.security.x509.X500Name");
} else if (vendorUC.indexOf("IBM") >= 0) {
jvm = 'I';
algorithmId = Class.forName("com.ibm.security.x509.AlgorithmId");
derValue = Class.forName("com.ibm.security.util.DerValue");
objectIdentifier = Class.forName("com.ibm.security.util.ObjectIdentifier");
x500Name = Class.forName("com.ibm.security.x509.X500Name");
} else {
System.out.println("Not support JRE: " + vendor);
System.exit(-1);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
}

}

相关jar包:compile group: 'org.bouncycastle', name: 'bcpkix-jdk15on', version: '1.52'

Guess you like

Origin www.cnblogs.com/ppybk/p/12146361.html