Example usage for org.bouncycastle.asn1.x509 KeyUsage encipherOnly

List of usage examples for org.bouncycastle.asn1.x509 KeyUsage encipherOnly

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 KeyUsage encipherOnly.

Prototype

int encipherOnly

To view the source code for org.bouncycastle.asn1.x509 KeyUsage encipherOnly.

Click Source Link

Usage

From source file:de.mendelson.util.security.cert.KeystoreCertificate.java

/**
 * Returns the key usages of this cert, OID 2.5.29.15
 *//*from w  ww  .ja v a 2  s .c o m*/
public List<String> getKeyUsages() {
    List<String> keyUsages = new ArrayList<String>();
    byte[] extensionValue = this.certificate.getExtensionValue("2.5.29.15");
    if (extensionValue == null) {
        return (keyUsages);
    }
    try {
        byte[] octedBytes = ((ASN1OctetString) ASN1Primitive.fromByteArray(extensionValue)).getOctets();
        //bit encoded values for the key usage
        int val = KeyUsage.getInstance(ASN1Primitive.fromByteArray(octedBytes)).getPadBits();
        //bit 0
        if ((val & KeyUsage.digitalSignature) == KeyUsage.digitalSignature) {
            keyUsages.add("Digital signature");
        }
        //bit 1
        if ((val & KeyUsage.nonRepudiation) == KeyUsage.nonRepudiation) {
            keyUsages.add("Non repudiation");
        }
        //bit 2
        if ((val & KeyUsage.keyEncipherment) == KeyUsage.keyEncipherment) {
            keyUsages.add("Key encipherment");
        }
        //bit 3
        if ((val & KeyUsage.dataEncipherment) == KeyUsage.dataEncipherment) {
            keyUsages.add("Data encipherment");
        }
        //bit 4
        if ((val & KeyUsage.keyAgreement) == KeyUsage.keyAgreement) {
            keyUsages.add("Key agreement");
        }
        //bit 5
        if ((val & KeyUsage.keyCertSign) == KeyUsage.keyCertSign) {
            keyUsages.add("Key certificate signing");
        }
        //bit6
        if ((val & KeyUsage.cRLSign) == KeyUsage.cRLSign) {
            keyUsages.add("CRL signing");
        }
        if ((val & KeyUsage.decipherOnly) == KeyUsage.decipherOnly) {
            keyUsages.add("Decipher");
        }

        if ((val & KeyUsage.encipherOnly) == KeyUsage.encipherOnly) {
            keyUsages.add("Encipher");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return (keyUsages);
}

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

License:Open Source License

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

    /*//from  w w  w.j  a v  a2s .c om
     * KeyUsage ::= BIT STRING { digitalSignature (0), nonRepudiation (1),
     * keyEncipherment (2), dataEncipherment (3), keyAgreement (4),
     * keyCertSign (5), cRLSign (6), encipherOnly (7), decipherOnly (8) }
     */

    // @formatter:on

    DERBitString keyUsage = DERBitString.getInstance(ASN1Primitive.fromByteArray(value));

    int keyUsages = keyUsage.intValue();

    StringBuilder sb = new StringBuilder();

    if (hasKeyUsage(keyUsages, KeyUsage.digitalSignature)) {
        sb.append(res.getString("DigitalSignatureKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.nonRepudiation)) {
        sb.append(res.getString("NonRepudiationKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.keyEncipherment)) {
        sb.append(res.getString("KeyEnciphermentKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.dataEncipherment)) {
        sb.append(res.getString("DataEnciphermentKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.keyAgreement)) {
        sb.append(res.getString("KeyAgreementKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.keyCertSign)) {
        sb.append(res.getString("KeyCertSignKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.cRLSign)) {
        sb.append(res.getString("CrlSignKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.encipherOnly)) {
        sb.append(res.getString("EncipherOnlyKeyUsage"));
        sb.append(NEWLINE);
    }
    if (hasKeyUsage(keyUsages, KeyUsage.decipherOnly)) {
        sb.append(res.getString("DecipherOnlyKeyUsage"));
        sb.append(NEWLINE);
    }

    return sb.toString();
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DKeyUsage.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 keyUsage = DERBitString.getInstance(new ASN1InputStream(value).readObject());

    int keyUsageValue = keyUsage.intValue();

    jcbDigitalSignature.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.digitalSignature));
    jcbNonRepudiation.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.nonRepudiation));
    jcbKeyEncipherment.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyEncipherment));
    jcbDataEncipherment.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.dataEncipherment));
    jcbKeyAgreement.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyAgreement));
    jcbCertificateSigning.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyCertSign));
    jcbCrlSign.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.cRLSign));
    jcbEncipherOnly.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.encipherOnly));
    jcbDecipherOnly.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.decipherOnly));
}

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

