List of usage examples for org.bouncycastle.asn1.x509 X509Extension isCritical
public boolean isCritical()
From source file:chapter6.PKCS10CertCreateExample.java
public static X509Certificate[] buildChain() throws Exception { // Create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // Create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // Validate the certification request if (request.verify("BC") == false) { System.out.println("Request failed to verify!!"); System.exit(1);// w w w . j av a2s . c om } // Create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded())); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // Extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i < attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // Process extension request 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); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateComplianceCA_IT.java
License:Open Source License
/** * check if qcStatements are present as per ETSI * @param _TbsC //from ww w . j av a 2 s . c o m * @return */ private boolean hasQcStatements(TBSCertificateStructure _TbsC) { //first check for CNIPA requirement //then check for ETSI 102 280 requirements //then check for ETSI 101 862 //qcstatements are defined in ETSI 101 862 X509Extensions xExt = _TbsC.getExtensions(); X509Extension qcStats = xExt.getExtension(X509Extensions.QCStatements); if (qcStats == null) { //no qcStatement setCertificateStateHelper(CertificateState.MISSING_EXTENSION); m_aLogger.log("missing qcStatements"); return false; } int numberOfChecksOk = 4; //if this drops to zero, //it's not marked critical if (!qcStats.isCritical()) numberOfChecksOk--; ASN1Sequence dns = (ASN1Sequence) X509Extension.convertValueToObject(qcStats); for (int i = 0; i < dns.size(); i++) { QCStatement qcs = QCStatement.getInstance(dns.getObjectAt(i)); if (QCStatement.id_etsi_qcs_QcCompliance.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_QcSSCD.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_RetentionPeriod.equals(qcs.getStatementId())) numberOfChecksOk--; } if (numberOfChecksOk != 0) { m_xQc.setCertificateElementErrorState(X509Extensions.QCStatements.getId(), CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.ERROR_IN_EXTENSION); return false; } return true; }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateCompliance_IT.java
License:Open Source License
/** * check if qcStatements are present as per ETSI * @param _TbsC /*www. j a va2 s . c o m*/ * @return */ private boolean hasQcStatements(TBSCertificateStructure _TbsC) { //first check for CNIPA requirement //then check for ETSI 102 280 requirements //then check for ETSI 101 862 //qcstatements are defined in ETSI 101 862 X509Extensions xExt = _TbsC.getExtensions(); X509Extension qcStats = xExt.getExtension(X509Extensions.QCStatements); if (qcStats == null) { //no qcStatement setCertificateStateHelper(CertificateState.MISSING_EXTENSION); m_aLogger.log("missing qcStatements"); String s = m_xQc.getCertificateDisplayObj() .getCertificateElementCommentString(CertificateElementID.NOT_CRITICAL_EXTENSION); s = s + "\r"; m_xQc.getCertificateDisplayObj().setCertificateElementCommentString( CertificateElementID.NOT_CRITICAL_EXTENSION, s + "qcStatement missing"); return false; } int numberOfChecksOk = 4; //if this drops to zero, //it's not marked critical if (!qcStats.isCritical()) numberOfChecksOk--; ASN1Sequence dns = (ASN1Sequence) X509Extension.convertValueToObject(qcStats); for (int i = 0; i < dns.size(); i++) { QCStatement qcs = QCStatement.getInstance(dns.getObjectAt(i)); if (QCStatement.id_etsi_qcs_QcCompliance.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_QcSSCD.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_RetentionPeriod.equals(qcs.getStatementId())) numberOfChecksOk--; } if (numberOfChecksOk != 0) { m_xQc.setCertificateElementErrorState(X509Extensions.QCStatements.getId(), CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.ERROR_IN_EXTENSION); m_xQc.getCertificateDisplayObj().setCertificateExtensionCommentString( X509Extensions.QCStatements.getId(), "some statement is wrong."); return false; } return true; }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.X509CertDisplayBase_IT.java
License:Open Source License
@Override public void prepareDisplayStrings(XFrame _xFrame, XComponent _xComp) throws IllegalArgumentException, Exception { m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, _xComp); if (m_xQc == null) throw (new IllegalArgumentException( "com.yacme.ext.oxsit.security.cert.XOX_X509CertificateDisplay#prepareDisplayStrings wrong argument")); ///*w ww. j ava 2 s.co m*/ m_aX509 = null; //remove old certificate //remove old data from HashMaps m_aExtensions.clear(); m_aExtensionLocalizedNames.clear(); m_aExtensionDisplayValues.clear(); m_aCriticalExtensions.clear(); m_aNotCriticalExtensions.clear(); ByteArrayInputStream as = new ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded()); ASN1InputStream aderin = new ASN1InputStream(as); DERObject ado; try { ado = aderin.readObject(); m_aX509 = new X509CertificateStructure((ASN1Sequence) ado); //initializes the certificate display information initSubjectName(); m_sVersion = String.format("V%d", m_aX509.getVersion()); m_sSerialNumber = new String("" + m_aX509.getSerialNumber().getValue()); initIssuerName(); m_sNotValidBefore = initCertDate(m_aX509.getStartDate().getDate()); m_sNotValidAfter = initCertDate(m_aX509.getEndDate().getDate()); m_sSubjectPublicKeyAlgorithm = initPublicKeyAlgorithm(); m_sSubjectPublicKeyValue = initPublicKeyData(); m_sSignatureAlgorithm = initSignatureAlgorithm(); initThumbPrints(); //now initializes the Extension listing X509Extensions aX509Exts = m_aX509.getTBSCertificate().getExtensions(); //fill the internal extension HashMaps //at the same time we'll get the extension localized name from resources and //fill the display data MessageConfigurationAccess m_aRegAcc = null; m_aRegAcc = new MessageConfigurationAccess(m_xContext, m_xMCF); //FIXME: may be we need to adapt this to the context: the following is valid ONLY if this //object is instantiated from within a dialog, is not true if instantiated from a not UI method (e.g. from basic for example). IDynamicLogger aDlgH = null; CertificateExtensionDisplayHelper aHelper = new CertificateExtensionDisplayHelper(m_xContext, m_lTheLocale, m_sTimeLocaleString, m_sLocaleDateOfBirth, m_bDisplayOID, m_aLogger); for (Enumeration<DERObjectIdentifier> enume = aX509Exts.oids(); enume.hasMoreElements();) { DERObjectIdentifier aDERId = enume.nextElement(); String aTheOID = aDERId.getId(); X509Extension aext = aX509Exts.getExtension(aDERId); m_aExtensions.put(aTheOID, aext); //now grab the localized description try { m_aExtensionLocalizedNames.put(aTheOID, m_aRegAcc.getStringFromRegistry(aTheOID) + ((m_bDisplayOID) ? (" (OID: " + aTheOID.toString() + ")") : "")); } catch (com.sun.star.uno.Exception e) { m_aLogger.severe("setDEREncoded", e); m_aExtensionLocalizedNames.put(aTheOID, aTheOID); } //and decode this extension m_aExtensionDisplayValues.put(aTheOID, aHelper.examineExtension(aext, aDERId, this)); if (aext.isCritical()) m_aCriticalExtensions.put(aTheOID, aext); else m_aNotCriticalExtensions.put(aTheOID, aext); } m_aRegAcc.dispose(); } catch (IOException e) { m_aLogger.severe("setDEREncoded", e); } }
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
License:Apache License
protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer, X509Certificate checkedProxy) throws ProxyPathValidatorException, IOException { logger.debug("enter: checkProxyConstraints"); X509Extensions extensions;/* ww w. j a v a2 s . c om*/ DERObjectIdentifier oid; X509Extension ext; X509Extension proxyKeyUsage = null; extensions = proxy.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { oid = (DERObjectIdentifier) e.nextElement(); ext = extensions.getExtension(oid); if (oid.equals(X509Extensions.SubjectAlternativeName) || oid.equals(X509Extensions.IssuerAlternativeName)) { // No Alt name extensions - 3.2 & 3.5 throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "Proxy certificate cannot contain subject or issuer alternative name extension"); } else if (oid.equals(X509Extensions.BasicConstraints)) { // Basic Constraint must not be true - 3.8 BasicConstraints basicExt = BouncyCastleUtil.getBasicConstraints(ext); if (basicExt.isCA()) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "Proxy certificate cannot have BasicConstraint CA=true"); } } else if (oid.equals(X509Extensions.KeyUsage)) { proxyKeyUsage = ext; boolean[] keyUsage = BouncyCastleUtil.getKeyUsage(ext); // these must not be asserted if (keyUsage[1] || keyUsage[5]) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "The keyCertSign and nonRepudiation bits must not be asserted in Proxy Certificate"); } boolean[] issuerKeyUsage = getKeyUsage(issuer); if (issuerKeyUsage != null) { for (int i = 0; i < 9; i++) { if (i == 1 || i == 5) { continue; } if (!issuerKeyUsage[i] && keyUsage[i]) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "Bad KeyUsage in Proxy Certificate"); } } } } } } extensions = issuer.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { oid = (DERObjectIdentifier) e.nextElement(); ext = extensions.getExtension(oid); if (oid.equals(X509Extensions.KeyUsage)) { // If issuer has it then proxy must have it also if (proxyKeyUsage == null) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "KeyUsage extension missing in Proxy Certificate"); } // If issuer has it as critical so does the proxy if (ext.isCritical() && !proxyKeyUsage.isCritical()) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "KeyUsage extension in Proxy Certificate is not critical"); } } } } logger.debug("exit: checkProxyConstraints"); }
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
License:Apache License
protected void checkUnsupportedCriticalExtensions(TBSCertificateStructure crt, int certType, X509Certificate checkedProxy) throws ProxyPathValidatorException { logger.debug("enter: checkUnsupportedCriticalExtensions"); X509Extensions extensions = crt.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { if (oid.equals(X509Extensions.BasicConstraints) || oid.equals(X509Extensions.KeyUsage) || (oid.equals(ProxyCertInfo.OID) && CertUtil.isGsi4Proxy(certType)) || (oid.equals(ProxyCertInfo.OLD_OID) && CertUtil.isGsi3Proxy(certType))) { } else { throw new ProxyPathValidatorException(ProxyPathValidatorException.UNSUPPORTED_EXTENSION, checkedProxy, "Unsuppored critical exception : " + oid.getId()); }/*from w ww.j a v a2s. c om*/ } } } logger.debug("exit: checkUnsupportedCriticalExtensions"); }
From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java
License:Apache License
public static X509Certificate[] buildChain() throws Exception { // create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1);//from w ww . j a v a 2 s . c o m } // create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // process extension request 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); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:org.cagrid.gaards.pki.BouncyCastleCertProcessingFactory.java
License:Open Source License
/** * Creates a proxy certificate. A set of X.509 extensions can be optionally * included in the new proxy certificate. <BR> * If a GSI-2 proxy is created, the serial number of the proxy certificate * will be the same as of the issuing certificate. Also, none of the * extensions in the issuing certificate will be copied into the proxy * certificate.<BR>//w w w. j a va2s .c o m * If a GSI-3 proxy is created, the serial number of the proxy certificate * will be picked randomly. If the issuing certificate contains a * <i>KeyUsage</i> extension, the extension will be copied into the proxy * certificate with <i>keyCertSign</i> and <i>nonRepudiation</i> bits * turned off. No other extensions are currently copied. * * @param issuerCert * the issuing certificate * @param issuerKey * private key matching the public key of issuer certificate. The * new proxy certificate will be signed by that key. * @param publicKey * the public key of the new certificate * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less * then) the new certificate will have the same lifetime as the * issuing certificate. * @param proxyType * can be one of {@link GSIConstants#DELEGATION_LIMITED * GSIConstants.DELEGATION_LIMITED}, * {@link GSIConstants#DELEGATION_FULL * GSIConstants.DELEGATION_FULL}, * {@link GSIConstants#GSI_2_LIMITED_PROXY * GSIConstants.GSI_2_LIMITED_PROXY}, * {@link GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY}, * {@link GSIConstants#GSI_3_IMPERSONATION_PROXY * GSIConstants.GSI_3_IMPERSONATION_PROXY}, * {@link GSIConstants#GSI_3_LIMITED_PROXY * GSIConstants.GSI_3_LIMITED_PROXY}, * {@link GSIConstants#GSI_3_INDEPENDENT_PROXY * GSIConstants.GSI_3_INDEPENDENT_PROXY}, * {@link GSIConstants#GSI_3_RESTRICTED_PROXY * GSIConstants.GSI_3_RESTRICTED_PROXY}. If * {@link GSIConstants#DELEGATION_LIMITED * GSIConstants.DELEGATION_LIMITED} and if * {@link CertUtil#isGsi3Enabled() CertUtil.isGsi3Enabled} * returns true then a GSI-3 limited proxy will be created. If * not, a GSI-2 limited proxy will be created. If * {@link GSIConstants#DELEGATION_FULL * GSIConstants.DELEGATION_FULL} and if * {@link CertUtil#isGsi3Enabled() CertUtil.isGsi3Enabled} * returns true then a GSI-3 impersonation proxy will be created. * If not, a GSI-2 full proxy will be created. * @param extSet * a set of X.509 extensions to be included in the new proxy * certificate. Can be null. If delegation mode is * {@link GSIConstants#GSI_3_RESTRICTED_PROXY * GSIConstants.GSI_3_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension * ProxyCertInfoExtension} must be present in the extension set. * @param cnValue * the value of the CN component of the subject of the new * certificate. If null, the defaults will be used depending on * the proxy certificate type created. * @return <code>X509Certificate</code> the new proxy certificate. * @exception GeneralSecurityException * if a security error occurs. */ public X509Certificate createProxyCertificate(String provider, X509Certificate issuerCert, PrivateKey issuerKey, PublicKey publicKey, int lifetime, int proxyType, X509ExtensionSet extSet, String cnValue, String signatureAlgorithm) throws GeneralSecurityException { if (proxyType == GSIConstants.DELEGATION_LIMITED) { int type = BouncyCastleUtil.getCertificateType(issuerCert); if (CertUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.GSI_4_LIMITED_PROXY; } else if (CertUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.GSI_3_LIMITED_PROXY; } else if (CertUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.GSI_2_LIMITED_PROXY; } else { // default to Globus OID proxyType = (CertUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_LIMITED_PROXY : GSIConstants.GSI_2_LIMITED_PROXY; } } else if (proxyType == GSIConstants.DELEGATION_FULL) { int type = BouncyCastleUtil.getCertificateType(issuerCert); if (CertUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.GSI_4_IMPERSONATION_PROXY; } else if (CertUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.GSI_3_IMPERSONATION_PROXY; } else if (CertUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.GSI_2_PROXY; } else { // Default to Globus OID proxyType = (CertUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_IMPERSONATION_PROXY : GSIConstants.GSI_2_PROXY; } } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); org.globus.gsi.X509Extension x509Ext = null; BigInteger serialNum = null; String delegDN = null; if (CertUtil.isGsi3Proxy(proxyType) || CertUtil.isGsi4Proxy(proxyType)) { Random rand = new Random(); delegDN = String.valueOf(Math.abs(rand.nextInt())); serialNum = new BigInteger(20, rand); if (extSet != null) { x509Ext = extSet.get(ProxyCertInfo.OID.getId()); if (x509Ext == null) { x509Ext = extSet.get(ProxyCertInfo.OLD_OID.getId()); } } if (x509Ext == null) { // create ProxyCertInfo extension ProxyPolicy policy = null; if (CertUtil.isLimitedProxy(proxyType)) { policy = new ProxyPolicy(ProxyPolicy.LIMITED); } else if (CertUtil.isIndependentProxy(proxyType)) { policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT); } else if (CertUtil.isImpersonationProxy(proxyType)) { // since limited has already been checked, this should work. policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); } else if ((proxyType == GSIConstants.GSI_3_RESTRICTED_PROXY) || (proxyType == GSIConstants.GSI_4_RESTRICTED_PROXY)) { throw new IllegalArgumentException("Restricted proxy requires ProxyCertInfo extension"); } else { throw new IllegalArgumentException("Invalid proxyType"); } ProxyCertInfo proxyCertInfo = new ProxyCertInfo(policy); x509Ext = new ProxyCertInfoExtension(proxyCertInfo); if (CertUtil.isGsi4Proxy(proxyType)) { // RFC compliant OID x509Ext = new ProxyCertInfoExtension(proxyCertInfo); } else { // old OID x509Ext = new GlobusProxyCertInfoExtension(proxyCertInfo); } } try { // add ProxyCertInfo extension to the new cert certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); // handle KeyUsage in issuer cert TBSCertificateStructure crt = BouncyCastleUtil.getTBSCertificateStructure(issuerCert); X509Extensions extensions = crt.getExtensions(); if (extensions != null) { X509Extension ext; // handle key usage ext ext = extensions.getExtension(X509Extensions.KeyUsage); if (ext != null) { // TBD: handle this better if (extSet != null && (extSet.get(X509Extensions.KeyUsage.getId()) != null)) { throw new GeneralSecurityException("KeyUsage extension present in X509ExtensionSet " + "and in issuer certificate."); } DERBitString bits = (DERBitString) BouncyCastleUtil.getExtensionObject(ext); byte[] bytes = bits.getBytes(); // make sure they are disabled if ((bytes[0] & KeyUsage.nonRepudiation) != 0) { bytes[0] ^= KeyUsage.nonRepudiation; } if ((bytes[0] & KeyUsage.keyCertSign) != 0) { bytes[0] ^= KeyUsage.keyCertSign; } bits = new DERBitString(bytes, bits.getPadBits()); certGen.addExtension(X509Extensions.KeyUsage, ext.isCritical(), bits); } } } catch (IOException e) { // but this should not happen throw new GeneralSecurityException(e.getMessage()); } } else if (proxyType == GSIConstants.GSI_2_LIMITED_PROXY) { delegDN = "limited proxy"; serialNum = issuerCert.getSerialNumber(); } else if (proxyType == GSIConstants.GSI_2_PROXY) { delegDN = "proxy"; serialNum = issuerCert.getSerialNumber(); } else { throw new IllegalArgumentException("Unsupported proxyType : " + proxyType); } // add specified extensions if (extSet != null) { Iterator iter = extSet.oidSet().iterator(); while (iter.hasNext()) { String oid = (String) iter.next(); // skip ProxyCertInfo extension if (oid.equals(ProxyCertInfo.OID.getId()) || oid.equals(ProxyCertInfo.OLD_OID.getId())) { continue; } x509Ext = (org.globus.gsi.X509Extension) extSet.get(oid); certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); } } X509Name issuerDN = (X509Name) issuerCert.getSubjectDN(); X509NameHelper issuer = new X509NameHelper(issuerDN); X509NameHelper subject = new X509NameHelper(issuerDN); subject.add(X509Name.CN, (cnValue == null) ? delegDN : cnValue); certGen.setSubjectDN(subject.getAsName()); certGen.setIssuerDN(issuer.getAsName()); certGen.setSerialNumber(serialNum); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm(signatureAlgorithm); GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); /* Allow for a five minute clock skew here. */ date.add(Calendar.MINUTE, -5); certGen.setNotBefore(date.getTime()); /* If hours = 0, then cert lifetime is set to user cert */ if (lifetime <= 0) { certGen.setNotAfter(issuerCert.getNotAfter()); } else { date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); certGen.setNotAfter(date.getTime()); } /** * FIXME: Copy appropriate cert extensions - this should NOT be done the * last time we talked to Doug E. This should investigated more. */ return certGen.generateX509Certificate(issuerKey, provider); }
From source file:org.candlepin.util.X509CRLStreamWriter.java
License:Open Source License
protected void writeToEmptyCrl(OutputStream out) throws IOException { ASN1InputStream asn1in = null; try {/*from w w w.j a va2 s .c o m*/ asn1in = new ASN1InputStream(crlIn); DERSequence certListSeq = (DERSequence) asn1in.readObject(); CertificateList certList = new CertificateList(certListSeq); X509CRLHolder oldCrl = new X509CRLHolder(certList); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date()); crlBuilder.addCRL(oldCrl); Date now = new Date(); Date oldNextUpdate = certList.getNextUpdate().getDate(); Date oldThisUpdate = certList.getThisUpdate().getDate(); Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime())); crlBuilder.setNextUpdate(nextUpdate); for (Object o : oldCrl.getExtensionOIDs()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o; X509Extension ext = oldCrl.getExtension(oid); if (oid.equals(X509Extension.cRLNumber)) { DEROctetString octet = (DEROctetString) ext.getValue().getDERObject(); DERInteger currentNumber = (DERInteger) DERTaggedObject.fromByteArray(octet.getOctets()); DERInteger nextNumber = new DERInteger(currentNumber.getValue().add(BigInteger.ONE)); crlBuilder.addExtension(oid, ext.isCritical(), nextNumber); } else if (oid.equals(X509Extension.authorityKeyIdentifier)) { crlBuilder.addExtension(oid, ext.isCritical(), new AuthorityKeyIdentifierStructure(ext.getValue().getDEREncoded())); } } for (DERSequence entry : newEntries) { // XXX: This is all a bit messy considering the user already passed in the serial, date // and reason. BigInteger serial = ((DERInteger) entry.getObjectAt(0)).getValue(); Date revokeDate = ((Time) entry.getObjectAt(1)).getDate(); int reason = CRLReason.unspecified; if (entry.size() == 3) { X509Extensions extensions = (X509Extensions) entry.getObjectAt(2); X509Extension reasonExt = extensions.getExtension(X509Extension.reasonCode); if (reasonExt != null) { reason = ((DEREnumerated) reasonExt.getParsedValue()).getValue().intValue(); } } crlBuilder.addCRLEntry(serial, revokeDate, reason); } RSAKeyParameters keyParams = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent()); signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm(); digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg); ContentSigner s; try { s = new BcRSAContentSignerBuilder(signingAlg, digestAlg).build(keyParams); X509CRLHolder newCrl = crlBuilder.build(s); out.write(newCrl.getEncoded()); } catch (OperatorCreationException e) { throw new IOException("Could not sign CRL", e); } } finally { IOUtils.closeQuietly(asn1in); } }
From source file:org.ejbca.core.model.ca.caadmin.X509CA.java
License:Open Source License
/** * sequence is ignored by X509CA// w w w .j ava 2 s . com */ public Certificate generateCertificate(UserDataVO subject, X509Name requestX509Name, PublicKey publicKey, int keyusage, Date notBefore, Date notAfter, CertificateProfile certProfile, X509Extensions extensions, String sequence, PublicKey caPublicKey, PrivateKey caPrivateKey, String provider) throws Exception { // We must only allow signing to take place if the CA itself if on line, even if the token is on-line. // We have to allow expired as well though, so we can renew expired CAs if ((getStatus() != SecConst.CA_ACTIVE) && ((getStatus() != SecConst.CA_EXPIRED))) { String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus()); if (log.isDebugEnabled()) { log.debug(msg); // This is something we handle so no need to log with higher priority } throw new CAOfflineException(msg); } final String sigAlg; if (certProfile.getSignatureAlgorithm() == null) { sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm(); } else { sigAlg = certProfile.getSignatureAlgorithm(); } final X509Certificate cacert = (X509Certificate) getCACertificate(); String dn = subject.getCertificateDN(); // Check if this is a root CA we are creating final boolean isRootCA = certProfile.getType() == CertificateProfile.TYPE_ROOTCA; // Get certificate validity time notBefore and notAfter final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert, isRootCA); final X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); { // Serialnumber is either random bits, where random generator is initialized by the serno generator. // Or a custom serial number defined in the end entity object final ExtendedInformation ei = subject.getExtendedinformation(); BigInteger customSN = ei != null ? ei.certificateSerialNumber() : null; if (customSN != null) { if (!certProfile.getAllowCertSerialNumberOverride()) { final String msg = intres.getLocalizedMessage( "signsession.certprof_not_allowing_cert_sn_override_using_normal", customSN.toString(16)); log.info(msg); customSN = null; } else { if (log.isDebugEnabled()) { log.debug("Using custom serial number: " + customSN.toString(16)); } } } final BigInteger serno = customSN != null ? customSN : SernoGenerator.instance().getSerno(); certgen.setSerialNumber(serno); } certgen.setNotBefore(val.getNotBefore()); certgen.setNotAfter(val.getNotAfter()); certgen.setSignatureAlgorithm(sigAlg); // Make DNs if (certProfile.getUseSubjectDNSubSet()) { dn = certProfile.createSubjectDNSubSet(dn); } if (certProfile.getUseCNPostfix()) { dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix()); } X509NameEntryConverter converter = null; if (getUsePrintableStringSubjectDN()) { converter = new PrintableStringEntryConverter(); } else { converter = new X509DefaultEntryConverter(); } // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN boolean ldapdnorder = true; if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) { ldapdnorder = false; } X509Name subjectDNName = CertTools.stringToBcX509Name(dn, converter, ldapdnorder); if (certProfile.getAllowDNOverride() && (requestX509Name != null)) { subjectDNName = requestX509Name; if (log.isDebugEnabled()) { log.debug("Using X509Name from request instead of user's registered."); } } if (log.isDebugEnabled()) { log.debug("Using subjectDN: " + subjectDNName.toString()); } certgen.setSubjectDN(subjectDNName); // 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"); } certgen.setIssuerDN(subjectDNName); } else { javax.security.auth.x500.X500Principal issuerPrincipal = cacert.getSubjectX500Principal(); if (log.isDebugEnabled()) { log.debug("Using issuer DN directly from the CA certificate: " + issuerPrincipal.getName()); } certgen.setIssuerDN(issuerPrincipal); } certgen.setPublicKey(publicKey); // // X509 Certificate Extensions // // Extensions we will add to the certificate, later when we have filled the structure with // everything we want. X509ExtensionsGenerator extgen = new X509ExtensionsGenerator(); // First we check if there is general extension override, and add all extensions from // the request in that case if (certProfile.getAllowExtensionOverride() && extensions != null) { Enumeration en = extensions.oids(); while (en != null && en.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement(); X509Extension ext = extensions.getExtension(oid); if (log.isDebugEnabled()) { log.debug("Overriding extension with oid: " + oid); } extgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } // Second we see if there is Key usage override X509Extensions overridenexts = extgen.generate(); if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) { if (log.isDebugEnabled()) { log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage); } if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) { X509KeyUsage ku = new X509KeyUsage(keyusage); // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(X509Extensions.KeyUsage) == null) { extgen.addExtension(X509Extensions.KeyUsage, certProfile.getKeyUsageCritical(), ku); } else { if (log.isDebugEnabled()) { log.debug( "KeyUsage was already overridden by an extension, not using KeyUsage from parameter."); } } } } // Third, check for standard Certificate Extensions that should be added. // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory // and implemented in package org.ejbca.core.model.certextensions.standard CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance(); List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions(); Iterator<String> certStdExtIter = usedStdCertExt.iterator(); overridenexts = extgen.generate(); while (certStdExtIter.hasNext()) { String oid = certStdExtIter.next(); // We don't want to try to add standard extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new DERObjectIdentifier(oid)) == null) { CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile); if (certExt != null) { byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey); if (value != null) { extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + oid + " has been overridden, standard extension will not be added."); } } } // Fourth, check for custom Certificate Extensions that should be added. // Custom certificate extensions is defined in certextensions.properties fact = CertificateExtensionFactory.getInstance(); List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions(); Iterator<Integer> certExtIter = usedCertExt.iterator(); while (certExtIter.hasNext()) { Integer id = certExtIter.next(); CertificateExtension certExt = fact.getCertificateExtensions(id); if (certExt != null) { // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new DERObjectIdentifier(certExt.getOID())) == null) { byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey); if (value != null) { extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + certExt.getOID() + " has been overridden, custom extension will not be added."); } } } } // Finally add extensions to certificate generator X509Extensions exts = extgen.generate(); Enumeration en = exts.oids(); while (en.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement(); X509Extension ext = exts.getExtension(oid); certgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } // // End of extensions // X509Certificate cert; if (log.isTraceEnabled()) { log.trace(">certgen.generate"); } cert = certgen.generate(caPrivateKey, provider); if (log.isTraceEnabled()) { log.trace("<certgen.generate"); } // Verify using the CA certificate before returning // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert // because something is wrong... PublicKey verifyKey; // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing // the keys. In this case the _new_ key will not match the current CA certificate. if ((cacert != null) && (!isRootCA)) { verifyKey = cacert.getPublicKey(); } else { verifyKey = caPublicKey; } cert.verify(verifyKey); // If we have a CA-certificate, verify that we have all path verification stuff correct if (cacert != null) { byte[] aki = CertTools.getAuthorityKeyId(cert); byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert); if ((aki != null) && (ski != null)) { boolean eq = Arrays.equals(aki, ski); if (!eq) { String akistr = new String(Hex.encode(aki)); String skistr = new String(Hex.encode(ski)); log.error(intres.getLocalizedMessage("signsession.errorpathverifykeyid", akistr, skistr)); } } Principal issuerDN = cert.getIssuerX500Principal(); Principal subjectDN = cacert.getSubjectX500Principal(); if ((issuerDN != null) && (subjectDN != null)) { boolean eq = issuerDN.equals(subjectDN); if (!eq) { log.error(intres.getLocalizedMessage("signsession.errorpathverifydn", issuerDN.getName(), subjectDN.getName())); } } } if (log.isDebugEnabled()) { log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: " + subject.getCertificateDN()); } return cert; }