项目中用到的数字证书的创建,签名实现
首先 需要下载jar包 bcprov-jdk15-145.jar
实体类
package com.hongan.lh.cert;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
public class CertInfo {
private KeyPair key;
private X509Certificate cert;
public KeyPair getKey() {
return key;
}
public void setKey(KeyPair key) {
this.key = key;
}
public X509Certificate getCert() {
return cert;
}
public void setCert(X509Certificate cert) {
this.cert = cert;
}
}
帮助类
package com.hongan.lh.cert;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.openssl.PasswordFinder;
public class HongAnUtils {
public static KeyPair getPrivateKey(String rootMiyuePath,
final String rootMiyuePwd) throws Exception {
PEMReader reader = new PEMReader(new InputStreamReader(
new FileInputStream(rootMiyuePath)), new PasswordFinder() {
public char[] getPassword() {
// TODO Auto-generated method stub
return rootMiyuePwd.toCharArray();
}
});
KeyPair key = (KeyPair) reader.readObject();
return key;
}
public static void saveX509Certificate(X509Certificate certificate,
String rootcertPath) throws Exception {
FileOutputStream stream = new FileOutputStream(rootcertPath);
stream.write(certificate.getEncoded());
stream.close();
}
public static void savePEM(PrivateKey key, String rootMiyuePwd,
String rootMiyuePath) throws Exception {
PEMWriter writer = new PEMWriter(new FileWriter(rootMiyuePath));
writer.writeObject(key, "DESEDE", rootMiyuePwd.toCharArray(),
new SecureRandom());
writer.close();
}
public static KeyPair generateRSAKeyPair() throws Exception {
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(1024, new SecureRandom());
return kpGen.generateKeyPair();
}
public static byte[] RSASign(PrivateKey key, byte[] src) throws Exception {
java.security.Signature sign = java.security.Signature.getInstance(
"SHA1withRSA", "BC");
sign.initSign(key);
sign.update(src);
return sign.sign();
}
public static boolean RSAVerifySign(PublicKey key, byte[] crypt, byte[] src)
throws Exception {
java.security.Signature sign = java.security.Signature.getInstance(
"SHA1withRSA", "BC");
sign.initVerify(key);
sign.update(src);
return sign.verify(crypt);
}
public static X509Certificate getCertificate(String rootCertPath)
throws Exception {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
FileInputStream inputStream = new FileInputStream(rootCertPath);
X509Certificate certificate = (X509Certificate) factory
.generateCertificate(inputStream);
return certificate;
}
public static void write(String file, byte[] data) throws Exception {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data);
outputStream.close();
}
public static byte[] read(String file) throws Exception {
FileInputStream stream = new FileInputStream(file);
byte[] by = new byte[stream.available()];
stream.read(by);
stream.close();
return by;
}
public static byte[] encrypt(Key key, byte[] b, String suan)
throws Exception {
Cipher newcipher = Cipher.getInstance(suan);
newcipher.init(Cipher.ENCRYPT_MODE, key);
return newcipher.doFinal(b);
}
public static byte[] encryptByKouling(byte[] s, String suan, String kou)
throws Exception {
PBEKeySpec spec = new PBEKeySpec(kou.toCharArray());
SecretKeyFactory factory = SecretKeyFactory.getInstance(suan);
SecretKey key = factory.generateSecret(spec);
Cipher cipher = Cipher.getInstance(suan);
PBEParameterSpec pps = new PBEParameterSpec(new byte[] { 0xF, 0x0, 0x1,
0x2, 0x3, 0x4, 0x5, 0x6 }, 1);
cipher.init(Cipher.ENCRYPT_MODE, key, pps);
byte[] debyte = cipher.doFinal(s);
return debyte;
}
public static byte[] decryptByKouling(byte[] s, String suan, String kou)
throws Exception {
PBEKeySpec spec = new PBEKeySpec(kou.toCharArray());
SecretKeyFactory factory = SecretKeyFactory.getInstance(suan);
SecretKey key = factory.generateSecret(spec);
Cipher cipher = Cipher.getInstance(suan);
PBEParameterSpec pps = new PBEParameterSpec(new byte[] { 0xF, 0x0, 0x1,
0x2, 0x3, 0x4, 0x5, 0x6 }, 1);
cipher.init(Cipher.DECRYPT_MODE, key, pps);
byte[] debyte = cipher.doFinal(s);
return debyte;
}
}
证书操作类
package com.hongan.lh.cert;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
public class HongAnCA {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// CreateRootCert("中国|广东省|深圳市|公司A|3650|1000000000000001|HARootPwd|c://ca//HARoot.pem|c://ca//HARoot.cer");
// BackupRootCert("c://ca//honganbackup.p12|p12pass|c://ca//HARoot.pem|HARootPwd|c://ca//HARoot.cer");
// RestoreRootCert("c://ca//honganbackup.p12|p12pass|c://ca//honganroot_restore.pem|privkeypass|c://ca//honganroot_restore.cer");
// CreateUserCert("中国|广东省|深圳市|一家|廖敏|111@163.com|3333333|365|1000000000000002|c://ca//廖敏.pem|user1pass|c://ca//廖敏.cer|c://ca//HARoot.pem|HARootPwd|c://ca//HARoot.cer");
// ExportCompanyKeyByUserCert("c://ca//companykey.dat|keypassword|c://ca//廖敏.cer|c://ca//廖敏.dat");
// CreateCompanyKey("ABCDEFGHIJKLMNOPQRSTUVWXYZ123456|c://ca//companykey.dat|keypassword");
// ExportCompanyKeyByUserCert("c://ca//companykey.dat|keypassword|c://ca//廖敏.cer|c://ca//廖敏.dat");
}
public static byte[] CreateRootCert(String certInfo) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String[] splt = certInfo.split("//|");
String country = splt[0];
String provice = splt[1];
String shi = splt[2];
String company = splt[3];
String validateTime = splt[4];
String seriszeString = splt[5];
String rootMiyuePwd = splt[6];
String rootMiyuePath = splt[7];
String rootcertPath = splt[8];
String certSubject = "C=" + country + ",S=" + provice + ",L=" + shi
+ ",O=" + company + ",CN=" + company;
KeyPair pair = HongAnUtils.generateRSAKeyPair();
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(new BigInteger(seriszeString));
certGen.setNotBefore(new Date(System.currentTimeMillis()));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ Long.parseLong(validateTime) * 24 * 60 * 60 * 1000L));
certGen.setSubjectDN(new X500Principal(certSubject));
certGen.setPublicKey(pair.getPublic());
certGen.setIssuerDN(new X500Principal(certSubject));
certGen.setSignatureAlgorithm("SHA1WithRSA");
X509Certificate certificate = certGen.generate(pair.getPrivate());
HongAnUtils.saveX509Certificate(certificate, rootcertPath);
HongAnUtils.savePEM(pair.getPrivate(), rootMiyuePwd, rootMiyuePath);
return certificate.getEncoded();
}
public static void BackupRootCert(String certInfo) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String[] splt = certInfo.split("//|");
String backPath = splt[0];
String backPwd = splt[1];
String rootMiyuePath = splt[2];
final String rootMiyuePwd = splt[3];
String rootCertPath = splt[4];
CertificateFactory factory = CertificateFactory.getInstance("X.509");
FileInputStream inputStream = new FileInputStream(rootCertPath);
X509Certificate certificate = (X509Certificate) factory
.generateCertificate(inputStream);
KeyPair key = HongAnUtils.getPrivateKey(rootMiyuePath, rootMiyuePwd);
Certificate[] chain = new Certificate[1];
chain[0] = certificate;
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store.load(null, null);
store.setCertificateEntry("root", certificate);
store.setKeyEntry("rootPriKey", key.getPrivate(), null, chain);
store.store(new FileOutputStream(backPath), backPwd.toCharArray());
}
public static void RestoreRootCert(String certInfo) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String[] splt = certInfo.split("//|");
String bakpath = splt[0];
String bakpwd = splt[1];
String yuanpem = splt[2];
String pempwd = splt[3];
String certPath = splt[4];
InputStream stream = new FileInputStream(bakpath);
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store.load(stream, bakpwd.toCharArray());
X509Certificate certificate = (X509Certificate) store
.getCertificate("root");
PrivateKey key = (PrivateKey) store.getKey("rootPriKey", null);
HongAnUtils.saveX509Certificate(certificate, certPath);
HongAnUtils.savePEM(key, pempwd, yuanpem);
}
// ca.CreateUserCert("中国|广东省|深圳市|一家|廖敏|111@163.com|3333333|365|1000000000000002|c://ca//廖敏.pem|user1pass|c://ca//于泳涛.cer|c://ca//HARoot.pem|HARootPwd|c://ca//HARoot.cer");
public static CertInfo CreateUserCert(String certInfo) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String[] splt = certInfo.split("//|");
String country = splt[0];
String provice = splt[1];
String shi = splt[2];
String company = splt[3];
String userName = splt[4];
String email = splt[5];
String cellphone = splt[6];
String validateTime = splt[7];
String seriszeString = splt[8];
String userpemPath = splt[9];
String userpemPwd = splt[10];
String usercertpath = splt[11];
String rootpempath = splt[12];
String rootpempwd = splt[13];
String rootcertpath = splt[14];
X509Certificate CA = HongAnUtils.getCertificate(rootcertpath);
String certSubject = "C=" + country + ",S=" + provice + ",L=" + shi
+ ",O=" + company + ",Email=" + email
+ ",0.9.2342.19200300.100.1.41 = " + cellphone + ",CN="
+ userName;
KeyPair pair = HongAnUtils.generateRSAKeyPair();
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(new BigInteger(seriszeString));
certGen.setNotBefore(new Date(System.currentTimeMillis()));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ Long.parseLong(validateTime) * 24 * 60 * 60 * 1000L));
certGen.setSubjectDN(new X500Principal(certSubject));
certGen.setPublicKey(pair.getPublic());
certGen.setIssuerDN(CA.getIssuerX500Principal());
certGen.setSignatureAlgorithm("SHA1WithRSA");
X509Certificate certificate = certGen.generate(pair.getPrivate());
byte[] src = certificate.getEncoded();
KeyPair key = HongAnUtils.getPrivateKey(rootpempath, rootpempwd);
// byte[] b = HongAnUtils.RSASign(key.getPrivate(), src);
X509CertImpl newcert = new X509CertImpl(src);
X509CertInfo info = (X509CertInfo) newcert.get(newcert.getName() + "."
+ newcert.INFO);
X509CertImpl export = new X509CertImpl(info);
export.sign(key.getPrivate(), "SHA1WithRSA");
HongAnUtils.savePEM(pair.getPrivate(), userpemPwd, userpemPath);
DEROutputStream stream = new DEROutputStream(new FileOutputStream(
usercertpath));
stream.write(export.getEncoded());
stream.close();
CertInfo cert = new CertInfo();
cert.setCert(certificate);
cert.setKey(pair);
return cert;
}
// 将字符串生成密钥文件利用密码保护
// ("ABCDEFGHIJKLMNOPQRSTUVWXYZ123456|c://ca//companykey.dat|keypassword");
public static void CreateCompanyKey(String strArgs) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String pwd = strArgs.split("//|")[0];
String savePathString = strArgs.split("//|")[1];
String baoPwd = strArgs.split("//|")[2];
char[] kouling = baoPwd.toCharArray();
PBEKeySpec spec = new PBEKeySpec(kouling);
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBEWithMD5AndDES");
SecretKey seKey = factory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
PBEParameterSpec pps = new PBEParameterSpec(new byte[] { 0xF, 0x0, 0x1,
0x2, 0x3, 0x4, 0x5, 0x6 }, 1);
cipher.init(Cipher.ENCRYPT_MODE, seKey, pps);
byte[] enbyte = cipher.doFinal(pwd.getBytes("utf-8"));
FileOutputStream stream = new FileOutputStream(savePathString);
stream.write(enbyte);
stream.close();
}
// 利用用户证书的公钥 给公司密钥加密生成用户密钥
// c://ca//companykey.dat|keypassword|c://ca//廖敏.cer|c://ca//廖敏.dat");
public static void ExportCompanyKeyByUserCert(String strArgs)
throws Exception {
Security.addProvider(new BouncyCastleProvider());
String[] splt = strArgs.split("//|");
String mimaPath = splt[0];
String mima = splt[1];
String rootCertPath = splt[2];
String usermimapath = splt[3];
FileInputStream input = new FileInputStream(mimaPath);
byte[] enbyte = new byte[input.available()];
input.read(enbyte);
input.close();
PBEKeySpec spec = new PBEKeySpec(mima.toCharArray());
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBEWithMD5AndDES");
SecretKey key = factory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
PBEParameterSpec pps = new PBEParameterSpec(new byte[] { 0xF, 0x0, 0x1,
0x2, 0x3, 0x4, 0x5, 0x6 }, 1);
cipher.init(Cipher.DECRYPT_MODE, key, pps);
byte[] debyte = cipher.doFinal(enbyte);
PublicKey pk = (PublicKey) HongAnUtils.getCertificate(rootCertPath)
.getPublicKey();
byte[] enbyteagain = HongAnUtils.encrypt(pk, debyte, "RSA");
HongAnUtils.write(usermimapath, enbyteagain);
}
}