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

📄 x509ca.java

📁 一个免费的CA,基于EJB平台的,老师叫我们测试,现把之共享出来让大家参考
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
      public boolean  getUsePrintableStringSubjectDN(){    	  return ((Boolean)data.get(USEPRINTABLESTRINGSUBJECTDN)).booleanValue();      }      public void setUsePrintableStringSubjectDN(boolean useprintablestring) {    	  data.put(USEPRINTABLESTRINGSUBJECTDN, Boolean.valueOf(useprintablestring));      }          public void updateCA(CAInfo cainfo) throws Exception{    	  super.updateCA(cainfo);     	  X509CAInfo info = (X509CAInfo) cainfo;    	      	  setUseAuthorityKeyIdentifier(info.getUseAuthorityKeyIdentifier());    	  setAuthorityKeyIdentifierCritical(info.getAuthorityKeyIdentifierCritical());     	  setUseCRLNumber(info.getUseCRLNumber());    	  setCRLNumberCritical(info.getCRLNumberCritical());    	  setDefaultCRLDistPoint(info.getDefaultCRLDistPoint());    	  setDefaultCRLIssuer(info.getDefaultCRLIssuer());    	  setDefaultOCSPServiceLocator(info.getDefaultOCSPServiceLocator());    	  setUseUTF8PolicyText(info.getUseUTF8PolicyText());          setUsePrintableStringSubjectDN(info.getUsePrintableStringSubjectDN());      }        public byte[] createPKCS7(Certificate cert, boolean includeChain) throws SignRequestSignatureException {        // First verify that we signed this certificate        try {            if (cert != null)                cert.verify(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN));        } catch (Exception e) {            throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?");        }        Collection chain = getCertificateChain();        ArrayList certList = new ArrayList();        if (cert != null) {            certList.add(cert);        }         if (includeChain) {            certList.addAll(chain);        }        try {            CMSProcessable msg = new CMSProcessableByteArray("EJBCA".getBytes());            CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();            if (getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN) == null) {            	String msg1 = "createPKCS7: Private key does not exist!";            	log.debug(msg1);            	throw new SignRequestSignatureException(msg1);            }            gen.addSigner(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), (X509Certificate)getCACertificate(), CMSSignedGenerator.DIGEST_SHA1);            gen.addCertificatesAndCRLs(certs);            CMSSignedData s = null;            CAToken catoken = getCAToken();            if (catoken != null && !(catoken instanceof NullCAToken)) {            	log.debug("createPKCS7: Provider="+catoken.getProvider()+" using algorithm "+getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN).getAlgorithm());            	s = gen.generate(msg, true, catoken.getProvider());            } else {            	String msg1 = "CA Token does not exist!";            	log.debug(msg);            	throw new SignRequestSignatureException(msg1);            }            return s.getEncoded();        } catch (CATokenOfflineException e) {        	throw new javax.ejb.EJBException(e);        	        } catch (Exception e) {            throw new javax.ejb.EJBException(e);        }       }                public Certificate generateCertificate(UserDataVO subject,                                            PublicKey publicKey,                                            int keyusage,                                            Date notBefore,                                           Date notAfter,                                           CertificateProfile certProfile) throws Exception{                                                   	    	        final String sigAlg = getCAToken().getCATokenInfo().getSignatureAlgorithm();        Date firstDate = new Date();        // Set back startdate ten minutes to avoid some problems with wrongly set clocks.        firstDate.setTime(firstDate.getTime() - 10 * 60 * 1000);        Date lastDate = new Date();        if ( (notBefore != null) && (certProfile.getAllowValidityOverride()) ) {        	// If we allow the client (or ra) to specify the startdate        	firstDate = notBefore;        	if (log.isDebugEnabled()) {            	log.debug("Using notBefore validity from request: "+firstDate);        		        	}        }        if ( (notAfter == null) || (!certProfile.getAllowValidityOverride()) ) {            // validity in days = validity*24*60*60*1000 milliseconds            long val = certProfile.getValidity();                	if (log.isDebugEnabled()) {        		log.debug("Using validity from profile: "+val);        	}            lastDate.setTime(lastDate.getTime() + ( val * 24 * 60 * 60 * 1000));        	        } else {        	// only if not null and we allow validity override        	lastDate = notAfter;        	if (log.isDebugEnabled()) {            	log.debug("Using notAfter validity from request: "+lastDate);        		        	}        }        // Do not allow last date to be before first date        if (!lastDate.after(firstDate)) {        	// Setting it to the same is silly as well but what the heck        	lastDate = firstDate;        }        X509Certificate cacert = (X509Certificate)getCACertificate();        String dn = subject.getDN();                // Check if this is a root CA we are creating        boolean isRootCA = false;        if (certProfile.getType() == CertificateProfile.TYPE_ROOTCA) {        	isRootCA = true;        }        // If our desired after date is after the CA expires, we will not allow this        // The CA will only issue certificates with maximum the same validity time as it-self        // We will not limit validity of a self signed cert (RootCA), because it is a renewal.        if ( !isRootCA ) {            if (lastDate.after(cacert.getNotAfter())) {            	String msg = intres.getLocalizedMessage("signsession.limitingvalidity", lastDate.toString(), cacert.getNotAfter());            	log.info(msg);                lastDate = cacert.getNotAfter();            }                    }        X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();        // Serialnumber is random bits, where random generator is initialized by the        // serno generator.        BigInteger serno = SernoGenerator.instance().getSerno();        certgen.setSerialNumber(serno);        certgen.setNotBefore(firstDate);        certgen.setNotAfter(lastDate);        certgen.setSignatureAlgorithm(sigAlg);        // Make DNs        if(certProfile.getUseSubjectDNSubSet()){          dn= certProfile.createSubjectDNSubSet(dn);	        }                if(certProfile.getUseCNPostfix()){          dn = CertTools.insertCNPostfix(dn,certProfile.getCNPostfix());	        }                String altName = subject.getSubjectAltName();         if(certProfile.getUseSubjectAltNameSubSet()){        	altName = certProfile.createSubjectAltNameSubSet(altName);        }                X509NameEntryConverter converter = null;        if (getUsePrintableStringSubjectDN()) {        	converter = new PrintableStringEntryConverter();        } else {        	converter = new X509DefaultEntryConverter();        }        certgen.setSubjectDN(CertTools.stringToBcX509Name(dn, converter));        // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN        // which many applications do not like.        if (isRootCA) {        	// This will be an initial root CA, since no CA-certificate exists        	// Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer,        	// it might have changed over the years.        	if (log.isDebugEnabled()) {        		log.debug("Using subject DN also as issuer DN, because it is a root CA");        	}            X509Name caname = CertTools.stringToBcX509Name(getSubjectDN(), converter);            certgen.setIssuerDN(caname);        } else {        	if (log.isDebugEnabled()) {        		log.debug("Using issuer DN directly from the CA certificate");        	}            certgen.setIssuerDN(cacert.getSubjectX500Principal());        	        }        certgen.setPublicKey(publicKey);        // Basic constranits, all subcerts are NOT CAs        if (certProfile.getUseBasicConstraints() == true) {        	BasicConstraints bc = new BasicConstraints(false);            if ((certProfile.getType() == CertificateProfile.TYPE_SUBCA)                || (certProfile.getType() == CertificateProfile.TYPE_ROOTCA)){            	            	if(certProfile.getUsePathLengthConstraint()){            		bc = new BasicConstraints(certProfile.getPathLengthConstraint());            	}else{            		bc =  new BasicConstraints(true);            	}            	            }                                        certgen.addExtension(                X509Extensions.BasicConstraints.getId(),                certProfile.getBasicConstraintsCritical(),                bc);        }        // Key usage        int newKeyUsage = -1;        if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) {            newKeyUsage = keyusage;        } else {            newKeyUsage = CertTools.sunKeyUsageToBC(certProfile.getKeyUsage());        }        if ( (certProfile.getUseKeyUsage() == true) && (newKeyUsage >=0) ){            X509KeyUsage ku = new X509KeyUsage(newKeyUsage);            certgen.addExtension(                X509Extensions.KeyUsage.getId(),                certProfile.getKeyUsageCritical(),                ku);        }        // Extended Key usage        if (certProfile.getUseExtendedKeyUsage() == true) {            // Get extended key usage from certificate profile            Collection c = certProfile.getExtendedKeyUsageAsOIDStrings();            Vector usage = new Vector();            Iterator iter = c.iterator();            while (iter.hasNext()) {                usage.add(new DERObjectIdentifier((String)iter.next()));            }            // Don't add empty key usage extension            if (!usage.isEmpty()) {                ExtendedKeyUsage eku = new ExtendedKeyUsage(usage);                // Extended Key Usage may be either critical or non-critical                certgen.addExtension(                    X509Extensions.ExtendedKeyUsage.getId(),                    certProfile.getExtendedKeyUsageCritical(),                    eku);            	            }        }        // Subject key identifier        if (certProfile.getUseSubjectKeyIdentifier() == true) {            SubjectPublicKeyInfo spki =                new SubjectPublicKeyInfo(                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())).readObject());            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);            certgen.addExtension(                X509Extensions.SubjectKeyIdentifier.getId(),                certProfile.getSubjectKeyIdentifierCritical(), ski);        }        // Authority key identifier        if (certProfile.getUseAuthorityKeyIdentifier() == true) {            SubjectPublicKeyInfo apki = null;            try{              apki =                new SubjectPublicKeyInfo(                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN).getEncoded())).readObject());             }catch(CATokenOfflineException e){                 log.debug("X509CA: CA Token Offline Exception: ", e);                                 throw e;             }            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) ) {            GeneralNames san = CertTools.getGeneralNamesFromAltName(altName);                        if (san != null) {                certgen.addExtension(X509Extensions.SubjectAlternativeName.getId(), certProfile.getSubjectAlternativeNameCritical(), san);            }        }        

⌨️ 快捷键说明

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