用java签发数字证书代码

 package com.koalii.eseal.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.CertificationRequestInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure;
import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure;

import com.koalii.eseal.info.EsealInfo;

public class CertUtil {
 private Logger logger = Logger.getLogger(this.getClass());
 private String signAlgorithm = "SHA1WithRSA";

 /**
  * 生成请求文件,输入文件名,SUBJECTDN,KEYPAIR;返回文件名;
  * @param fullFileName
  * @param subjectDN
  * @param subjectKeyPair
  * @return
  */
 public String createCertRequest(String fullFileName, String subjectDN,
   KeyPair subjectKeyPair) {
  try {
   PKCS10CertificationRequest req = new PKCS10CertificationRequest(
     signAlgorithm, new X509Name(subjectDN), subjectKeyPair
       .getPublic(), null, subjectKeyPair.getPrivate());
   FileOutputStream fout = new FileOutputStream(new File(fullFileName));
   fout.write(Base64.encode(req.getEncoded()));
   fout.close();
   return fullFileName;
  } catch (Exception e) {
   logger.error("createCertRequest error." + e.getMessage());
  }
  return null;
 }
 
 
 /**
  * 生成请求对象,输入SUBJECTDN,KEYPAIR;返回请求对象;
  * @param subjectDN
  * @param subjectKeyPair
  * @return
  */
 public PKCS10CertificationRequest createCertRequest(String subjectDN,
   KeyPair subjectKeyPair) {
  try {
   PKCS10CertificationRequest req = new PKCS10CertificationRequest(
     signAlgorithm, new X509Name(subjectDN), subjectKeyPair
       .getPublic(), null, subjectKeyPair.getPrivate());

   return req;
  } catch (Exception e) {
   logger.error("createCertRequest error." + e.getMessage());
  }
  return null;
 }

 /**
  * 生成根证书,返回证书对象
  * @param issuerDN
  * @param validityDays
  * @param rootkeypair
  * @return
  */
 public X509Certificate signRootCert(String issuerDN, int validityYears, KeyPair rootkeypair) {
  // // signers name
  // String issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy ROOT
  // // subjects name - the same as we are self signed.
  // String subject = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy ROOT

  String subjectDN = issuerDN;
  // create the certificate - version 1
  X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator();
  v1CertGen.setSerialNumber( this.createSerialNum());
  v1CertGen.setIssuerDN(new X509Principal(issuerDN));
  Date start = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 0);
  v1CertGen.setNotBefore(start);
  Date end = DateUtil.validdate(validityYears, start);
  //new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * validityDays))
  v1CertGen.setNotAfter(end);
  v1CertGen.setSubjectDN(new X509Principal(subjectDN));
  v1CertGen.setPublicKey(rootkeypair.getPublic());
  v1CertGen.setSignatureAlgorithm(signAlgorithm);