License:Open Source License

private void okPressed() {
    if (!jcbDigitalSignature.isSelected() && !jcbNonRepudiation.isSelected() && !jcbKeyEncipherment.isSelected()
            && !jcbDataEncipherment.isSelected() && !jcbKeyAgreement.isSelected()
            && !jcbCertificateSigning.isSelected() && !jcbCrlSign.isSelected() && !jcbEncipherOnly.isSelected()
            && !jcbDecipherOnly.isSelected()) {
        JOptionPane.showMessageDialog(this, res.getString("DKeyUsage.ValueReq.message"), getTitle(),
                JOptionPane.WARNING_MESSAGE);
        return;//from  w  w w. ja va  2  s  .  c o  m
    }

    int keyUsageIntValue = 0;
    keyUsageIntValue |= jcbDigitalSignature.isSelected() ? KeyUsage.digitalSignature : 0;
    keyUsageIntValue |= jcbNonRepudiation.isSelected() ? KeyUsage.nonRepudiation : 0;
    keyUsageIntValue |= jcbKeyEncipherment.isSelected() ? KeyUsage.keyEncipherment : 0;
    keyUsageIntValue |= jcbDataEncipherment.isSelected() ? KeyUsage.dataEncipherment : 0;
    keyUsageIntValue |= jcbKeyAgreement.isSelected() ? KeyUsage.keyAgreement : 0;
    keyUsageIntValue |= jcbCertificateSigning.isSelected() ? KeyUsage.keyCertSign : 0;
    keyUsageIntValue |= jcbCrlSign.isSelected() ? KeyUsage.cRLSign : 0;
    keyUsageIntValue |= jcbEncipherOnly.isSelected() ? KeyUsage.encipherOnly : 0;
    keyUsageIntValue |= jcbDecipherOnly.isSelected() ? KeyUsage.decipherOnly : 0;

    KeyUsage keyUsage = new KeyUsage(keyUsageIntValue);

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

    closeDialog();
}

From source file:org.conscrypt.javax.crypto.CipherTest.java

License:Apache License

