Example usage for org.bouncycastle.asn1.misc NetscapeCertType smime

List of usage examples for org.bouncycastle.asn1.misc NetscapeCertType smime

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.misc NetscapeCertType smime.

Prototype

int smime

To view the source code for org.bouncycastle.asn1.misc NetscapeCertType smime.

Click Source Link

Usage

From source file:net.sf.keystore_explorer.crypto.x509.X509Ext.java

License:Open Source License

private String getNetscapeCertificateTypeStringValue(byte[] value) throws IOException {
    // @formatter:off

    /*/*from   ww w. ja  v  a 2 s . c  o m*/
     * NetscapeCertType ::= BIT STRING { sslClient (0), sslServer (1), smime
     * (2), objectSigning (3), reserved (4), sslCA (5), smimeCA (6),
     * objectSigningCA (7) }
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    @SuppressWarnings("resource") // we have a ByteArrayInputStream here which does not need to be closed
    DERBitString netscapeCertType = DERBitString.getInstance(new ASN1InputStream(value).readObject());

    int netscapeCertTypes = netscapeCertType.intValue();

    if (isCertType(netscapeCertTypes, NetscapeCertType.sslClient)) {
        sb.append(res.getString("SslClientNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    if (isCertType(netscapeCertTypes, NetscapeCertType.sslServer)) {
        sb.append(res.getString("SslServerNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    if (isCertType(netscapeCertTypes, NetscapeCertType.smime)) {
        sb.append(res.getString("SmimeNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    if (isCertType(netscapeCertTypes, NetscapeCertType.objectSigning)) {
        sb.append(res.getString("ObjectSigningNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    if (isCertType(netscapeCertTypes, NetscapeCertType.reserved)) {
        sb.append(res.getString("ReservedNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    if (isCertType(netscapeCertTypes, NetscapeCertType.sslCA)) {
        sb.append(res.getString("SslCaNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    if (isCertType(netscapeCertTypes, NetscapeCertType.smimeCA)) {
        sb.append(res.getString("SmimeCaNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    if (isCertType(netscapeCertTypes, NetscapeCertType.objectSigningCA)) {
        sb.append(res.getString("ObjectSigningCaNetscapeCertificateType"));
        sb.append(NEWLINE);
    }

    return sb.toString();
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DNetscapeCertificateType.java

License:Open Source License

private void prepopulateWithValue(byte[] value) throws IOException {
    @SuppressWarnings("resource") // we have a ByteArrayInputStream here which does not need to be closed
    DERBitString netscapeCertType = DERBitString.getInstance(new ASN1InputStream(value).readObject());

    int netscapeCertTypes = netscapeCertType.intValue();

    jcbSslClient.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.sslClient));
    jcbSslServer.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.sslServer));
    jcbSmime.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.smime));
    jcbObjectSigning.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.objectSigning));
    jcbReserved.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.reserved));
    jcbSslCa.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.sslCA));
    jcbSmimeCa.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.smimeCA));
    jcbObjectSigningCa.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.objectSigningCA));
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DNetscapeCertificateType.java

License:Open Source License