  X509Certificate cert = null;
  try {
   cert = v1CertGen.generate(rootkeypair.getPrivate());
  } catch (CertificateEncodingException e) {
   e.printStackTrace();
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (IllegalStateException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (SignatureException e) {
   e.printStackTrace();
  }
//  cert.checkValidity(new Date());
//  cert.verify(pubKey);
//  PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;
//  //
//  // this is actually optional - but if you want to have control
//  // over setting the friendly name this is the way to do it...
//  //
//  bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
//    new DERBMPString("Bouncy Primary Certificate"));

  return cert;

 }

 /**
  * 根据证书请求文件,签发下级证书,返回证书对象
  * @param subjectRequestFilename
  * @param issuerCert
  * @param issuerKeyPair
  * @param validityDays
  * @return
  */
 public X509Certificate signSubCert(String subjectRequestFilename,
   X509Certificate issuerCert, PrivateKey issuerPrivateKey, int validityDays) {
  File file = new File(subjectRequestFilename);
  try {
   FileInputStream fin = new FileInputStream(file);
   byte[] b = new byte[(int) file.length()];
   fin.read(b);
   fin.close();

   return this.signSubCert(b, issuerCert, issuerPrivateKey, validityDays);
  } catch (Exception e) {
   logger.error("signCert error." + e.getMessage());
  }
  return null;

 }

 /**
  * 根据证书请求的内容,签发下级证书,返回证书对象
  * @param subjectRequestFilename
  * @param issuerCert
  * @param issuerKeyPair
  * @param validityDays
  * @return
  */
 public X509Certificate signSubCert(byte[] requestContent,
   X509Certificate issuerCert, PrivateKey issuerPrivateKey, int validityDays) {
  try {
   PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(requestContent));
   PublicKey subjectPublicKey = csr.getPublicKey();
   CertificationRequestInfo CSRInfo = csr
     .getCertificationRequestInfo();
   X509Name subjectDN = CSRInfo.getSubject();
   // ASN1Set attributes = CSRInfo.getAttributes();

   // set generator's params: subCA's DN/serialNumber/date
   X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
   certGen.setSignatureAlgorithm(signAlgorithm);
   // subject's DN/publicKey
   certGen.setSubjectDN(subjectDN);
   certGen.setPublicKey(subjectPublicKey);
   // subCA's info
   certGen.setIssuerDN(issuerCert.getSubjectX500Principal());
   certGen.setSerialNumber( this.createSerialNum());
   certGen.setNotBefore(issuerCert.getNotBefore());
   certGen.setNotAfter(issuerCert.getNotAfter());
   // extensions
   certGen.addExtension(X509Extensions.SubjectKeyIdentifier,
    false, new SubjectKeyIdentifierStructure(subjectPublicKey));
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier,
    false, new AuthorityKeyIdentifierStructure(issuerCert.getPublicKey()));

   X509Certificate cert = certGen.generate(issuerPrivateKey,"BC");
   return cert;
  } catch (Exception e) {
   logger.error("signCert error." + e.getMessage());
  }
  return null;

 }
 
 /**
  *
  * 根据请求者DN和请求者KEYPAIR,签发证书,返回证书对象
  * @param subjectDN
  * @param subjectPeyPair
  * @param issuerCert
  * @param issuerKeyPair
  * @param validityDays
  * @return
  */
 public X509Certificate signSubCert(String subjectDN,
   PublicKey subjectPublicKey, X509Certificate issuerCert,
   PrivateKey issuerPrivateKey, int validityDays) {
  try {
   X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
   v3CertGen.setSerialNumber( this.createSerialNum());
   // v3CertGen.setIssuerDN(getSubjectX509Principal(rootCACert));// or
   v3CertGen.setIssuerDN(issuerCert.getSubjectX500Principal());
   v3CertGen.setSubjectDN(new X509Principal(subjectDN));
   Date start = new Date(System.currentTimeMillis() - 0);
   v3CertGen.setNotBefore(start);
   Date end = DateUtil.validdate(validityDays, start);
   //new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * validityDays))
   v3CertGen.setNotAfter(end);
   v3CertGen.setPublicKey(subjectPublicKey);
   v3CertGen.setSignatureAlgorithm(signAlgorithm);

   v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier,
   false, new  SubjectKeyIdentifierStructure(subjectPublicKey));
   v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier,
   false, new AuthorityKeyIdentifierStructure(issuerCert));
   
   X509Certificate subCA_Cert = v3CertGen.generate(issuerPrivateKey);
   // subCA_Cert.checkValidity(new Date());
   // subCA_Cert.verify(issuerKeyPair.getPublic());

   return subCA_Cert;
  } catch (Exception e) {
   logger.error("signCert error." + e.getMessage());
  }
  return null;
 }

 /**
  * 根据签章请求内容(BASE64),返回X509格式的证书
  * @param esealRequest
  * @param issuerCert
  * @param issuerKeyPair
  * @return
  */
 public X509Certificate signESeal(String esealRequest,
   X509Certificate issuerCert, PrivateKey issuerPrivateKey) {
  byte[] derCode = Base64.decode(esealRequest.getBytes());
  PKCS10CertificationRequest csr = new PKCS10CertificationRequest(derCode);
  try {
   logger.info("ESeal request info:==============");
   PublicKey subjectPublicKey = csr.getPublicKey();
   System.out.println("Requester publickey: " + subjectPublicKey);

   CertificationRequestInfo CSRInfo = csr.getCertificationRequestInfo();
   X509Name subjectDN = CSRInfo.getSubject();
   System.out.println("Requester subjectDN: " + subjectDN);

   X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
   certGen.setSignatureAlgorithm(signAlgorithm);
   // subject's DN/publicKey
   certGen.setSubjectDN(subjectDN);
   certGen.setPublicKey(subjectPublicKey);
   // subCA's info
   //certGen.setIssuerDN(this.getSubjectX509Principal(issuerCert));
   certGen.setIssuerDN(issuerCert.getSubjectX500Principal());
   certGen.setSerialNumber(this.createSerialNum());

   //NotBefore/NotAfter in extensions
   //certGen.setNotBefore(issuerCert.getNotBefore());
   //certGen.setNotAfter(issuerCert.getNotAfter());
   
   // extensions
   certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
     new SubjectKeyIdentifierStructure(subjectPublicKey));
   certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
     new AuthorityKeyIdentifierStructure(issuerCert.getPublicKey()));
   
   ASN1Set attributes = CSRInfo.getAttributes();
   for (int i = 0; i != attributes.size(); i++) {
    Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
    if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
           X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

           Enumeration e = extensions.oids();
           while (e.hasMoreElements()) {
             DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
             X509Extension ext = extensions.getExtension(oid);
            DateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss 'GMT'", Locale.CHINA);
          formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
             if(oid.getId().equals(ESealUtil.ExtesealNotBeforeOID.getId())){
            Date notBefore = formatter.parse((new String(ext.getValue().getOctets()))); 
        certGen.setNotBefore(notBefore);
             }else if(oid.getId().equals(ESealUtil.ExtesealNotAfterOID.getId())){
            Date notAfter = formatter.parse((new String(ext.getValue().getOctets()))); 
        certGen.setNotAfter(notAfter);
             }else{
              certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
              //certGen.addExtension(oid, ext.isCritical(), ext.getValue());
             }
           }
         }
   }