@Test
public void testCipherInitWithCertificate() throws Exception {
    // no key usage specified, everything is fine
    assertCipherInitWithKeyUsage(0, true, true, true, true);

    // common case is that encrypt/wrap is prohibited when special usage is specified
    assertCipherInitWithKeyUsage(KeyUsage.digitalSignature, false, true, false, true);
    assertCipherInitWithKeyUsage(KeyUsage.nonRepudiation, false, true, false, true);
    assertCipherInitWithKeyUsage(KeyUsage.keyAgreement, false, true, false, true);
    assertCipherInitWithKeyUsage(KeyUsage.keyCertSign, false, true, false, true);
    assertCipherInitWithKeyUsage(KeyUsage.cRLSign, false, true, false, true);

    // Note they encipherOnly/decipherOnly don't have to do with
    // ENCRYPT_MODE or DECRYPT_MODE, but restrict usage relative
    // to keyAgreement. There is not a *_MODE option that
    // corresponds to this in Cipher, the RI does not enforce
    // anything in Cipher.
    // http://code.google.com/p/android/issues/detail?id=12955
    assertCipherInitWithKeyUsage(KeyUsage.encipherOnly, false, true, false, true);
    assertCipherInitWithKeyUsage(KeyUsage.decipherOnly, false, true, false, true);
    assertCipherInitWithKeyUsage(KeyUsage.keyAgreement | KeyUsage.encipherOnly, false, true, false, true);
    assertCipherInitWithKeyUsage(KeyUsage.keyAgreement | KeyUsage.decipherOnly, false, true, false, true);

    // except when wrapping a key is specifically allowed or
    assertCipherInitWithKeyUsage(KeyUsage.keyEncipherment, false, true, true, true);
    // except when wrapping data encryption is specifically allowed
    assertCipherInitWithKeyUsage(KeyUsage.dataEncipherment, true, true, false, true);
}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * Creates a CertificateExtension. The id can be the OID or the name as
 * defined below. The values is a comma separated list of value(s)
 * <p>/*from   w  w  w  . j av a 2s  .c  om*/
 * Valid names and values:
 * <ul>
 * <li>KeyUsage
 * <ul>
 * <li>DigitalSignature
 * <li>NonRepudiation
 * <li>KeyEncipherment
 * <li>DataEncipherment
 * <li>KeyAgreement
 * <li>KeyCertSign
 * <li>CRLSign
 * <li>EncipherOnly
 * <li>DecipherOnly
 * </ul>
 * <li>ExtendedKeyUsage
 * <ul>
 * <li>AnyExtendedKeyUsage
 * <li>ServerAuth
 * <li>ClientAuth
 * <li>CodeSigning
 * <li>EmailProtection
 * <li>IPSecEndSystem
 * <li>IPSecTunnel
 * <li>IPSecUser
 * <li>OCSPSigning
 * <li>Smartcardlogon
 * </ul>
 * <li>CertificatePolicies
 * <ul>
 * <li>The policy OID(s)
 * </ul>
 * <li>SubjectAltName
 * <ul>
 * <li>email:EMAIL_ADDRESS
 * <li>dns:HOSTNAME
 * </ul>
 * </ul>
 * <p>
 * Example:
 * <pre>
 * CertificateExtension keyUsageExtension = 
 *       CertificateExtensionFactory.createCertificateExtension("KeyUsage", "DigitalSignature,KeyEncipherment");
 * CertificateExtension subjectAltNameExtension = 
 *       CertificateExtensionFactory.createCertificateExtension("SubjectAltName", "email:john.doe@example.com,dns:www.exmaple.com");
 * </pre>
 * 
 * @param id
 *            The name or the OID of the extension.
 * @param values
 *            A comma separated list of extension value(s).
 * @return The corresponding CertificateExtension or <code>null</code> if
 *         the id (name or oid) is not supported.
 */