private void okPressed() {
    if (!jcbSslClient.isSelected() && !jcbSslServer.isSelected() && !jcbSmime.isSelected()
            && !jcbObjectSigning.isSelected() && !jcbReserved.isSelected() && !jcbSslCa.isSelected()
            && !jcbSmimeCa.isSelected() && !jcbObjectSigningCa.isSelected()) {
        JOptionPane.showMessageDialog(this, res.getString("DNetscapeCertificateType.ValueReq.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;/*from w  w  w.j ava  2 s.  c o m*/
    }

    int netscapeCertTypeIntValue = 0;
    netscapeCertTypeIntValue |= jcbSslClient.isSelected() ? NetscapeCertType.sslClient : 0;
    netscapeCertTypeIntValue |= jcbSslServer.isSelected() ? NetscapeCertType.sslServer : 0;
    netscapeCertTypeIntValue |= jcbSmime.isSelected() ? NetscapeCertType.smime : 0;
    netscapeCertTypeIntValue |= jcbObjectSigning.isSelected() ? NetscapeCertType.objectSigning : 0;
    netscapeCertTypeIntValue |= jcbReserved.isSelected() ? NetscapeCertType.reserved : 0;
    netscapeCertTypeIntValue |= jcbSslCa.isSelected() ? NetscapeCertType.sslCA : 0;
    netscapeCertTypeIntValue |= jcbSmimeCa.isSelected() ? NetscapeCertType.smimeCA : 0;
    netscapeCertTypeIntValue |= jcbObjectSigningCa.isSelected() ? NetscapeCertType.objectSigningCA : 0;

    NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeIntValue);

    try {
        value = netscapeCertType.getEncoded(ASN1Encoding.DER);
    } catch (IOException ex) {
        DError dError = new DError(this, ex);
        dError.setLocationRelativeTo(this);
        dError.setVisible(true);
        return;
    }

    closeDialog();
}

From source file:net.sf.taverna.t2.activities.wsdl.servicedescriptions.ConfirmTrustedCertificateDialog.java

License:Open Source License

/**
 * Gets the intended certificate uses, i.e. Netscape Certificate Type
 * extension (2.16.840.1.113730.1.1) value as a string
 * /*from   ww  w.  j a va 2 s. co m*/
 * @param value
 *            Extension value as a DER-encoded OCTET string
 * @return Extension value as a string
 */
private String getIntendedUses(byte[] value) {

    // Netscape Certificate Types (2.16.840.1.113730.1.1)
    int[] INTENDED_USES = new int[] { NetscapeCertType.sslClient, NetscapeCertType.sslServer,
            NetscapeCertType.smime, NetscapeCertType.objectSigning, NetscapeCertType.reserved,
            NetscapeCertType.sslCA, NetscapeCertType.smimeCA, NetscapeCertType.objectSigningCA, };

    // Netscape Certificate Type strings (2.16.840.1.113730.1.1)
    HashMap<String, String> INTENDED_USES_STRINGS = new HashMap<String, String>();
    INTENDED_USES_STRINGS.put("128", "SSL Client");
    INTENDED_USES_STRINGS.put("64", "SSL Server");
    INTENDED_USES_STRINGS.put("32", "S/MIME");
    INTENDED_USES_STRINGS.put("16", "Object Signing");
    INTENDED_USES_STRINGS.put("8", "Reserved");
    INTENDED_USES_STRINGS.put("4", "SSL CA");
    INTENDED_USES_STRINGS.put("2", "S/MIME CA");
    INTENDED_USES_STRINGS.put("1", "Object Signing CA");

    // Get octet string from extension value
    ASN1OctetString fromByteArray = new DEROctetString(value);
    byte[] octets = fromByteArray.getOctets();
    DERBitString fromByteArray2 = new DERBitString(octets);
    int val = new NetscapeCertType(fromByteArray2).intValue();
    StringBuffer strBuff = new StringBuffer();
    for (int i = 0, len = INTENDED_USES.length; i < len; i++) {
        int use = INTENDED_USES[i];
        if ((val & use) == use) {
            strBuff.append(INTENDED_USES_STRINGS.get(String.valueOf(use)) + ", \n");
        }
    }
    // remove the last ", \n" from the end of the buffer
    String str = strBuff.toString();
    str = str.substring(0, str.length() - 3);
    return str;
}

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 ww  w . j a  va 2  s  .  co  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.kontalk.certgen.X509Bridge.java

License:Open Source License

/**
 * Creates a self-signed certificate from a public and private key. The
 * (critical) key-usage extension is set up with: digital signature,
 * non-repudiation, key-encipherment, key-agreement and certificate-signing.
 * The (non-critical) Netscape extension is set up with: SSL client and
 * S/MIME. A URI subjectAltName may also be set up.
 *
 * @param pubKey/*from  ww w . j ava 2  s  . c  om*/
 *            public key
 * @param privKey
 *            private key
 * @param subject
 *            subject (and issuer) DN for this certificate, RFC 2253 format
 *            preferred.
 * @param startDate
 *            date from which the certificate will be valid
 *            (defaults to current date and time if null)
 * @param endDate
 *            date until which the certificate will be valid
 *            (defaults to start date and time if null)
 * @param subjectAltName
 *            URI to be placed in subjectAltName
 * @return self-signed certificate
 */
private static X509Certificate createCertificate(PublicKey pubKey, PrivateKey privKey, X500Name subject,
        Date startDate, Date endDate, String subjectAltName, byte[] publicKeyData)
        throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException,
        CertificateException, NoSuchProviderException, IOException, OperatorCreationException {

    /*
     * Sets the signature algorithm.
     */
    BcContentSignerBuilder signerBuilder;
    String pubKeyAlgorithm = pubKey.getAlgorithm();
    if (pubKeyAlgorithm.equals("DSA")) {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithDSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        signerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId);
    } else if (pubKeyAlgorithm.equals("RSA")) {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
                .find("SHA1WithRSAEncryption");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
    }
    /*
    else if (pubKeyAlgorithm.equals("ECDSA")) {
    // TODO is this even legal?
    certGenerator.setSignatureAlgorithm("SHA1WithECDSA");
    }
    */
    else {
        throw new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm);
    }

    AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(privKey.getEncoded());
    ContentSigner signer = signerBuilder.build(keyp);

    /*
     * Sets up the validity dates.
     */
    if (startDate == null) {
        startDate = new Date(System.currentTimeMillis());
    }
    if (endDate == null) {
        endDate = startDate;
    }

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
            /*
             * Sets up the subject distinguished name.
             * Since it's a self-signed certificate, issuer and subject are the
             * same.
             */
            subject,
            /*
             * The serial-number of this certificate is 1. It makes sense
             * because it's self-signed.
             */
            BigInteger.ONE, startDate, endDate, subject,
            /*
             * Sets the public-key to embed in this certificate.
             */
            SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pubKey.getEncoded()).readObject()));

    /*
     * Adds the Basic Constraint (CA: true) extension.
     */
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

    /*
     * Adds the Key Usage extension.
     */
    certBuilder.addExtension(Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment
                    | KeyUsage.keyAgreement | KeyUsage.keyCertSign));

    /*
     * Adds the Netscape certificate type extension.
     */
    certBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime));

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    /*
     * Adds the subject key identifier extension.
     */
    SubjectKeyIdentifier subjectKeyIdentifier = extUtils.createSubjectKeyIdentifier(pubKey);
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier);

    /*
     * Adds the authority key identifier extension.
     */
    AuthorityKeyIdentifier authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(pubKey);
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);

    /*
     * Adds the subject alternative-name extension.
     */
    if (subjectAltName != null) {
        GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, subjectAltName));
        certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    }

    /*
     * Adds the PGP public key block extension.
     */
    SubjectPGPPublicKeyInfo publicKeyExtension = new SubjectPGPPublicKeyInfo(publicKeyData);
    certBuilder.addExtension(SubjectPGPPublicKeyInfo.OID, false, publicKeyExtension);

    /*
     * Creates and sign this certificate with the private key
     * corresponding to the public key of the certificate
     * (hence the name "self-signed certificate").
     */
    X509CertificateHolder holder = certBuilder.build(signer);

    /*
     * Checks that this certificate has indeed been correctly signed.
     */
    X509Certificate cert = new JcaX509CertificateConverter().getCertificate(holder);
    cert.verify(pubKey);

    return cert;
}

