⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 x509ca.java

📁 一套JAVA的CA证书签发系统.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                certProfile.getSubjectKeyIdentifierCritical(), ski);        }        // Authority key identifier        if (certProfile.getUseAuthorityKeyIdentifier() == true) {            SubjectPublicKeyInfo apki = null;            try{              apki =                new SubjectPublicKeyInfo(                    (ASN1Sequence) new DERInputStream(new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN).getEncoded())).readObject());             }catch(CATokenOfflineException e){                 log.debug("X509CA : Setting STATUS OFFLINE " + this.getName());                     this.setStatus(SecConst.CA_OFFLINE);                 log.debug("X509CA : New STATUS  " + this.getStatus());                 throw new CATokenOfflineException(e.getMessage());             }            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);            certgen.addExtension(                X509Extensions.AuthorityKeyIdentifier.getId(),                certProfile.getAuthorityKeyIdentifierCritical(), aki);        }        // Subject Alternative name        if ( (certProfile.getUseSubjectAlternativeName() == true) && (altName != null) && (altName.length() > 0) ) {            String email = CertTools.getEmailFromDN(altName);            DEREncodableVector vec = new DEREncodableVector();            if (email != null) {                GeneralName gn = new GeneralName(new DERIA5String(email), 1);                vec.add(gn);            }            String dns = CertTools.getPartFromDN(altName, CertTools.DNS);            if (dns != null) {                GeneralName gn = new GeneralName(new DERIA5String(dns), 2);                vec.add(gn);            }            String uri = CertTools.getPartFromDN(altName, CertTools.URI);            if (uri == null){                            uri  = CertTools.getPartFromDN(altName, CertTools.URI1);            }            if (uri != null) {                GeneralName gn = new GeneralName(new DERIA5String(uri), 6);                vec.add(gn);            }            String ipstr = CertTools.getPartFromDN(altName, CertTools.IPADDR);            if (ipstr != null) {                byte[] ipoctets = StringTools.ipStringToOctets(ipstr);                GeneralName gn = new GeneralName(new DEROctetString(ipoctets), 7);                vec.add(gn);            }            String upn =  CertTools.getPartFromDN(altName, CertTools.UPN);            if (upn != null) {                ASN1EncodableVector v = new ASN1EncodableVector();                v.add(new DERObjectIdentifier(CertTools.UPN_OBJECTID));                v.add(new DERTaggedObject(true, 0, new DERUTF8String(upn)));                //GeneralName gn = new GeneralName(new DERSequence(v), 0);                DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));                vec.add(gn);            }                        String guid =  CertTools.getPartFromDN(altName, CertTools.GUID);            if (guid != null) {                ASN1EncodableVector v = new ASN1EncodableVector();                byte[] guidbytes = Hex.decode(guid);                if (guidbytes != null) {                    v.add(new DERObjectIdentifier(CertTools.GUID_OBJECTID));                    v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes)));                    DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));                    vec.add(gn);                                    } else {                    log.error("Cannot decode hexadecimal guid: "+guid);                }            }                        if (vec.size() > 0) {                GeneralNames san = new GeneralNames(new DERSequence(vec));                certgen.addExtension(X509Extensions.SubjectAlternativeName.getId(), certProfile.getSubjectAlternativeNameCritical(), san);            }        }                // Certificate Policies         if (certProfile.getUseCertificatePolicies() == true) {                 PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(certProfile.getCertificatePolicyId()));                 DERSequence seq = new DERSequence(pi);                 certgen.addExtension(X509Extensions.CertificatePolicies.getId(),                         certProfile.getCertificatePoliciesCritical(), seq);         }         // CRL Distribution point URI         if (certProfile.getUseCRLDistributionPoint() == true) {             // Multiple CDPs are spearated with the ';' sign            StringTokenizer tokenizer = new StringTokenizer(certProfile.getCRLDistributionPointURI(), ";", false);            ArrayList distpoints = new ArrayList();            while (tokenizer.hasMoreTokens()) {                // 6 is URI                String uri = tokenizer.nextToken();                GeneralName gn = new GeneralName(new DERIA5String(uri), 6);                log.debug("Added CRL distpoint: "+uri);                ASN1EncodableVector vec = new ASN1EncodableVector();                vec.add(gn);                GeneralNames gns = new GeneralNames(new DERSequence(vec));                DistributionPointName dpn = new DistributionPointName(0, gns);                distpoints.add(new DistributionPoint(dpn, null, null));            }            if (distpoints.size() > 0) {                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[])distpoints.toArray(new DistributionPoint[0]));                certgen.addExtension(X509Extensions.CRLDistributionPoints.getId(),                    certProfile.getCRLDistributionPointCritical(), ext);            }         }         // Authority Information Access (OCSP url)         if (certProfile.getUseOCSPServiceLocator() == true) {             String ocspUrl = certProfile.getOCSPServiceLocatorURI();             // OCSP access location is a URL (GeneralName no 6)             GeneralName ocspLocation = new GeneralName(new DERIA5String(ocspUrl), 6);             certgen.addExtension(X509Extensions.AuthorityInfoAccess.getId(),                 false, new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, ocspLocation));         }		                   X509Certificate cert;         try{           cert = certgen.generateX509Certificate(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN),                                             getCAToken().getProvider());         }catch(CATokenOfflineException e){             log.debug("X509CA : Setting STATUS OFFLINE");             this.setStatus(SecConst.CA_OFFLINE);             throw e;          }                // Verify before returning        cert.verify(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN));        log.debug(">X509CA: generate certificate, CA "+ this.getCAId() + " for DN=" + subject.getDN());                  return (X509Certificate) cert;                                                                                            }        public CRL generateCRL(Vector certs, int crlnumber) throws Exception {        final String sigAlg= getCAToken().getCATokenInfo().getSignatureAlgorithm();        Date thisUpdate = new Date();        Date nextUpdate = new Date();        // crlperiod is hours = crlperiod*60*60*1000 milliseconds        nextUpdate.setTime(nextUpdate.getTime() + (getCRLPeriod() * 60 * 60 * 1000));        X509V2CRLGenerator crlgen = new X509V2CRLGenerator();        crlgen.setThisUpdate(thisUpdate);        crlgen.setNextUpdate(nextUpdate);        crlgen.setSignatureAlgorithm(sigAlg);        // Make DNs        X509Name caname = new X509Name(getSubjectDN());        crlgen.setIssuerDN(caname);        if (certs != null) {                        Iterator it = certs.iterator();            while( it.hasNext() ) {                RevokedCertInfo certinfo = (RevokedCertInfo)it.next();                crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(), certinfo.getReason());            }        }        // Authority key identifier        if (getUseAuthorityKeyIdentifier() == true) {            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new DERInputStream(                new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN).getEncoded())).readObject());            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);            crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), getAuthorityKeyIdentifierCritical(), aki);        }        // CRLNumber extension        if (getUseCRLNumber() == true) {            CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));            crlgen.addExtension(X509Extensions.CRLNumber.getId(),  this.getCRLNumberCritical(), crlnum);        }                X509CRL crl;        try{        	crl = crlgen.generateX509CRL(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN),getCAToken().getProvider());        }catch(CATokenOfflineException e){        	this.setStatus(SecConst.CA_OFFLINE);        	throw e;         }                                // Verify before sending back        crl.verify(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN));        return (X509CRL)crl;            }            /** Implemtation of UpgradableDataHashMap function getLatestVersion */    public float getLatestVersion(){       return LATEST_VERSION;    }    /** Implemtation of UpgradableDataHashMap function upgrade. */    public void upgrade(){      if(LATEST_VERSION != getVersion()){        // New version of the class, upgrade        data.put(VERSION, new Float(LATEST_VERSION));      }      }    /**      * Method used to perform an extended service.     */    public ExtendedCAServiceResponse extendedService(ExtendedCAServiceRequest request)       throws ExtendedCAServiceRequestException, IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException{          log.debug(">extendedService()");          ExtendedCAServiceResponse returnval = null;           if(request instanceof OCSPCAServiceRequest) {              BasicOCSPRespGenerator ocsprespgen = ((OCSPCAServiceRequest)request).getOCSPrespGenerator();              String sigAlg = ((OCSPCAServiceRequest)request).getSigAlg();              boolean useCACert = ((OCSPCAServiceRequest)request).useCACert();              boolean includeChain = ((OCSPCAServiceRequest)request).includeChain();              PrivateKey pk = null;              X509Certificate[] chain = null;              try {                  if (useCACert) {                      pk = getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);                      if (includeChain) {                          chain = (X509Certificate[])getCertificateChain().toArray(new X509Certificate[0]);                      }                   } else {                      // Super class handles signing with the OCSP signing certificate                      log.debug("<extendedService(super)");                      return super.extendedService(request);                                        }                  BasicOCSPResp ocspresp = ocsprespgen.generate(sigAlg, pk, chain, new Date(), "BC" );                  returnval = new OCSPCAServiceResponse(ocspresp, chain == null ? null : Arrays.asList(chain));                            } catch (IllegalKeyStoreException ike) {                  throw new ExtendedCAServiceRequestException(ike);              } catch (NoSuchProviderException nspe) {                  throw new ExtendedCAServiceRequestException(nspe);              } catch (OCSPException ocspe) {                  throw new ExtendedCAServiceRequestException(ocspe);                                } catch (CATokenOfflineException ctoe) {              	this.setStatus(SecConst.CA_OFFLINE);              	throw new ExtendedCAServiceRequestException(ctoe);			}          } else {              log.debug("<extendedService(super)");              return super.extendedService(request);          }          log.debug("<extendedService()");          return returnval;    }        public byte[] encryptKeys(KeyPair keypair) throws IOException, CATokenOfflineException{        	ByteArrayOutputStream baos = new ByteArrayOutputStream();    	ObjectOutputStream os = new ObjectOutputStream(baos);    	os.writeObject(keypair);    	        	    	CertTools.installBCProvider();    		        CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();    	    	    	    	                 	CMSEnvelopedData ed;		try {			edGen.addKeyTransRecipient( this.getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT), this.keyId);			ed = edGen.generate(					new CMSProcessableByteArray(baos.toByteArray()), CMSEnvelopedDataGenerator.AES256_CBC,					              getCAToken().getProvider());		} catch (CATokenOfflineException ctoe) {			this.setStatus(SecConst.CA_OFFLINE);          	throw ctoe;	 			} catch (Exception e) {            setStatus(SecConst.CA_OFFLINE);            log.error("-encryptKeys: ", e);            throw new IOException(e.getMessage());        		}								return ed.getEncoded();     }        public KeyPair decryptKeys(byte[] data) throws Exception{    	CMSEnvelopedData ed = new CMSEnvelopedData(data);   	    	    	     		RecipientInformationStore  recipients = ed.getRecipientInfos();           	    	Iterator    it =  recipients.getRecipients().iterator();    	RecipientInformation   recipient = (RecipientInformation) it.next();    	ObjectInputStream ois = null;    	try{    	  byte[] recdata = recipient.getContent(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT),getCAToken().getProvider());    	  ois = new ObjectInputStream(new ByteArrayInputStream(recdata));    	}catch(CATokenOfflineException e){    		setStatus(SecConst.CA_OFFLINE);    		throw e;    	}    	    	    	    	return (KeyPair) ois.readObject();      }           // private help methods    private int sunKeyUsageToBC(boolean[] sku) {        int bcku = 0;        if (sku[0] == true)            bcku = bcku | X509KeyUsage.digitalSignature;        if (sku[1] == true)            bcku = bcku | X509KeyUsage.nonRepudiation;        if (sku[2] == true)            bcku = bcku | X509KeyUsage.keyEncipherment;        if (sku[3] == true)            bcku = bcku | X509KeyUsage.dataEncipherment;        if (sku[4] == true)            bcku = bcku | X509KeyUsage.keyAgreement;        if (sku[5] == true)            bcku = bcku | X509KeyUsage.keyCertSign;        if (sku[6] == true)            bcku = bcku | X509KeyUsage.cRLSign;        if (sku[7] == true)            bcku = bcku | X509KeyUsage.encipherOnly;        if (sku[8] == true)            bcku = bcku | X509KeyUsage.decipherOnly;        return bcku;    }        private X509Name getSubjectDNAsX509Name(){      if(subjectx509name == null){        subjectx509name = CertTools.stringToBcX509Name(getSubjectDN());        }              return subjectx509name;      }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -