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

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

Introduction

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

Prototype

int keyAgreement

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

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. j  a v  a2  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  ww .  j  a v a  2 s .com*/
     * 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;// w w w .j  a va2 s.c  om
    }

    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.apache.nifi.registry.security.util.CertificateUtils.java

License:Apache License

/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 *//*from   w  ww . j  a va  2  s.c  o m*/
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn,
        String signingAlgorithm, int certificateDurationDays) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)),
                getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);

        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                        | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign
                        | KeyUsage.keyCertSign));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
                new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));

        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

License:Apache License

/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 *//*from   w  w  w  . j ava 2  s .  c  o m*/
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions,
        X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())),
                getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                        | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
                new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));

        // (3) subjectAlternativeName
        if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false,
                    extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }

        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidatorTest.java

License:Apache License

/**
 * Generates a signed certificate with a specific keypair.
 *
 * @param dn      the DN/*from w w  w  .  j  av a 2  s.c  o  m*/
 * @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateCertificate(String dn, KeyPair keyPair)
        throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException,
        SignatureException, InvalidKeyException, OperatorCreationException {
    PrivateKey privateKey = keyPair.getPrivate();
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER)
            .build(privateKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(dn),
            BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn),
            subPubKeyInfo);

    // Set certificate extensions
    // (1) digitalSignature extension
    certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature
            | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement));

    // (2) extendedKeyUsage extension
    Vector<KeyPurposeId> ekUsages = new Vector<>();
    ekUsages.add(KeyPurposeId.id_kp_clientAuth);
    ekUsages.add(KeyPurposeId.id_kp_serverAuth);
    certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages));

    // Sign the certificate
    X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certificateHolder);
}

From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCertificateGenerator.java

License:Open Source License

/**
 * Basic common path.//w w w . ja v  a2s. c  om
 * @param subjectDN the distinguished name of the subject.
 * @param subjectPublicKey the public key of the subject.
 * @param issuerDN the distinguished name of the issuer.
 * @param duration the validity duration of the certificate.
 * @param isCA
 * @param allUsage if isCA is true, add "regular" KeyUsage flags, for dual-use cert
 */
public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey, X500Principal issuerDN,
        long duration, boolean isCA, Integer chainLength, boolean allUsage) {

    _generator.setSubjectDN(new X509Name(subjectDN));
    _generator.setIssuerDN(issuerDN);
    _generator.setSerialNumber(new BigInteger(64, cachedRandom));
    _generator.setPublicKey(subjectPublicKey);

    Date startTime = new Date();
    Date stopTime = new Date(startTime.getTime() + duration);
    _generator.setNotBefore(startTime);
    _generator.setNotAfter(stopTime);

    // CA key usage
    final int caKeyUsage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyCertSign
            | KeyUsage.cRLSign;
    // Non-CA key usage
    final int nonCAKeyUsage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.keyAgreement;

    int ourUsage;
    if (isCA) {
        if (!allUsage) {
            ourUsage = caKeyUsage;
        } else {
            ourUsage = caKeyUsage | nonCAKeyUsage;
        }
    } else {
        ourUsage = nonCAKeyUsage;
    }
    _generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(ourUsage));

    BasicConstraints bc = ((isCA == false) || (null == chainLength)) ? new BasicConstraints(isCA)
            : new BasicConstraints(chainLength.intValue());
    _generator.addExtension(X509Extensions.BasicConstraints, true, bc);

    SubjectKeyIdentifier ski = new SubjectKeyIdentifier(CryptoUtil.generateKeyID(subjectPublicKey));
    _generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
}

From source file:org.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.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java

License:Open Source License

protected void addKeyUsage(X509v3CertificateBuilder certificateBuilder) throws CertIOException {
    certificateBuilder.addExtension(Extension.keyUsage, false,
            new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature | KeyUsage.keyAgreement
                    | KeyUsage.keyCertSign | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation));
}