static public CertificateExtension createCertificateExtension(String id, String values) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("id:" + id + " value(s):" + values);
    }
    if (id.equals(X509Extensions.KeyUsage.getId()) || id.equalsIgnoreCase("KeyUsage")) {
        // parse the comma separated list of key usage
        int usage = 0;
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String keyUsage = (String) st.nextElement();
            keyUsage = keyUsage.trim();

            if (keyUsage.equalsIgnoreCase("DigitalSignature")) {
                usage += KeyUsage.digitalSignature;
            } else if (keyUsage.equalsIgnoreCase("NonRepudiation")) {
                usage += KeyUsage.nonRepudiation;
            } else if (keyUsage.equalsIgnoreCase("KeyEncipherment")) {
                usage += KeyUsage.keyEncipherment;
            } else if (keyUsage.equalsIgnoreCase("DataEncipherment")) {
                usage += KeyUsage.dataEncipherment;
            } else if (keyUsage.equalsIgnoreCase("KeyAgreement")) {
                usage += KeyUsage.keyAgreement;
            } else if (keyUsage.equalsIgnoreCase("KeyCertSign")) {
                usage += KeyUsage.keyCertSign;
            } else if (keyUsage.equalsIgnoreCase("CRLSign")) {
                usage += KeyUsage.cRLSign;
            } else if (keyUsage.equalsIgnoreCase("EncipherOnly")) {
                usage += KeyUsage.encipherOnly;
            } else if (keyUsage.equalsIgnoreCase("DecipherOnly")) {
                usage += KeyUsage.decipherOnly;
            } else {
                LOG.error("Unknown KeyUsage: " + keyUsage);
            }

        }
        return createKeyUsageExtension(usage, values);
    } else if (id.equals(X509Extensions.ExtendedKeyUsage.getId()) || id.equalsIgnoreCase("ExtendedKeyUsage")) {
        // value is a comma separated list of keyPurpose
        Vector keyPurposeIds = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String keyPurpose = (String) st.nextElement();
            keyPurpose = keyPurpose.trim();
            if (keyPurpose.equalsIgnoreCase("AnyExtendedKeyUsage")) {
                keyPurposeIds.add(KeyPurposeId.anyExtendedKeyUsage);
            } else if (keyPurpose.equalsIgnoreCase("ServerAuth")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_serverAuth);
            } else if (keyPurpose.equalsIgnoreCase("ClientAuth")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_clientAuth);
            } else if (keyPurpose.equalsIgnoreCase("CodeSigning")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_codeSigning);
            } else if (keyPurpose.equalsIgnoreCase("EmailProtection")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_emailProtection);
            } else if (keyPurpose.equalsIgnoreCase("IPSecEndSystem")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecEndSystem);
            } else if (keyPurpose.equalsIgnoreCase("IPSecTunnel")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecTunnel);
            } else if (keyPurpose.equalsIgnoreCase("IPSecUser")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecUser);
            } else if (keyPurpose.equalsIgnoreCase("TimeStamping")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_timeStamping);
            } else if (keyPurpose.equalsIgnoreCase("OCSPSigning")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_OCSPSigning);
            } else if (keyPurpose.equalsIgnoreCase("Smartcardlogon")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_smartcardlogon);
            } else {
                LOG.error("Unknown ExtendedKeyUsage: " + keyPurpose);
            }
        }
        return createExtendedKeyUsageExtension(keyPurposeIds, values);
    } else if (id.equals(X509Extensions.CertificatePolicies.getId())
            || id.equalsIgnoreCase("CertificatePolicies")) {
        // values is a comma separated list of policyOIDs
        Vector policyOIDs = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String policyOID = (String) st.nextElement();
            policyOID = policyOID.trim();
            policyOIDs.add(policyOID);
        }
        return createCertificatePoliciesExtension(policyOIDs, values);
    } else if (id.equals(X509Extensions.SubjectAlternativeName.getId())
            || id.equalsIgnoreCase("SubjectAltName")) {
        // values is a comma separated list of altername names prefixed with
        // the type (email: or dns:)
        Vector typedSubjectAltNames = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String typedAltName = (String) st.nextElement();
            typedAltName = typedAltName.trim();
            typedSubjectAltNames.add(typedAltName);
        }
        return createSubjectAltNameExtension(typedSubjectAltNames, values);
    }
    LOG.error("Unsupported CertificateExtension: " + id);
    return null;
}

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

License:Open Source License

