List of usage examples for org.bouncycastle.asn1.x509 X509Extensions BasicConstraints
ASN1ObjectIdentifier BasicConstraints
To view the source code for org.bouncycastle.asn1.x509 X509Extensions BasicConstraints.
Click Source Link
From source file:org.mailster.gui.dialogs.CertificateDialog.java
License:Open Source License
private void generateExtensionNode(TreeItem parent, X509Certificate cert, X509Extensions extensions, String oid) {//w w w .j a v a 2 s. co m DERObjectIdentifier derOID = new DERObjectIdentifier(oid); X509Extension ext = extensions.getExtension(derOID); if (ext.getValue() == null) return; byte[] octs = ext.getValue().getOctets(); ASN1InputStream dIn = new ASN1InputStream(octs); StringBuilder buf = new StringBuilder(); try { if (ext.isCritical()) buf.append(Messages.getString("MailsterSWT.dialog.certificate.criticalExt")); //$NON-NLS-1$ else buf.append(Messages.getString("MailsterSWT.dialog.certificate.nonCriticalExt")); //$NON-NLS-1$ if (derOID.equals(X509Extensions.BasicConstraints)) { BasicConstraints bc = new BasicConstraints((ASN1Sequence) dIn.readObject()); if (bc.isCA()) buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.isCA")); //$NON-NLS-1$ else buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.notCA")); //$NON-NLS-1$ buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.maxIntermediateCA")); //$NON-NLS-1$ if (bc.getPathLenConstraint() == null || bc.getPathLenConstraint().intValue() == Integer.MAX_VALUE) buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.unlimited")); //$NON-NLS-1$ else buf.append(bc.getPathLenConstraint()).append('\n'); generateNode(parent, Messages.getString(oid), buf); } else if (derOID.equals(X509Extensions.KeyUsage)) { KeyUsage us = new KeyUsage((DERBitString) dIn.readObject()); if ((us.intValue() & KeyUsage.digitalSignature) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.digitalSignature")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.nonRepudiation) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.nonRepudiation")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.keyEncipherment) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyEncipherment")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.dataEncipherment) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.dataEncipherment")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.keyAgreement) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyAgreement")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.keyCertSign) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyCertSign")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.cRLSign) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.cRLSign")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.encipherOnly) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.encipherOnly")); //$NON-NLS-1$ if ((us.intValue() & KeyUsage.decipherOnly) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.decipherOnly")); //$NON-NLS-1$ generateNode(parent, Messages.getString(oid), buf); } else if (derOID.equals(X509Extensions.SubjectKeyIdentifier)) { SubjectKeyIdentifier id = new SubjectKeyIdentifier((DEROctetString) dIn.readObject()); generateNode(parent, Messages.getString(oid), buf.toString() + CertificateUtilities.byteArrayToString(id.getKeyIdentifier())); } else if (derOID.equals(X509Extensions.AuthorityKeyIdentifier)) { AuthorityKeyIdentifier id = new AuthorityKeyIdentifier((ASN1Sequence) dIn.readObject()); generateNode(parent, Messages.getString(oid), buf.toString() + id.getAuthorityCertSerialNumber()); } else if (derOID.equals(MiscObjectIdentifiers.netscapeRevocationURL)) { buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append("\n"); generateNode(parent, Messages.getString(oid), buf.toString()); } else if (derOID.equals(MiscObjectIdentifiers.verisignCzagExtension)) { buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append("\n"); generateNode(parent, Messages.getString(oid), buf.toString()); } else if (derOID.equals(X509Extensions.CRLNumber)) { buf.append((DERInteger) dIn.readObject()).append("\n"); generateNode(parent, Messages.getString(oid), buf.toString()); } else if (derOID.equals(X509Extensions.ReasonCode)) { ReasonFlags rf = new ReasonFlags((DERBitString) dIn.readObject()); if ((rf.intValue() & ReasonFlags.unused) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.unused")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.keyCompromise) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.keyCompromise")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.cACompromise) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.cACompromise")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.affiliationChanged) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.affiliationChanged")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.superseded) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.superseded")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.cessationOfOperation) > 0) buf.append( Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.cessationOfOperation")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.certificateHold) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.certificateHold")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.privilegeWithdrawn) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.privilegeWithdrawn")); //$NON-NLS-1$ if ((rf.intValue() & ReasonFlags.aACompromise) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.aACompromise")); //$NON-NLS-1$ generateNode(parent, Messages.getString(oid), buf.toString()); } else if (derOID.equals(MiscObjectIdentifiers.netscapeCertType)) { NetscapeCertType type = new NetscapeCertType((DERBitString) dIn.readObject()); if ((type.intValue() & NetscapeCertType.sslClient) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslClient")); //$NON-NLS-1$ if ((type.intValue() & NetscapeCertType.sslServer) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslServer")); //$NON-NLS-1$ if ((type.intValue() & NetscapeCertType.smime) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.smime")); //$NON-NLS-1$ if ((type.intValue() & NetscapeCertType.objectSigning) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.objectSigning")); //$NON-NLS-1$ if ((type.intValue() & NetscapeCertType.reserved) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.reserved")); //$NON-NLS-1$ if ((type.intValue() & NetscapeCertType.sslCA) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslCA")); //$NON-NLS-1$ if ((type.intValue() & NetscapeCertType.smimeCA) > 0) buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.smimeCA")); //$NON-NLS-1$ if ((type.intValue() & NetscapeCertType.objectSigningCA) > 0) buf.append( Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.objectSigningCA")); //$NON-NLS-1$ generateNode(parent, Messages.getString(oid), buf.toString()); } else if (derOID.equals(X509Extensions.ExtendedKeyUsage)) { ExtendedKeyUsage eku = new ExtendedKeyUsage((ASN1Sequence) dIn.readObject()); if (eku.hasKeyPurposeId(KeyPurposeId.anyExtendedKeyUsage)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.anyExtendedKeyUsage")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth)) buf.append( Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_clientAuth")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_codeSigning)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_codeSigning")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_emailProtection")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecEndSystem)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecEndSystem")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecTunnel)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecTunnel")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecUser)) buf.append( Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecUser")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_OCSPSigning")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth)) buf.append( Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_serverAuth")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_smartcardlogon)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_smartcardlogon")); //$NON-NLS-1$ if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping)) buf.append(Messages .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_timeStamping")); //$NON-NLS-1$ generateNode(parent, Messages.getString(oid), buf.toString()); } else generateNode(parent, MessageFormat.format(Messages.getString("MailsterSWT.dialog.certificate.objectIdentifier"), //$NON-NLS-1$ new Object[] { oid.replace('.', ' ') }), CertificateUtilities.byteArrayToString((cert.getExtensionValue(oid)))); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.neociclo.odetteftp.util.OnTheFlyHelper.java
License:Apache License
public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception { installBouncyCastleProviderIfNecessary(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate")); certGen.setPublicKey(intKey);/*from w w w . j a va2 s .c om*/ certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); return certGen.generate(caKey, BC_PROVIDER); }
From source file:org.neociclo.odetteftp.util.OnTheFlyHelper.java
License:Apache License
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { installBouncyCastleProviderIfNecessary(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test End Certificate")); certGen.setPublicKey(entityKey);// w w w . j a va 2 s . c o m certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); return certGen.generate(caKey, BC_PROVIDER); }
From source file:org.nimbustools.auto_common.ezpz_ca.CAFactory.java
License:Apache License
public X509Certificate create(String baseName, int months, KeyPair keyPair) throws Exception { final X509Principal newprincipal = new X509Principal("O=Auto,OU=" + baseName + ",CN=CA"); this.certGen.reset(); /*//w w w.ja v a2s . c o m "The entity that created the certificate is responsible for assigning it a serial number to distinguish it from other certificates it issues. This information is used in numerous ways, for example when a certificate is revoked its serial number is placed in a Certificate Revocation List (CRL)" */ this.certGen.setSerialNumber(BigInteger.ZERO); final Calendar expires = Calendar.getInstance(); expires.add(Calendar.MONTH, months); this.certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); this.certGen.setNotAfter(expires.getTime()); this.certGen.setSubjectDN(newprincipal); this.certGen.setIssuerDN(newprincipal); this.certGen.setSignatureAlgorithm("SHA1withRSA"); final PublicKey pubkey = keyPair.getPublic(); this.certGen.setPublicKey(pubkey); // begin X509/BC security nastiness, not sure these are the very best // choices but it is working... final ByteArrayInputStream in = new ByteArrayInputStream(pubkey.getEncoded()); final SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new DERInputStream(in).readObject()); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); final ByteArrayInputStream in2 = new ByteArrayInputStream(newprincipal.getEncoded()); final GeneralNames generalNames = new GeneralNames((ASN1Sequence) new DERInputStream(in2).readObject()); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(spki, generalNames, BigInteger.ZERO); this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* this.certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); */ this.certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); this.certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); this.certGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); return this.certGen.generateX509Certificate(keyPair.getPrivate()); }
From source file:org.nimbustools.auto_common.ezpz_ca.EzPzCA.java
License:Apache License
private void initializeGenerator() { this.certGen.reset(); this.certGen.setSerialNumber(this.caX509.getSerialNumber()); this.certGen.setSignatureAlgorithm(this.caX509.getSigAlgName()); this.certGen.setIssuerDN(this.caX509Name); this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); this.certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); }
From source file:org.nimbustools.ctxbroker.security.CertificateAuthority.java
License:Apache License
private void initializeGenerator() { this.certGen.reset(); this.certGen.setSerialNumber(this.caX509.getSerialNumber().add(BigInteger.ONE)); this.certGen.setSignatureAlgorithm(this.caX509.getSigAlgName()); this.certGen.setIssuerDN(this.caX509Name); this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); this.certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
License:Open Source License
protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException { X509Certificate cert;//w w w. ja v a 2 s . com try { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal()); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setNotBefore(getCertStartDate()); certGen.setNotAfter(getCertEndDate()); certGen.setPublicKey(csr.getPublicKey("BC")); certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(getRootCertificate())); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); @SuppressWarnings("rawtypes") 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()); } } } KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(), rootService.getRootCertificateAlias(), rootService.getRootKeyPassword()); cert = certGen.generate(rootKeyPair.getPrivate(), "BC"); } catch (CertificateParsingException e) { throw new CertException(e); } catch (CertificateEncodingException e) { throw new CertException(e); } catch (InvalidKeyException e) { throw new CertException(e); } catch (IllegalStateException e) { throw new CertException(e); } catch (NoSuchProviderException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } catch (java.security.SignatureException e) { throw new CertException(e); } LOG.debug("Certificate generated for subject: " + cert.getSubjectDN()); return cert; }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
/** * DOCUMENT ME!/*ww w . j a va 2 s . c om*/ * * @param dn DOCUMENT ME! * @param validity DOCUMENT ME! * @param policyId DOCUMENT ME! * @param privKey DOCUMENT ME! * @param pubKey DOCUMENT ME! * @param isCA DOCUMENT ME! * * @return DOCUMENT ME! * * @throws NoSuchAlgorithmException DOCUMENT ME! * @throws SignatureException DOCUMENT ME! * @throws InvalidKeyException DOCUMENT ME! * @throws IllegalStateException * @throws CertificateEncodingException */ public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException { // Create self signed certificate String sigAlg = "SHA1WithRSA"; 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(); // 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(pubKey); // 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 == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; 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 Mozilla. try { if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.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); return selfcert; }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
public static X509Certificate genCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA, String caDn, PrivateKey caPrivateKey, PublicKey acPubKey) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException {/* w w w. j a v a 2 s . c om*/ // Create self signed certificate String sigAlg = "SHA1WithRSA"; 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(); // 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(caDn)); certgen.setPublicKey(pubKey); // 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 (false) { //if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; 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 Mozilla. try { if (false) { //if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(acPubKey.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 cert = certgen.generate(caPrivateKey); return cert; }
From source file:org.objectweb.proactive.extensions.ssl.CertificateGenerator.java
License:Open Source License
/** * Create a random, self signed, one time certificate * * A such certificate can be used to take advantage of the SSL/TLS encryption * feature without requiring any action from the user. * * A self signed certificate, valid for the next 10 year is issued. * * @return/* ww w . ja v a 2s . c o m*/ */ public X509Certificate generateCertificate(String subjectDN, KeyPair pair) throws SslException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Auto-generated certificate, use a default principal X500Principal defaultPrincipal; defaultPrincipal = new X500Principal(subjectDN); certGen.setIssuerDN(defaultPrincipal); certGen.setSubjectDN(defaultPrincipal); // Valid for the next few years certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + (10 * 365 * 24 * 60))); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // Not certified by a CA certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // SSL requires signiture & encipherment KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment); certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage); // Allow client and server authentication Vector<DERObjectIdentifier> extendedKeyUsageV = new Vector<DERObjectIdentifier>(); extendedKeyUsageV.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsageV.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(extendedKeyUsageV)); try { X509Certificate cert = certGen.generate(pair.getPrivate(), BouncyCastleProvider.PROVIDER_NAME); try { cert.checkValidity(); cert.verify(pair.getPublic()); } catch (GeneralSecurityException e) { throw new SslException("Generated certificate is not valid", e); } return cert; } catch (GeneralSecurityException e) { throw new SslException("Failed to generate certificate", e); } }