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

📄 x509ca.java

📁 一个免费的CA,基于EJB平台的,老师叫我们测试,现把之共享出来让大家参考
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
            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 ASN1InputStream(                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;        crl = crlgen.generate(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN),getCAToken().getProvider());        // Verify before sending back        crl.verify(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN));        return crl;            }            /** Implemtation of UpgradableDataHashMap function getLatestVersion */    public float getLatestVersion(){       return LATEST_VERSION;    }    /** Implemtation of UpgradableDataHashMap function upgrade.      */    public void upgrade(){    	if(Float.compare(LATEST_VERSION, getVersion()) != 0) {            // New version of the class, upgrade            log.info("Upgrading X509CA with version "+getVersion());            if (data.get(DEFAULTOCSPSERVICELOCATOR) == null) {                setDefaultCRLDistPoint("");                setDefaultOCSPServiceLocator("");            }            if (data.get(CRLISSUEINTERVAL) == null) {                setCRLIssueInterval(0);            }            if (data.get(CRLOVERLAPTIME) == null) {            	// Default value 10 minutes            	setCRLOverlapTime(10);            }            boolean useprintablestring = true;            if (data.get("alwaysuseutf8subjectdn") == null) {            	// Default value false            	setUseUTF8PolicyText(false);            } else {            	// Use the same value as we had before when we had alwaysuseutf8subjectdn                boolean useutf8 = ((Boolean)data.get("alwaysuseutf8subjectdn")).booleanValue();            	setUseUTF8PolicyText(useutf8);            	// If we had checked to use utf8 on an old CA, we do not want to use PrintableString after upgrading            	useprintablestring = !useutf8;            }            if (data.get(USEPRINTABLESTRINGSUBJECTDN) == null) {            	// Default value true (as before)            	setUsePrintableStringSubjectDN(useprintablestring);            }            if (data.get(DEFAULTCRLISSUER) == null) {            	setDefaultCRLIssuer(null);            }                                    data.put(VERSION, new Float(LATEST_VERSION));        }      }    /**     * Method to upgrade new (or existing externacaservices)     * This method needs to be called outside the regular upgrade     * since the CA isn't instansiated in the regular upgrade.     *     */    public boolean upgradeExtendedCAServices() {    	boolean retval = false;    	Collection extendedServiceTypes = getExternalCAServiceTypes();    	if(getCAInfo().getStatus() != SecConst.CA_EXTERNAL){    		// Create XKMS service if it does not exist    		if (!extendedServiceTypes.contains(new Integer(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE))){    			String keytype = CATokenConstants.KEYALGORITHM_RSA;    			String keyspec = "2048";    			XKMSCAServiceInfo xKMSCAInfo =  new XKMSCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE,    					"CN=XKMSCertificate, " + getSubjectDN(),    					"",    					keyspec,    					keytype);    			XKMSCAService xkmsservice = new XKMSCAService(xKMSCAInfo);    			try {    				xkmsservice.init(this);    				retval = true;    			} catch (Exception e) {    				CAInfo info = this.getCAInfo();    				String caname = null;    				if (info != null) {    					caname = info.getName();    				}    				log.error(intres.getLocalizedMessage("signsession.errorupgradingxkmsservice",caname), e);    			}    			setExtendedCAService(xkmsservice);    			extendedServiceTypes.add(new Integer(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE));    			data.put(EXTENDEDCASERVICES, extendedServiceTypes);    		}		    		// Create CMS service if it does not exist    		if (!extendedServiceTypes.contains(new Integer(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE))){    			String keytype = CATokenConstants.KEYALGORITHM_RSA;    			String keyspec = "2048";    			CmsCAServiceInfo cmsCAInfo =  new CmsCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE,    					"CN=CMSCertificate, " + getSubjectDN(),    					"",    					keyspec,    					keytype);    			CmsCAService cmsservice = new CmsCAService(cmsCAInfo);    			try {    				cmsservice.init(this);    				retval = true;    			} catch (Exception e) {    				CAInfo info = this.getCAInfo();    				String caname = null;    				if (info != null) {    					caname = info.getName();    				}    				log.error(intres.getLocalizedMessage("signsession.errorupgradingcmsservice",caname), e);    			}    			setExtendedCAService(cmsservice);    			extendedServiceTypes.add(new Integer(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE));    			data.put(EXTENDEDCASERVICES, extendedServiceTypes);    		}		    	}    	return retval;    }		/** 	 * Method used to perform an extended service.	 */    public ExtendedCAServiceResponse extendedService(ExtendedCAServiceRequest request)       throws ExtendedCAServiceRequestException, IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException{          log.debug(">extendedService()");          if(request instanceof OCSPCAServiceRequest) {        	  OCSPCAServiceRequest ocspServiceReq = (OCSPCAServiceRequest)request;              boolean useCACert = ocspServiceReq.useCACert();              try {                  if (useCACert) {                	  ocspServiceReq.setPrivKey(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN));                	  ocspServiceReq.setPrivKeyProvider(getCAToken().getProvider());                	  X509Certificate[] signerChain = (X509Certificate[])getCertificateChain().toArray(new X509Certificate[0]);                	  List chain = Arrays.asList(signerChain);                	  ocspServiceReq.setCertificateChain(chain);                      // Super class handles signing with the OCSP signing certificate                      log.debug("<extendedService(super with ca cert)");                      return super.extendedService(ocspServiceReq);                                        } else {                      // Super class handles signing with the OCSP signing certificate                      log.debug("<extendedService(super no ca cert)");                      return super.extendedService(request);                                        }              } catch (IllegalKeyStoreException ike) {            	  throw new ExtendedCAServiceRequestException(ike);              } catch (CATokenOfflineException ctoe) {            	  throw new ExtendedCAServiceRequestException(ctoe);              } catch (IllegalArgumentException e) {            	  log.error("IllegalArgumentException: ", e);            	  throw new IllegalExtendedCAServiceRequestException(e);              }          } else {              log.debug("<extendedService(super)");              return super.extendedService(request);          }    }        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,"BC");		} catch (Exception e) {            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;    	byte[] recdata = recipient.getContent(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT),getCAToken().getProvider());    	ois = new ObjectInputStream(new ByteArrayInputStream(recdata));    	    	    	    	return (KeyPair) ois.readObject();      }            /**     * Obtains the Policy Notice     *      * @param policyOID,     *          OID of the policy     * @param cps,     *          url to cps document     * @param unotice,     *          user notice text     * @param displayencoding,     *          the encoding used for UserNotice text, DisplayText.CONTENT_TYPE_BMPSTRING, CONTENT_TYPE_UTF8STRING, CONTENT_TYPE_IA5STRING or CONTENT_TYPE_VISIBLESTRING      *               * @return     */    private PolicyInformation getPolicyInformation(String policyOID, String cps, String unotice, int displayencoding) {            	ASN1EncodableVector qualifiers = new ASN1EncodableVector();        if ((unotice != null) && !StringUtils.isEmpty(unotice.trim())) {            // Normally we would just use 'DisplayText(unotice)' here. IE has problems with UTF8 though, so lets stick with BMSSTRING to satisfy Bills sick needs.            UserNotice un = new UserNotice(null, new DisplayText(displayencoding, unotice));            PolicyQualifierInfo pqiUNOTICE = new PolicyQualifierInfo(PolicyQualifierId.id_qt_unotice, un);            qualifiers.add(pqiUNOTICE);        }        if ((cps != null) && !StringUtils.isEmpty(cps.trim())) {            PolicyQualifierInfo pqiCPS = new PolicyQualifierInfo(cps);            qualifiers.add(pqiCPS);        }        PolicyInformation policyInformation = null;        if ( StringUtils.isNotEmpty(policyOID) && (qualifiers.size() > 0) ) {            policyInformation = new PolicyInformation(new DERObjectIdentifier(policyOID), new DERSequence(qualifiers));                    } else {            policyInformation = new PolicyInformation(new DERObjectIdentifier(policyOID));        }                return policyInformation;    }   }

⌨️ 快捷键说明

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