private void generateExtensionNode(TreeItem parent, X509Certificate cert, X509Extensions extensions,
        String oid) {/*from ww  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.texai.x509.X509Utils.java

License:Open Source License

/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication
 * and for message signing.//from ww  w.j  av a2s  .  co  m
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate
 * @param uid the subject UID
 * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime
 * @return a signed end-use certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid,
        final String domainComponent)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";
    assert uid != null : "uid must not be null";

    final String x500PrincipalString;
    // provide items to X500Principal in reverse order
    if (domainComponent == null || domainComponent.isEmpty()) {
        x500PrincipalString = "UID=" + uid + ", CN=texai.org";
    } else {
        x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org";
    }
    final X500Principal x500Principal = new X500Principal(x500PrincipalString);

    LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName());

    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
            new X500Name(StringUtils
                    .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            new X500Name(x500Principal.getName()), // subject,
            new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(false)); // is not a CA certificate

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the digitalSignature usage indicates that the subject public key may be used with a digital signature
            // mechanism to support security services other than non-repudiation, certificate signing, or revocation
            // information signing
            KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures
                                        // used to provide a non-repudiation service which protects against the signing entity falsely denying some
                                        // action, excluding certificate or CRL signing
                    KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the
                                              // exchange of efficient symmetric keys in SSL
                    KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data,
                                               // other than cryptographic keys
                    KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a
                                                // Diffie-Hellman key is to be used for key management
                    KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
                                            // certificates
                    KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                           // information
                    KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL
                                       // client authorization
                    KeyUsage.encipherOnly);
    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }
    assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage";

    return x509Certificate;
}

From source file:org.texai.x509.X509UtilsTest.java

License:Open Source License

/**
 * Test of hasKeyUsage method of class X509Utils.
 */// w w w.  java2s  .  co  m
@Test
public void testHasKeyUsage() {
    LOGGER.info("hasKeyUsage");

    X509Certificate rootX509Certificate = X509Utils.getRootX509Certificate();
    LOGGER.info("root certificate:\n" + rootX509Certificate);
    LOGGER.info("root certificate class: " + rootX509Certificate.getClass().getName());
    LOGGER.info("key usage bits: " + StringUtils.booleanArrayToBitString(rootX509Certificate.getKeyUsage()));
    assertFalse(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.digitalSignature));
    assertFalse(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.nonRepudiation));
    assertFalse(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.keyEncipherment));
    assertFalse(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.dataEncipherment));
    assertFalse(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.keyAgreement));
    assertTrue(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.keyCertSign));
    assertTrue(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.cRLSign));
    assertFalse(X509Utils.hasKeyUsage(rootX509Certificate, KeyUsage.encipherOnly));

    if (!X509Utils.isTrustedDevelopmentSystem()) {
        return;
    }
    try {
        KeyPair keyPair = X509Utils.generateRSAKeyPair3072();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey certificateAuthorityPrivateKey = X509Utils.getRootPrivateKey();
        X509Certificate intermediateX509Certificate = X509Utils.generateIntermediateX509Certificate(publicKey,
                certificateAuthorityPrivateKey, rootX509Certificate, 0);

        LOGGER.info("generated intermediate certificate:\n" + intermediateX509Certificate);
        assertFalse(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.digitalSignature));
        assertFalse(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.nonRepudiation));
        assertFalse(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.keyEncipherment));
        assertFalse(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.dataEncipherment));
        assertFalse(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.keyAgreement));
        assertTrue(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.keyCertSign));
        assertTrue(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.cRLSign));
        assertFalse(X509Utils.hasKeyUsage(intermediateX509Certificate, KeyUsage.encipherOnly));

        keyPair = X509Utils.generateRSAKeyPair2048();
        publicKey = keyPair.getPublic();
        certificateAuthorityPrivateKey = X509Utils.getRootPrivateKey();
        LOGGER.info(
                "root certificate (" + rootX509Certificate.getClass().getName() + "):\n" + rootX509Certificate);
        X509Certificate x509Certificate = X509Utils.generateX509Certificate(publicKey,
                certificateAuthorityPrivateKey, rootX509Certificate, null);

        LOGGER.info("generated certificate:\n" + x509Certificate);
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.digitalSignature));
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.nonRepudiation));
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.keyEncipherment));
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.dataEncipherment));
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.keyAgreement));
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.keyCertSign));
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.cRLSign));
        assertTrue(X509Utils.hasKeyUsage(x509Certificate, KeyUsage.encipherOnly));
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | CertificateParsingException | CertificateEncodingException | SignatureException
            | InvalidKeyException | IOException ex) {
        fail(ex.getMessage());
    }
}

From source file:test.unit.be.fedict.trust.constraints.KeyUsageCertificateConstraintTest.java

License:Open Source License

@Test
public void testFailingOnUnexpectedKeyUsageEncypherOnly() throws Exception {
    // setup/*from  w w  w .  j av a 2  s.c  om*/
    KeyPair keyPair = PKITestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    KeyUsage keyUsage = new KeyUsage(KeyUsage.encipherOnly);
    X509Certificate certificate = PKITestUtils.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
            notAfter, true, 0, null, keyUsage);

    this.testedInstance.setEncipherOnlyFilter(false);

    // operate
    try {
        this.testedInstance.check(certificate);
        fail();
    } catch (TrustLinkerResultException e) {
        assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION, e.getReason());
    }
}