// If attribute=DERSet(extensions) that is  new PKCS10CertificationRequest(signAlgorithm, new X509Name(subjectDN), esealKeyPair.getPublic(),  new DERSet(extensions), esealKeyPair.getPrivate());   
//   if (attributes != null) {
//    Enumeration enums = attributes.getObjects();
//    addCustomExtensions(enums, certGen);
//   }

   X509Certificate cert = certGen.generate(issuerPrivateKey,"BC");
   System.out.println("ESealCert info:=============");
   System.out.println(cert.toString());
   return cert;
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (NoSuchProviderException e) {
   e.printStackTrace();
  } catch (CertificateParsingException e) {
   e.printStackTrace();
  } catch (CertificateEncodingException e) {
   e.printStackTrace();
  } catch (IllegalStateException e) {
   e.printStackTrace();
  } catch (SignatureException e) {
   e.printStackTrace();
  } catch (ParseException e) {
   e.printStackTrace();
  }

  return null;
 }
 
 /**
  * 将证书和私钥保存到KEYSTORE
  * @param fullFileName
  * @param certChain
  * @param keyPair
  * @param keyentry_alias
  * @param storepass
  * @return
  */
 public String saveCertChainToKeyStore(String fullFileName, X509Certificate[] certChain, KeyPair keyPair,
   String keyentry_alias, String storepass) {
  try {
   KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");

   keyStore.load(null, null);
   keyStore.setKeyEntry(keyentry_alias, keyPair.getPrivate(), storepass
     .toCharArray(),certChain);

   FileOutputStream fOut = new FileOutputStream(fullFileName);
   keyStore.store(fOut, storepass.toCharArray());
   fOut.close();
   return fullFileName;
  } catch (Exception e) {
   logger.error("Save cert error." + e.getMessage());
  }
  return null;
 }
 
 /**
  * 将证书和私钥保存到KEYSTORE
  * @param fullFileName
  * @param certChain
  * @param keyPair
  * @param keyentry_alias
  * @param storepass
  * @return
  */
 public String saveCertChainToExistKeyStore(String fullFileName, X509Certificate[] certChain, KeyPair keyPair,
   String keyentry_alias, String storepass) {
  try {
   InputStream inStream = new FileInputStream(fullFileName);
   KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");

   keyStore.load(inStream, storepass.toCharArray());
   keyStore.setKeyEntry(keyentry_alias, keyPair.getPrivate(), storepass
     .toCharArray(),certChain);
   inStream.close();
   FileOutputStream fOut = new FileOutputStream(fullFileName);
   keyStore.store(fOut, storepass.toCharArray());
   fOut.close();
   return fullFileName;
  } catch (Exception e) {
   logger.error("Save cert error." + e.getMessage());
  }
  return null;
 }

 /**
  * 将证书保存到证书文件.CER
  * @param fullFileName
  * @param cert
  */
 public void saveCertToFile(String fullFileName, X509Certificate cert) {
  try {
    FileOutputStream fout = new FileOutputStream(new File(fullFileName));
          fout.write(cert.getEncoded());
          fout.close();
  } catch (Exception e) {
   logger.error("Save cert error." + e.getMessage());
  }
 }

 /**
  * 仅将证书保存到KEYSTORE
  * @param fullFileName
  * @param cert
  * @param cert_alias
  * @param storepass
  * @return
  */
 public String saveCertToKeyStore(String fullFileName, X509Certificate cert, String cert_alias, String storepass) {
  try {
   KeyStore keyStore = KeyStore.getInstance("JKS");
   keyStore.load(null, null);
   keyStore.setCertificateEntry(cert_alias, cert);
   //keyStore.setKeyEntry(cert_alias, null, new X509Certificate[]{cert} );
   FileOutputStream fOut = new FileOutputStream(fullFileName);
   keyStore.store(fOut, storepass.toCharArray());
   fOut.close();
   return fullFileName;
  } catch (Exception e) {
   logger.error("Save cert error." + e.getMessage());
  }
  return null;
 }
 
 /**
  * 从KEYSTORE中获取私钥
  * @param fullFileName
  * @param alias
  * @param storepass
  * @return
  */
 public PrivateKey getPrivateFromKeyStore(String fullFileName, String alias,String storepass){
  PrivateKey priKey = null;
  try {
   KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
   InputStream inStream = new FileInputStream(fullFileName);
   keyStore.load(inStream, storepass.toCharArray());
   priKey = (PrivateKey)keyStore.getKey(alias, storepass.toCharArray());
   inStream.close();
  } catch (KeyStoreException e) {
   e.printStackTrace();
  } catch (NoSuchProviderException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (CertificateException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (UnrecoverableKeyException e) {
   e.printStackTrace();
  }
  return priKey;
 }
 
 /**
  * 从证书文件获取公钥
  * @param fullFileName
  * @return
  */
 public PublicKey getPublicKeyFromCertFile(String fullFileName){
  X509Certificate cert = this.getCertFromCertFile(fullFileName);
  return cert.getPublicKey();
 }
 /**
  * 从证书文件获取证书对象
  * @param fullFileName
  * @return
  */
 public X509Certificate getCertFromCertFile(String fullFileName){
  try {
   FileInputStream in = new FileInputStream(fullFileName);    
   CertificateFactory  cf = CertificateFactory.getInstance("X.509");
   X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
   in.close();
   return cert;
  } catch (CertificateException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * 从KEYSTORE中,根据证书别名获取证书
  * @param fullFileName
  * @param cert_alias
  * @param storepass
  * @return
  */
 public X509Certificate getCertFromKeyStoreFile(String fullFileName,String cert_alias,String storepass,String storeType){
  KeyStore keyStore = null;
  try {
   if("PKCS12".equals(storeType.toUpperCase())){
    keyStore = KeyStore.getInstance("PKCS12", "BC");
   }else if("JKS".equals(storeType.toUpperCase())){
    keyStore = KeyStore.getInstance("JKS");
   }
   InputStream inStream = new FileInputStream(fullFileName);
   keyStore.load(inStream, storepass.toCharArray());
   inStream.close();

   return (X509Certificate)keyStore.getCertificate(cert_alias);
  } catch (KeyStoreException e) {
   e.printStackTrace();
  } catch (NoSuchProviderException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (CertificateException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * 从KEYSTORE中,根据私钥别名获取证书链
  * @param fullFileName
  * @param key_alias
  * @param storepass
  * @return
  */
 public Certificate[] getCertChainFromKeyStoreFile(String fullFileName,String key_alias,String storepass){
  try {
   KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
   InputStream inStream = new FileInputStream(fullFileName);
   keyStore.load(inStream, storepass.toCharArray());
   inStream.close();
   Certificate[] certs = (Certificate[])keyStore.getCertificateChain(key_alias);
   return certs;
  } catch (KeyStoreException e) {
   e.printStackTrace();
  } catch (NoSuchProviderException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (CertificateException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }

 
 /**
  * 从base64编码的字符串解码中出证书
  * @param base64Cert
  * @return
  * @throws Exception
  */
 public static X509Certificate getCertFromBase64String(String base64Cert)
   throws Exception {
  X509Certificate cert = null;
  ByteArrayInputStream bin = null;
  try {
   bin = new ByteArrayInputStream(Base64.decode(base64Cert));
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   if (bin.available() > 0) {
    cert = (X509Certificate) cf.generateCertificate(bin);
   }
  } catch (CertificateException e) {
   throw e;
  } finally {
   if (bin != null) {
    try {
     bin.close();
     bin = null;
    } catch (IOException e) {
     //do nothing
    }

   }
  }
  return cert;
 }
 /**
  * 从KEYSTORE中同时获取私钥和证书
  * @param fullFileName
  * @param alias
  * @param storepass
  * @param privateKey
  * @param cert
  */
 public void getPrivateKeyAndCertFromKeyStoreFile(String fullFileName,String alias,String storepass, PrivateKey privateKey, X509Certificate cert){
  try {
   InputStream inStream = new FileInputStream(fullFileName);
   KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
   keyStore.load(inStream, storepass.toCharArray());
   privateKey = (PrivateKey)keyStore.getKey(alias, storepass.toCharArray());
   Certificate[] certs = keyStore.getCertificateChain(alias);
   cert = (X509Certificate) certs[0];
   inStream.close();
  } catch (KeyStoreException e) {
   e.printStackTrace();
  } catch (NoSuchProviderException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (CertificateException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (UnrecoverableKeyException e) {
   e.printStackTrace();
  }
 }
 
  public X509Certificate[] parseB64Cert(String b64Cert)
     {
         return parseDerCert(Base64.decode(b64Cert.getBytes()));
     }

     public X509Certificate[] parseDerCert(byte[] derCert)
     {
         try
         {
             CertificateFactory cf = CertificateFactory.getInstance("X.509");
             Collection col = cf.generateCertificates(new ByteArrayInputStream(derCert));
             int clen = col.size();
             X509Certificate[] x509s = new X509Certificate[clen];
             col.toArray(x509s);
             return x509s;
         }
         catch (Exception exp)
         {
             throw new IllegalArgumentException("parse der cert  - " + exp);
         }
     }
    
     /**
   * @param subjectName
   */
  public static String parseEsealName(String subjectName) {
   String[] subject = subjectName.split(",");
   int size = subject.length;
   if(!"".equals(subjectName)){
    for (int i = 0; i < size; i++) {
     if(subject[i].indexOf("CN=")>=0){
      return subject[i].replaceAll("CN=", "");
     }
    }
   }
   return null;
   
  }
  
  public static String parseOrg(String subjectName) {
   String[] subject = subjectName.split(",");
   int size = subject.length;
   if(!"".equals(subjectName)){
    for (int i = 0; i < size; i++) {
     if(subject[i].indexOf("O=")>=0){
      return subject[i].replaceAll("O=", "");
     }
    }
   }
   return null;
   
  }
  
  public static String parseST(String subjectName) {
   String[] subject = subjectName.split(",");
   int size = subject.length;
   if(!"".equals(subjectName)){
    for (int i = 0; i < size; i++) {
     if(subject[i].indexOf("ST=")>=0){
      return subject[i].replaceAll("ST=", "");
     }
    }
   }
   return null;
   
  }
  
  public static String parseLocal(String subjectName) {
   String[] subject = subjectName.split(",");
   int size = subject.length;
   if(!"".equals(subjectName)){
    for (int i = 0; i < size; i++) {
     if(subject[i].indexOf("L=")>=0){
      return subject[i].replaceAll("L=", "");
     }
    }
   }
   return null;
   
  }
 
 
// private void addCustomExtensions(Enumeration enums, X509V3CertificateGenerator certGen){
//  //DERSet extensionSet = null;
//  DERObjectIdentifier oid = null;
//  DEROctetString value = null;
//  while (enums.hasMoreElements()) {
//    Object obj = enums.nextElement();
//    if(obj instanceof DERObjectIdentifier){
//     System.out.println("DERObjectIdentifier obj: " + obj);
//     oid = (DERObjectIdentifier) obj;
//    }else if(obj instanceof DEROctetString){
//     value = (DEROctetString)obj;
//     System.out.println("DEROctetString value: " + new String(value.getOctets()));
//     if(oid!=null && value!=null){
//      certGen.addExtension(oid, true,new DEROctetString(value.getOctets()));
//      oid = null;
//      value = null;
//     }
//    }else {
//     Enumeration enum2= ((DERSequence)obj).getObjects();
//     this.addCustomExtensions(enum2, certGen);
//    }
   }else if 
    
    while(enums2.hasMoreElements()){
     obj = enums2.nextElement();
     if(obj instanceof DERSequence){
      sequence = (DERSequence)obj;
      Enumeration enums3 = sequence.getObjects();
      DERObjectIdentifier oid = null;
      DEROctetString value = null;
      while(enums3.hasMoreElements()){
       Object derobj = enums3.nextElement();
       if(derobj instanceof DERObjectIdentifier){
        System.out.println("DERObjectIdentifier obj: " + derobj);
        oid = (DERObjectIdentifier) derobj;
       }else if(derobj instanceof DEROctetString){
        value = (DEROctetString)derobj;
        System.out.println("DEROctetString value: " + new String(value.getOctets()));
        if(oid!=null && value!=null){
         certGen.addExtension(oid, true,new DEROctetString(value.getOctets()));
         oid = null;
         value = null;
        }
       }else{
        System.out.println("Unknown obj: " + derobj);
       }
      }
     }
    }
   }
//  }
// }

// private X509Principal getSubjectX509Principal(X509Certificate cert)
//   throws CertificateEncodingException {
//  try {
//   ByteArrayInputStream bIn = new ByteArrayInputStream(cert
//     .getTBSCertificate());
//   ASN1InputStream aIn = new ASN1InputStream(bIn);
//   TBSCertificateStructure tbsCert = new TBSCertificateStructure(
//     (ASN1Sequence) aIn.readObject());
//
//   X509Principal princ = new X509Principal(tbsCert.getSubject());
//   return princ;
//  } catch (IOException e) {
//   throw new CertificateEncodingException(e.toString());
//  }
// }

 private BigInteger createSerialNum(){
  SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
  String newtime = format.format(Calendar.getInstance().getTime());
  String newrandom = String.valueOf((int)(Math.random()*100)+1);
  return BigInteger.valueOf(Long.valueOf(newtime+newrandom).longValue());
 }
 

 public static void main(String[] args) {
  CertUtil certUtil = new CertUtil();
  //root CA
  KeyPair rootkeypair = KeyUtil.generateKeyPair(2048);
  String issuerDN = "C=cn,ST=bj,L=beijing,O=o1,OU=ou1,CN=I am a rootCA";
  X509Certificate rootCert =  certUtil.signRootCert(issuerDN, 365, rootkeypair);
  certUtil.saveCertChainToKeyStore("D:/RootCA.pfx", new X509Certificate[]{rootCert}, rootkeypair, "rootca", "123456");
  certUtil.saveCertToFile("d:/rootca.cer", rootCert);
  certUtil.saveCertToKeyStore("d:/truststore.pfx", rootCert, "trustcert", "123456");
  //sub CA
  KeyPair subkeypair = KeyUtil.generateKeyPair(1024);
  String subjectDN = "C=cn,ST=bj,L=beijing,O=o1,OU=ou1,CN=localhost";
  X509Certificate subCert =  certUtil.signSubCert(subjectDN, subkeypair.getPublic(), rootCert, rootkeypair.getPrivate(), 365);
  certUtil.saveCertToFile("d:/subca1.cer", subCert);
  certUtil.saveCertChainToKeyStore("D:/SubCA1.pfx", new X509Certificate[]{subCert,rootCert}, subkeypair, "ESEALCA2009081011121355588", "123456");

  subjectDN = "C=cn,ST=bj,L=beijing,O=o1,OU=ou1,CN=I am a subCA2";
  subCert =  certUtil.signSubCert(subjectDN, subkeypair.getPublic(), rootCert, rootkeypair.getPrivate(), 365);
  certUtil.saveCertToFile("d:/subca2.cer", subCert);
  certUtil.saveCertChainToKeyStore("D:/SubCA2.pfx", new X509Certificate[]{subCert,rootCert}, subkeypair, "ESEALCA2009081011121355588", "123456");
  //X509Certificate trustcert = certUtil.getCertFromKeyStoreFile("D:/truststore.pfx", "trustcert", "123456","JKS");
  //Certificate[] certchain = certUtil.getCertChainFromKeyStoreFile("D:/SubCA.pfx", "subca",  "123456");
  //ESeal
  ESealUtil esealUtil = new ESealUtil();
  EsealInfo info = new EsealInfo();
  info.setVersion(1);
  info.setEsealName("I am a user");
  info.setPictureData(new byte[] { '1', '2', '3' });
  info.setEsealNotBefore(Calendar.getInstance().getTime());
  info.setEsealNotAfter(Calendar.getInstance().getTime());
  String[] userAttrs = new String[]{"name=li","id=100","sex=1"};
  for(int i=0;i<userAttrs.length;i++){
   info.getUserAttr().add(userAttrs[i]);
  }
  
  X509Certificate signCert = certUtil.getCertFromCertFile("business_der.cer");
  try {
   info.setDerSignCert(signCert.getEncoded());
  } catch (CertificateEncodingException e) {
   e.printStackTrace();
  }
  KeyPair esealkeypair = KeyUtil.generateKeyPair(1024);
  //eseal request
  String esealRequest = esealUtil.createESealRequest(info, esealkeypair);
  //eseal cert
  X509Certificate esealCert = certUtil.signESeal(esealRequest, subCert, subkeypair.getPrivate());
  certUtil.saveCertToFile("D:/eseal.cer", esealCert);
  esealUtil.parseESealCert(esealCert);
  
  
//  byte[] b = new Hex().decode("433d636e2c53543d626a2c4c3d6265696a696e672c4f3d6f312c4f553d6f75312c434e3d4920616d20612075736572");
//  System.out.println(new String(b));
//  BigInteger bit = certUtil.createSerialNum();
//  System.out.println(bit.longValue());
  System.out.println("OK");
 }
 
 
}

 

//私钥的处理类

package com.koalii.eseal.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;

import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

public class KeyUtil {
 private static Logger logger = Logger.getLogger(KeyUtil.class);
 
 public static KeyPair generateKeyPair(int keySize){
  Security.addProvider(new BouncyCastleProvider());
  try {
   KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA","BC");
   keyGen.initialize(keySize, new SecureRandom());
   KeyPair keyPair = keyGen.generateKeyPair();
   logger.info("Generate new keypair.");
   return keyPair;
  } catch (NoSuchAlgorithmException e) {
   logger.error(e.getMessage());
  } catch (NoSuchProviderException e) {
   logger.error(e.getMessage());
  }
  return null;
 }
 
 /**
  * @param oriData
  * @return digestpass base64的摘要结果
  *
  * sha-1摘要算法
  * */
 public static String keyStorePassDgt(String oriData){
  return keyStorePassDgt(oriData.getBytes());
  
 }
 
 public static String keyStorePassDgt(byte[] oriData){
  byte[] digest = keyStorePassDgtByte(oriData);
  String digestpass = new String(Base64.encode(digest));
  
  return digestpass;
 }
 
 public static byte[] keyStorePassDgtByte(byte[] oriData){
  MessageDigest dgt = null;
  try
  {
   dgt = MessageDigest.getInstance("SHA-1");
  }
  catch (NoSuchAlgorithmException e)
  {
   logger.error(e.getMessage());
  }
  
  return dgt.digest(oriData);
 }
 
 
}

 

 

 

//应网友要求,现将ESealUtil、Esealinfo类贴出来

 

package com.koalii.eseal.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.MessageDigest;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.X509CertificateStructure;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.util.encoders.Base64;

import com.koalii.eseal.info.Eseal;
import com.koalii.eseal.info.EsealInfo;

/**
 * ESealUtil.java
 *
 * @CopyRight KOAL Co. Lmt 2009
 * @author zhengxd
 * @Since
 * @version
 * @Date: 2009-8-8
 */
public class ESealUtil {
 private Logger logger = Logger.getLogger(this.getClass());
 private String signAlgorithm = "SHA1WithRSA";
 private Eseal eseal;

 // Basic info
 public final static DERObjectIdentifier ExtVersionOID = new DERObjectIdentifier(
   "2.16.156.514556.311");
 public final static DERObjectIdentifier ExtesealNotBeforeOID = new DERObjectIdentifier(
   "2.16.156.514556.318");
 public final static DERObjectIdentifier ExtesealNotAfterOID = new DERObjectIdentifier(
   "2.16.156.514556.319");
 // Business cert info
 public final static DERObjectIdentifier ExtSignCertSubjectOID = new DERObjectIdentifier(
   "2.16.156.514556.312");
 public final static DERObjectIdentifier ExtSignCertSnOID = new DERObjectIdentifier(
   "2.16.156.514556.313");
 public final static DERObjectIdentifier ExtSignCertIssuerOID = new DERObjectIdentifier(
   "2.16.156.514556.314");
 public final static DERObjectIdentifier ExtSignCertHashOID = new DERObjectIdentifier(
   "2.16.156.514556.315");
 // pic info
 public final static DERObjectIdentifier ExtPictureTypeOID = new DERObjectIdentifier(
   "2.16.156.514556.316");
 public final static DERObjectIdentifier ExtPictureDataOID = new DERObjectIdentifier(
   "2.16.156.514556.302");
 // ext attribute
 public final static DERObjectIdentifier ExtAttrNameOID = new DERObjectIdentifier(
   "2.16.156.514556.100");
 public final static DERObjectIdentifier ExtEsealAttrOID = new DERObjectIdentifier(
   "2.16.156.514556.301");
 public final static DERObjectIdentifier ExtUserAttrOID = new DERObjectIdentifier(
   "2.16.156.514556.303");

 /**
  * @return the esealInfo
  */
 public Eseal getEseal() {
  return eseal;
 }

 /**
  * 根据esealInfo添加证书申请的扩展项
  *
  * @param esealInfo
  * @param esealKeyPair
  * @return
  */
 public String createESealRequest(EsealInfo esealInfo, KeyPair esealKeyPair) {
  try {
   // Extensions object
   Vector oids = new Vector();
   Vector values = new Vector();

   DateFormat formatter = new SimpleDateFormat(
     "dd MM yyyy HH:mm:ss 'GMT'", Locale.CHINA);
   formatter.setTimeZone(TimeZone.getTimeZone("GMT"));

   oids.add(ExtVersionOID);
   values.add(new X509Extension(true, new DEROctetString(
     new DERInteger(esealInfo.getVersion()))));

   oids.add(ExtesealNotBeforeOID);
   String notBefore = formatter.format(esealInfo.getEsealNotBefore());
   values.add(new X509Extension(true, new DEROctetString(notBefore
     .getBytes())));

   oids.add(ExtesealNotAfterOID);
   String notAfter = formatter.format(esealInfo.getEsealNotAfter());
   values.add(new X509Extension(true, new DEROctetString(notAfter
     .getBytes())));

   X509Certificate[] signCerts = this.parseDerCert(esealInfo
     .getDerSignCert());
   X509Certificate signCert = signCerts[0];

   // sign cert info
   oids.add(ExtSignCertSubjectOID);
   values.add(new X509Extension(true, new DEROctetString(new X509Name(
     false, signCert.getSubjectDN().getName()))));
   // values.add(new X509Extension(true, new
   // DEROctetString(subjectDN.getBytes())));

   oids.add(ExtSignCertSnOID);
   values.add(new X509Extension(true, new DEROctetString(
     new DERInteger(signCert.getSerialNumber()))));

   oids.add(ExtSignCertIssuerOID);
   values.add(new X509Extension(true, new DEROctetString(new X509Name(
     false, signCert.getIssuerDN().getName()))));

   MessageDigest dgt = MessageDigest.getInstance("SHA-1");
   byte[] digest = dgt.digest(esealInfo.getDerSignCert());

   oids.add(ExtSignCertHashOID);
   values.add(new X509Extension(true, new DEROctetString(
     new DERBitString(digest))));

   // pic info
   if (esealInfo.getPictureType() > -1) {
    oids.add(ExtPictureTypeOID);
    values.add(new X509Extension(true, new DEROctetString(
      new DERInteger(esealInfo.getPictureType()))));
   }

   if (esealInfo.getPictureData() != null) {
    oids.add(ExtPictureDataOID);
    values.add(new X509Extension(true, new DEROctetString(
      new DERBitString(esealInfo.getPictureData()))));
   }

   // ext attribute
   if (esealInfo.getEsealAttr() != null) {
    oids.add(ExtEsealAttrOID);
    values.add(new X509Extension(true, new DEROctetString(this
      .attrToASN1Encodable(esealInfo.getEsealAttr()))));
   }
   if (esealInfo.getUserAttr() != null) {
    oids.add(ExtUserAttrOID);
    values.add(new X509Extension(true, new DEROctetString(this
      .attrToASN1Encodable(esealInfo.getUserAttr()))));
   }

   // P10 request
   String subjectDN = "cn=" + esealInfo.getEsealName()
     + ", ou=koaliieseal";
   X509Extensions extensions = new X509Extensions(oids, values);
   Attribute attribute = new Attribute(
     PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
     new DERSet(extensions));
   PKCS10CertificationRequest req = new PKCS10CertificationRequest(
     signAlgorithm, new X509Name(subjectDN), esealKeyPair
       .getPublic(), new DERSet(attribute), esealKeyPair
       .getPrivate());

   return new String(Base64.encode(req.getEncoded()));
  } catch (Exception e) {
   logger.error("createCertRequest error." + e.getMessage());
  }
  return null;
 }

 private static DERObject derObjectDecode(byte[] derData) {
  ASN1InputStream ain = null;
  try {
   ain = new ASN1InputStream(derData);
   return ain.readObject();
  } catch (IOException exp) {
   throw new IllegalArgumentException(exp.getMessage());
  } finally {
   try {
    ain.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

 }

 public void parseESealCert(X509Certificate esealCert) {

  eseal = new Eseal();

  // basic info
  eseal.setEsealSn(esealCert.getSerialNumber());
  parseEsealName(esealCert.getSubjectDN().getName());
  eseal.setIssuerDN(esealCert.getIssuerDN().getName());
  eseal.setEsealNotBefore(esealCert.getNotBefore());
  eseal.setEsealNotAfter(esealCert.getNotAfter());

  // sign cert info

  X509Extensions exts = null;
  try {
   X509CertificateStructure esealcertStruct = X509CertificateStructure
     .getInstance(ASN1Object.fromByteArray(esealCert
       .getEncoded()));
   exts = esealcertStruct.getTBSCertificate().getExtensions();
  } catch (CertificateEncodingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

  Enumeration enums = exts.oids();
  while (enums.hasMoreElements()) {
   DERObjectIdentifier oid = (DERObjectIdentifier) enums.nextElement();
   //System.out.println("oid: " + oid);
   byte[] bvalue = esealCert.getExtensionValue(oid.getId());

   // 1 if certGen.addExtension(oid, ext.isCritical(),
   // ext.getValue().getOctets());
   try {
    ASN1Object derObj = ASN1Object.fromByteArray(bvalue);
    if (derObj instanceof DEROctetString) {// customer extension
              // must DEROctetString
     byte[] value = ((DEROctetString) derObj).getOctets();
     if (oid.getId().endsWith(ExtSignCertSubjectOID.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      X509Name x509name = new X509Name((DERSequence) derObj);
      eseal.setSignCertSubject(x509name.toString());
     } else if (oid.getId().equals(ExtSignCertIssuerOID.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      X509Name x509name = new X509Name((DERSequence) derObj);
      eseal.setSignCertIssuer(x509name.toString());
     } else if (oid.getId().equals(ExtSignCertSnOID.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      DERInteger serialNum = DERInteger.getInstance(derObj);
      eseal.setSignCertSn(serialNum.getValue());
     } else if (oid.getId().equals(ExtPictureDataOID.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      DERBitString picData = DERBitString.getInstance(derObj);
      eseal.setPictureData(picData.getBytes());
     } else if (oid.getId().equals(ExtUserAttrOID.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      ArrayList userList = parseAttr(derObj.getEncoded());
      eseal.setUserAttr(userList);
     } else if (ExtEsealAttrOID.getId().equals(oid.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      ArrayList esealList = parseAttr(derObj.getEncoded());
      eseal.setEsealAttr(esealList);
     } else if (ExtVersionOID.getId().equals(oid.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      DERInteger verision = DERInteger.getInstance(derObj);
      eseal.setVersion(verision.getValue().intValue());
     } else if (ExtSignCertHashOID.getId().equals(oid.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      DERBitString hashsign = DERBitString
        .getInstance(derObj);
      eseal.setHashedSignCert(hashsign.getBytes());
     } else if (ExtPictureTypeOID.getId().equals(oid.getId())) {
      derObj = ASN1Object.fromByteArray(value);
      DERInteger picType = DERInteger.getInstance(derObj);
      eseal.setPictureType(picType.getValue().intValue());
     }
    } else {
     System.out
       .println("Unknown data type:" + derObj.getClass());
    }
   } catch (IOException e) {
    e.printStackTrace();
   }

  }

 }

 /**
  * @param derData
  * @return
  */
 private ArrayList parseAttr(byte[] derData) {
  GeneralNames gnames = GeneralNames
    .getInstance(derObjectDecode(derData));
  GeneralName[] nameArray = gnames.getNames();

  ArrayList list = new ArrayList();

  for (int i = 0; i < nameArray.length; i++) {
   if (GeneralName.otherName != nameArray[i].getTagNo()) {
    // throw new Exception("Illegal attr in eseal");
   }

   ASN1Sequence othername = DERSequence.getInstance(nameArray[i]
     .getName());
   DERObjectIdentifier oid = DERObjectIdentifier.getInstance(othername
     .getObjectAt(0));
   if (!ExtAttrNameOID.getId().equals(oid.getId())) {
    // throw new Exception("Illegal attr name oid in eseal");
   }

   DERUTF8String uname = DERUTF8String.getInstance(othername
     .getObjectAt(1));
   list.add(uname.getString());
  }

  return list;
 }

 /**
  * @param subjectName
  */
 public void parseEsealName(String subjectName) {
  String[] subject = subjectName.split(",");
  int size = subject.length;
  if(!"".equals(subjectName)){
   for (int i = 0; i < size; i++) {
    if(subject[i].indexOf("CN=")>=0){
     eseal.setEsealName(subject[i].replaceAll("CN=", ""));
     break;
    }
   }
  }
  
 }
 


 private X509Certificate[] parseDerCert(byte[] derCert) {
  try {
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   Collection col = cf.generateCertificates(new ByteArrayInputStream(
     derCert));
   int clen = col.size();
   X509Certificate[] x509s = new X509Certificate[clen];
   col.toArray(x509s);
   return x509s;
  } catch (Exception exp) {
   return null;
  }
 }

 private ASN1Encodable attrToASN1Encodable(ArrayList attr) {
  ASN1EncodableVector gnames = new ASN1EncodableVector();

  for (int i = 0; i < attr.size(); i++) {
   String s = (String) attr.get(i);
   ASN1EncodableVector v = new ASN1EncodableVector();
   v.add(ExtAttrNameOID);
   v.add(new DERUTF8String(s));
   DERSequence seq = new DERSequence(v);
   gnames.add(new GeneralName(GeneralName.otherName, seq));
  }

  return new DERSequence(gnames);
 }

 public static void main(String[] args) {
  String cert = "MIIEKDCCA5GgAwIBAgIIG+GocKPeBcAwDQYJKoZIhvcNAQEFBQAwVzESMBAGA1UEAwwJZXNlYWxjYWFhMQowCAYDVQQKDAFhMQowCAYDVQQHDAFhMQowCAYDVQQIDAFhMQswCQYDVQQGEwJaSDEQMA4GA1UECwwHRVNFQUxDQTAeFw0wOTA3MjEwMjUyMTNaFw0wOTA4MDcwMzMyNDJaMCUxDTALBgNVBAMMBGVzZWExFDASBgNVBAsMC2tvYWxpaWVzZWFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvINVs04ScdRNvxxg7IPxvgsXkGyjT/kbA6taA/GP8IwZt9ngZ2jtoPMiW3lGcAf7K+XY5v56BVWq6AlI7WUnbtjEzODf6jd2h2uxC5tgZWihuu+Gi8GJZjy+LQ4+fKm9dsJtCJS8rVo3F//QMYYFX6wAdukyKhB1ANKRMjkYMdwIDAQABo4ICLTCCAikwHQYDVR0OBBYEFOTpJtAKW/0kBULttjzacIeaRBXjMB8GA1UdIwQYMBaAFI9UfJNncAGunMAzlAH1vZvE2X+AMBIGCGCBHJ+zfII3AQH/BAMCAQEwgaIGCGCBHJ+zfII4AQH/BIGSMIGPMUQwQgYDVQQDDDswNDFAMGNhaWt1d3V6aGlodWF0d29hYUA0Njk3ODk0NTZAY2Fpa3V3dXpoaWh1YXR3b0AwMDAwMDAwMTERMA8GA1UECwwIT3BlcmF0b3IxETAPBgNVBAsMCDc4OTQ1NkAxMRQwEgYDVQQKDAtQQkMgVGVzdCBDQTELMAkGA1UEBhMCQ04wIQYIYIEcn7N8gjkBAf8EEgIQfeeMg7T2Libadx984iTXzDA0BghggRyfs3yCOgEB/wQlMCMxFDASBgNVBAoMC1BCQyBUZXN0IENBMQswCQYDVQQGEwJDTjAmBghggRyfs3yCOwEB/wQXAxUAxL9qLDNnOU+oYNh7Br7fbFwcgAowFQYIYIEcn7N8gi4BAf8EBgMEADEyMzBKBghggRyfs3yCLQEB/wQ7MDmgEgYHYIEcn7N8ZAwHbmFtZT1saaARBgdggRyfs3xkDAZpZD0xMDCgEAYHYIEcn7N8ZAwFc2V4PTEwSgYIYIEcn7N8gi8BAf8EOzA5oBIGB2CBHJ+zfGQMB25hbWU9bGmgEQYHYIEcn7N8ZAwGaWQ9MTAwoBAGB2CBHJ+zfGQMBXNleD0xMA0GCSqGSIb3DQEBBQUAA4GBAC8S6jAnYlNjL3tA1aqD00+7aHaiuZIn/QGXJ9IMLQc07i6xwAXoDdTTgVvGfeHWbBZ1msASKCzXp7yqPxW8rYcJgwc3OvE12v0NXcpRmenXrqlXryl8ZNe42V5aZ5TWyCbQBiLf35oNnMhYsa1RHyItxYNfgEBv6ODjPVRfKeqs";
  ESealUtil e = new ESealUtil();
  X509Certificate[] x509cert = e.parseDerCert(Base64.decode(cert
    .getBytes()));
  e.parseESealCert(x509cert[0]);
  // System.out.println("begin");
  // ESealUtil util = new ESealUtil();
  // EsealInfo info = new EsealInfo();
  // info.setEsealName("C=cn,ST=bj,L=beijing,O=o1,OU=ou1,CN=I am a user");
  // info.setPictureData(new byte[]{'1','2','3'});
  // System.out.println("key pair");
  // KeyPair pair = new KeyUtil().generateKeyPair(2048);
  // System.out.println("request");
  // util.createESealRequest(info, pair);

  // //String/byte[] to DERObject to String
  // String abc ="weeeeeeeeewww";
  // ASN1Object derObj = new DEROctetString(abc.getBytes());
  // System.out.println(derObj);
  //  
  // byte[] value;
  // try {
  // value =
  // ((ASN1OctetString)ASN1Object.fromByteArray(derObj.getEncoded())).getOctets();
  // System.out.println(new String(value));
  // } catch (IOException e) {
  //   
  // e.printStackTrace();
  // }

 }

}

 

 

 


package com.koalii.eseal.info;

import java.util.ArrayList;
import java.util.Date;

/**
 * 签章申请信息
 * EsealInfo.java
 *
 * @CopyRight KOAL Co. Lmt 2009
 * @author Administrator
 * @Since
 * @version
 * @Date: 2009-7-22
 */
public class EsealInfo
{
    //1 eseal basic info
    private int version = 1;   //must 0 for v1.0; 1 for v1.0.1
    private String esealName;    //must
    private Date esealNotBefore;  //must
    private Date esealNotAfter;   //must
   
    //2 sign cert info
    private byte[] derSignCert;    //must
    //3 picture info
    private int pictureType = 1;   //must
    private byte[] pictureData;    //must
   
    //4 eseal extended info
    private ArrayList userAttr = new ArrayList(); //optional
    private ArrayList esealAttr = new ArrayList();//optional
   
   
   
   
     /**
  * @return the derSignCert
  */
 public byte[] getDerSignCert() {
  return derSignCert;
 }

 

 /**
  * @param derSignCert the derSignCert to set
  */
 public void setDerSignCert(byte[] derSignCert) {
  this.derSignCert = derSignCert;
 }

 

  /**
  * @return the version
  */
 public int getVersion() {
  return version;
 }

 

 /**
  * @param version the version to set
  */
 public void setVersion(int version) {
  this.version = version;
 }

 

 /**
  * @return the esealName
  */
 public String getEsealName() {
  return esealName;
 }

 

 /**
  * @param esealName the esealName to set
  */
 public void setEsealName(String esealName) {
  this.esealName = esealName;
 }

 

 /**
  * @return the esealNotBefore
  */
 public Date getEsealNotBefore() {
  return esealNotBefore;
 }

 

 /**
  * @param esealNotBefore the esealNotBefore to set
  */
 public void setEsealNotBefore(Date esealNotBefore) {
  this.esealNotBefore = esealNotBefore;
 }

 

 /**
  * @return the esealNotAfter
  */
 public Date getEsealNotAfter() {
  return esealNotAfter;
 }

 

 /**
  * @param esealNotAfter the esealNotAfter to set
  */
 public void setEsealNotAfter(Date esealNotAfter) {
  this.esealNotAfter = esealNotAfter;
 }

 

 

 /**
  * @return the pictureType
  */
 public int getPictureType() {
  return pictureType;
 }

 

 /**
  * @param pictureType the pictureType to set
  */
 public void setPictureType(int pictureType) {
  this.pictureType = pictureType;
 }

 

 /**
  * @return the pictureData
  */
 public byte[] getPictureData() {
  return pictureData;
 }

 

 /**
  * @param pictureData the pictureData to set
  */
 public void setPictureData(byte[] pictureData) {
  this.pictureData = pictureData;
 }

 

 /**
  * @return the userAttr
  */
 public ArrayList getUserAttr() {
  return userAttr;
 }

 

 /**
  * @param userAttr the userAttr to set
  */
 public void setUserAttr(ArrayList userAttr) {
  this.userAttr = userAttr;
 }

 

 /**
  * @return the esealAttr
  */
 public ArrayList getEsealAttr() {
  return esealAttr;
 }

 

 /**
  * @param esealAttr the esealAttr to set
  */
 public void setEsealAttr(ArrayList esealAttr) {
  this.esealAttr = esealAttr;
 }

 

 protected String attrListToString(ArrayList attrList)
    {
        if (null == attrList || 0 == attrList.size())
            return "";
       
        StringBuffer sbuf = new StringBuffer();
       
        for (int i = 0; i < attrList.size(); i++)
        {
            String s = (String)attrList.get(i);
            sbuf.append(s);
            if (i != attrList.size() - 1)
                sbuf.append(",");
        }
        return sbuf.toString();
    }
}

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值