From source file:org.mailster.gui.dialogs.CertificateDialog.java

License:Open Source License

private void generateExtensionNode(TreeItem parent, X509Certificate cert, X509Extensions extensions,
        String oid) {/* www.j  ava2  s  .c  om*/
    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.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

/**
 * Creates a lower level certificate, adding authority key-id and subject
  * key-id extensions to the resulting certificate (version 3).
 * /* w  ww  .  j  a  v a  2 s .c o  m*/
 * @param pubKey
 * @param serialNumber
 * @param name
 * @param notBefore
 * @param notAfter
 * @param signatureAlgorithm
 * @param issuerPrivKey
 * @param issuerCert
 * @param friendlyName
 * @return X509Certificate
 * @throws Exception
 */
public static X509Certificate createCert(PublicKey pubKey, BigInteger serialNumber, String name, Date notBefore,
        Date notAfter, String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert,
        String friendlyName) throws Exception {
    byte[] nameBytes = new X500Principal(name).getEncoded();

    //
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(serialNumber);
    v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setNotBefore(notBefore);
    v3CertGen.setNotAfter(notAfter);
    v3CertGen.setSubjectDN(new X509Principal(nameBytes));
    v3CertGen.setPublicKey(pubKey);
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    //
    // add the extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(pubKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerCert.getPublicKey(),
                    new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslServer | NetscapeCertType.sslClient
                    | NetscapeCertType.objectSigning | NetscapeCertType.smime));

    X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey);

    if (friendlyName != null) {
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(pubKey));
    }

    return cert;
}

