List of usage examples for org.bouncycastle.asn1.x509 X509Extensions KeyUsage
ASN1ObjectIdentifier KeyUsage
To view the source code for org.bouncycastle.asn1.x509 X509Extensions KeyUsage.
Click Source Link
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>//from w ww .j av a 2 s. c om * 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.pki.impl.BouncyCastlePKIUtility.java
License:Open Source License
@Override public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Certificate caCert = reader.getCACert(); // set cert fields certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(startDate);/*from w ww .j av a2 s . c o m*/ certGen.setNotAfter(endDate); X500Principal subjectPrincipal = new X500Principal(dn); certGen.setSubjectDN(subjectPrincipal); certGen.setPublicKey(clientKeyPair.getPublic()); certGen.setSignatureAlgorithm(SIGNATURE_ALGO); // set key usage - required for proper x509 function KeyUsage keyUsage = new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment); // add SSL extensions - required for proper x509 function NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime); certGen.addExtension(MiscObjectIdentifiers.netscapeCertType.toString(), false, certType); certGen.addExtension(X509Extensions.KeyUsage.toString(), false, keyUsage); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); // Add an alternate name if provided if (alternateName != null) { GeneralName name = new GeneralName(GeneralName.uniformResourceIdentifier, "CN=" + alternateName); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(name)); } if (extensions != null) { for (X509ExtensionWrapper wrapper : extensions) { // Bouncycastle hates null values. So, set them to blank // if they are null String value = wrapper.getValue() == null ? "" : wrapper.getValue(); certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DERUTF8String(value)); } } if (byteExtensions != null) { for (X509ByteExtensionWrapper wrapper : byteExtensions) { // Bouncycastle hates null values. So, set them to blank // if they are null byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue(); certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DEROctetString(value)); } } // Generate the certificate return certGen.generate(reader.getCaKey()); }
From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCertificateGenerator.java
License:Open Source License
/** * Basic common path.// w w w. j a v a 2 s.c om * @param subjectDN the distinguished name of the subject. * @param subjectPublicKey the public key of the subject. * @param issuerDN the distinguished name of the issuer. * @param duration the validity duration of the certificate. * @param isCA * @param allUsage if isCA is true, add "regular" KeyUsage flags, for dual-use cert */ public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey, X500Principal issuerDN, long duration, boolean isCA, Integer chainLength, boolean allUsage) { _generator.setSubjectDN(new X509Name(subjectDN)); _generator.setIssuerDN(issuerDN); _generator.setSerialNumber(new BigInteger(64, cachedRandom)); _generator.setPublicKey(subjectPublicKey); Date startTime = new Date(); Date stopTime = new Date(startTime.getTime() + duration); _generator.setNotBefore(startTime); _generator.setNotAfter(stopTime); // CA key usage final int caKeyUsage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyCertSign | KeyUsage.cRLSign; // Non-CA key usage final int nonCAKeyUsage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement; int ourUsage; if (isCA) { if (!allUsage) { ourUsage = caKeyUsage; } else { ourUsage = caKeyUsage | nonCAKeyUsage; } } else { ourUsage = nonCAKeyUsage; } _generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(ourUsage)); BasicConstraints bc = ((isCA == false) || (null == chainLength)) ? new BasicConstraints(isCA) : new BasicConstraints(chainLength.intValue()); _generator.addExtension(X509Extensions.BasicConstraints, true, bc); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(CryptoUtil.generateKeyID(subjectPublicKey)); _generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); }
From source file:org.deviceconnect.android.ssl.AbstractKeyStoreManager.java
License:MIT License
private X509Certificate generateX509V3Certificate(final KeyPair keyPair, final X500Principal subject, final X500Principal issuer, final Date notBefore, final Date notAfter, final BigInteger serialNumber, final GeneralNames generalNames, final boolean isCA) throws GeneralSecurityException { Security.addProvider(new BouncyCastleProvider()); X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); generator.setSerialNumber(serialNumber); generator.setIssuerDN(issuer);//from w w w . j ava 2s .co m generator.setSubjectDN(subject); generator.setNotBefore(notBefore); generator.setNotAfter(notAfter); generator.setPublicKey(keyPair.getPublic()); generator.setSignatureAlgorithm("SHA256WithRSAEncryption"); generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA)); generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160)); generator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); if (generalNames != null) { generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames); } return generator.generateX509Certificate(keyPair.getPrivate(), "BC"); }
From source file:org.ejbca.core.ejb.ca.sign.RSASignSessionBean.java
License:Open Source License
@Override public IResponseMessage createCertificate(Admin admin, IRequestMessage req, Class responseClass, UserDataVO suppliedUserData) throws EjbcaException { if (log.isTraceEnabled()) { log.trace(">createCertificate(IRequestMessage)"); }//from w w w.j a v a2 s.c o m // Get CA that will receive request UserDataVO data = null; IResponseMessage ret = null; CA ca; if (suppliedUserData == null) { ca = getCAFromRequest(admin, req); } else { ca = caSession.getCA(admin, suppliedUserData.getCAId()); // Take the CAId from the supplied userdata, if any } try { CATokenContainer catoken = ca.getCAToken(); // See if we need some key material to decrypt request if (req.requireKeyInfo()) { // You go figure...scep encrypts message with the public CA-cert req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getJCEProvider()); } // Verify the request if (req.verify() == false) { String msg = intres.getLocalizedMessage("signsession.popverificationfailed"); logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg); throw new SignRequestSignatureException(msg); } if (ca.isUseUserStorage() && req.getUsername() == null) { String msg = intres.getLocalizedMessage("signsession.nouserinrequest", req.getRequestDN()); logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg); throw new SignRequestException(msg); //ret.setFailInfo(FailInfo.BAD_REQUEST); //ret.setStatus(ResponseStatus.FAILURE); } else if (ca.isUseUserStorage() && req.getPassword() == null) { String msg = intres.getLocalizedMessage("signsession.nopasswordinrequest"); logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg); throw new SignRequestException(msg); } else { ResponseStatus status = ResponseStatus.SUCCESS; FailInfo failInfo = null; String failText = null; Certificate cert = null; try { // If we haven't done so yet, authenticate user. (Only if we store UserData for this CA.) if (ca.isUseUserStorage()) { data = authUser(admin, req.getUsername(), req.getPassword()); } else { data = suppliedUserData; } PublicKey reqpk = req.getRequestPublicKey(); if (reqpk == null) { logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, intres.getLocalizedMessage("signsession.nokeyinrequest")); throw new InvalidKeyException("Key is null!"); } // We need to make sure we use the users registered CA here if (data.getCAId() != ca.getCAId()) { failText = intres.getLocalizedMessage("signsession.wrongauthority", Integer.valueOf(ca.getCAId()), Integer.valueOf(data.getCAId())); status = ResponseStatus.FAILURE; failInfo = FailInfo.WRONG_AUTHORITY; logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText); } if (status.equals(ResponseStatus.SUCCESS)) { Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity X509Extensions exts = req.getRequestExtensions(); // Optionally requested extensions int keyusage = -1; if (exts != null) { if (log.isDebugEnabled()) { log.debug( "we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request"); } X509Extension ext = exts.getExtension(X509Extensions.KeyUsage); if (ext != null) { ASN1OctetString os = ext.getValue(); ByteArrayInputStream bIs = new ByteArrayInputStream(os.getOctets()); ASN1InputStream dIs = new ASN1InputStream(bIs); DERObject dob = dIs.readObject(); DERBitString bs = DERBitString.getInstance(dob); keyusage = bs.intValue(); if (log.isDebugEnabled()) { log.debug("We have a key usage request extension: " + keyusage); } } } String sequence = null; byte[] ki = req.getRequestKeyInfo(); if ((ki != null) && (ki.length > 0)) { sequence = new String(ki); } cert = createCertificate(admin, data, req.getRequestX509Name(), ca, reqpk, keyusage, notBefore, notAfter, exts, sequence); } } catch (ObjectNotFoundException oe) { // If we didn't find the entity return error message log.error("User not found: ", oe); failText = intres.getLocalizedMessage("signsession.nosuchuser", req.getUsername()); status = ResponseStatus.FAILURE; failInfo = FailInfo.INCORRECT_DATA; logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText); } //Create the response message with all nonces and checks etc ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider()); if ((cert == null) && (status == ResponseStatus.SUCCESS)) { status = ResponseStatus.FAILURE; failInfo = FailInfo.BAD_REQUEST; } else { ret.setCertificate(cert); } ret.setStatus(status); if (failInfo != null) { ret.setFailInfo(failInfo); ret.setFailText(failText); } } ret.create(); // Call authentication session and tell that we are finished with this user. (Only if we store UserData for this CA.) if (ca.isUseUserStorage() && data != null) { finishUser(ca, data); } } catch (NoUniqueCertSerialNumberIndexException e) { cleanUserCertDataSN(data); throw e.ejbcaException; } catch (IllegalKeyException ke) { log.error("Key is of unknown type: ", ke); throw ke; } catch (CATokenOfflineException ctoe) { String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getSubjectDN()); CATokenOfflineException ex = new CATokenOfflineException(msg); ex.initCause(ctoe); throw ex; //} catch (EjbcaException e) { // throw e; } catch (NoSuchProviderException e) { log.error("NoSuchProvider provider: ", e); } catch (InvalidKeyException e) { log.error("Invalid key in request: ", e); } catch (NoSuchAlgorithmException e) { log.error("No such algorithm: ", e); } catch (IOException e) { log.error("Cannot create response message: ", e); } if (log.isTraceEnabled()) { log.trace("<createCertificate(IRequestMessage)"); } return ret; }
From source file:org.ejbca.core.model.ca.caadmin.X509CA.java
License:Open Source License
/** * sequence is ignored by X509CA/*from w ww . j a v a 2 s . c o m*/ */ 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; }
From source file:org.ejbca.core.model.ca.certextensions.standard.KeyUsage.java
License:Open Source License
@Override public void init(final CertificateProfile certProf) { super.setOID(X509Extensions.KeyUsage.getId()); super.setCriticalFlag(certProf.getKeyUsageCritical()); }
From source file:org.ejbca.core.model.ca.certificateprofiles.CertificateProfileTest.java
License:Open Source License
public void test09CertificateExtensions() throws Exception { log.trace(">test09CertificateExtensions()"); CertificateProfile profile = new CertificateProfile(); // Check standard values for the certificate profile List l = profile.getUsedStandardCertificateExtensions(); assertEquals(l.size(), 5);/*from w w w . j av a 2s .co m*/ assertTrue(l.contains(X509Extensions.KeyUsage.getId())); assertTrue(l.contains(X509Extensions.BasicConstraints.getId())); assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId())); assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId())); assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId())); CertificateProfile eprofile = new EndUserCertificateProfile(); // Check standard values for the certificate profile l = eprofile.getUsedStandardCertificateExtensions(); assertEquals(l.size(), 6); assertTrue(l.contains(X509Extensions.KeyUsage.getId())); assertTrue(l.contains(X509Extensions.BasicConstraints.getId())); assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId())); assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId())); assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId())); assertTrue(l.contains(X509Extensions.ExtendedKeyUsage.getId())); profile = new CertificateProfile(); profile.setUseAuthorityInformationAccess(true); profile.setUseCertificatePolicies(true); profile.setUseCRLDistributionPoint(true); profile.setUseFreshestCRL(true); profile.setUseMicrosoftTemplate(true); profile.setUseOcspNoCheck(true); profile.setUseQCStatement(true); profile.setUseExtendedKeyUsage(true); profile.setUseSubjectDirAttributes(true); l = profile.getUsedStandardCertificateExtensions(); assertEquals(l.size(), 14); assertTrue(l.contains(X509Extensions.KeyUsage.getId())); assertTrue(l.contains(X509Extensions.BasicConstraints.getId())); assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId())); assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId())); assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId())); assertTrue(l.contains(X509Extensions.ExtendedKeyUsage.getId())); assertTrue(l.contains(X509Extensions.AuthorityInfoAccess.getId())); assertTrue(l.contains(X509Extensions.CertificatePolicies.getId())); assertTrue(l.contains(X509Extensions.CRLDistributionPoints.getId())); assertTrue(l.contains(X509Extensions.FreshestCRL.getId())); assertTrue(l.contains(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())); assertTrue(l.contains(X509Extensions.QCStatements.getId())); assertTrue(l.contains(X509Extensions.SubjectDirectoryAttributes.getId())); assertTrue(l.contains(CertTools.OID_MSTEMPLATE)); }
From source file:org.ejbca.util.CertTools.java
License:Open Source License
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { // Create self signed certificate 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(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/* w ww .java2s . c om*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); certgen.setSerialNumber(new java.math.BigInteger(serno).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(publicKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey, provider); return selfcert; }
From source file:org.glite.security.delegation.GrDProxyGenerator.java
License:Apache License
/** * Create a proxy certificate from a given certificate * /*www. j a v a2 s. c o m*/ * @param issuerCert * issuer certificate * @param issuerKey * issuer private key * @param publicKey * public key of delegatee * @param lifetime * life time of proxy * @param proxyType * type of proxy * @param cnValue * common name of proxy * @return created proxy certificate * @throws GeneralSecurityException * @deprecated Use proxy generator from util-java */ public X509Certificate createProxyCertificate(X509Certificate issuerCert, PrivateKey issuerKey, PublicKey publicKey, int lifetime1, int proxyType1, String cnValue) throws GeneralSecurityException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); BigInteger serialNum = null; serialNum = issuerCert.getSerialNumber(); X509Name issuer = (X509Name) issuerCert.getSubjectDN(); ASN1Sequence seqSubject = (ASN1Sequence) issuer.getDERObject(); logger.debug("SubjectDN of IssuerCert" + issuer); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(X509Name.CN); v.add(new DERPrintableString(cnValue)); Enumeration subjectParts = seqSubject.getObjects(); ASN1EncodableVector subjectVector = new ASN1EncodableVector(); while (subjectParts.hasMoreElements()) { DERObject part = (DERObject) subjectParts.nextElement(); subjectVector.add(part); } subjectVector.add(new DERSet(new DERSequence(v))); DERSequence subjDerSeq = new DERSequence(subjectVector); X509Name subjectX = new X509Name(subjDerSeq); logger.debug("SubjectDN :" + subjectX); certGen.setSubjectDN(subjectX); certGen.setIssuerDN(issuer); certGen.setSerialNumber(serialNum); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm(issuerCert.getSigAlgName()); certGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature)); GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("UTC")); date.add(Calendar.MINUTE, -5); certGen.setNotBefore(date.getTime()); if (lifetime1 <= 0) { certGen.setNotAfter(issuerCert.getNotAfter()); } else { date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime1); certGen.setNotAfter(date.getTime()); } return certGen.generateX509Certificate(issuerKey); }