From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

/**
 * Generate a certificate which is a "copy" of another certificate, but 
* resigned by a different issuer./*w w w .java2  s .  c  o  m*/
 *
 * @param initialCert
 * @param serialNumber
 * @param signatureAlgorithm
 * @param issuerPrivKey
 * @param issuerCert
 * @return X509Certificate
 */
public static X509Certificate resignCert(X509Certificate initialCert, BigInteger serialNumber,
        String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert) throws Exception {
    //
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(serialNumber);
    v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setNotBefore(initialCert.getNotBefore());
    v3CertGen.setNotAfter(initialCert.getNotAfter());
    v3CertGen.setSubjectDN(new X509Principal(initialCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setPublicKey(initialCert.getPublicKey());
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    //
    // add the extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(initialCert.getPublicKey()));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerCert.getPublicKey(),
                    new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.sslClient | NetscapeCertType.objectSigning | NetscapeCertType.smime));

    X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey);

    return cert;
}

From source file:org.xwiki.crypto.x509.internal.X509Keymaker.java

License:Open Source License

/**
 * Create a new X509 client certificate.
 *
 * @param forCert the public key which will be embedded in the certificate, whoever has the matching private key
 *                "owns" the certificate.
 * @param toSignWith the private key in this pair will be used to sign the certificate.
 * @param daysOfValidity number of days the cert should be valid for.
 * @param nonRepudiable this should only be true if the private key is not stored on the server.
 * @param webId the URI to put as the alternative name (for FOAFSSL webId compatibility)
 * @param userName a String representation of the name of the user getting the certificate.
 * @return a new X509 certificate./*w w  w  . j  av  a  2 s  .  co  m*/
 * @throws GeneralSecurityException if something goes wrong.
 */
public synchronized X509Certificate makeClientCertificate(final PublicKey forCert, final KeyPair toSignWith,
        final int daysOfValidity, final boolean nonRepudiable, final String webId, final String userName)
        throws GeneralSecurityException {
    try {
        // the UID (same for issuer since this certificate confers no authority)
        final X509Name dName = new X509Name("UID=" + userName);

        this.prepareGenericCertificate(forCert, daysOfValidity, dName, dName);

        // Not a CA
        certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

        // Client cert
        certGenerator.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
                new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime));

        // Key Usage extension.
        int keyUsage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement;
        if (nonRepudiable) {
            keyUsage |= KeyUsage.nonRepudiation;
        }
        certGenerator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));

        // Set the authority key identifier to be the CA key which we are using.
        certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(toSignWith.getPublic()));

        // FOAFSSL compatibility.
        final GeneralNames subjectAltNames = new GeneralNames(
                new GeneralName(GeneralName.uniformResourceIdentifier, webId));
        certGenerator.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames);

        return this.generate(toSignWith);

    } finally {
        // Clean up after ourselves so that it is more difficult to try to extract private keys from the heap.
        this.certGenerator.reset();
    }
}