Example usage for org.bouncycastle.asn1 DERIA5String DERIA5String

List of usage examples for org.bouncycastle.asn1 DERIA5String DERIA5String

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DERIA5String DERIA5String.

Prototype

public DERIA5String(String string) 

Source Link

Document

Basic constructor - without validation.

Usage

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

License:Open Source License

private void okPressed() {
    String netscapeCaPolicyUrlStr = jtfNetscapeCaPolicyUrl.getText().trim();

    if (netscapeCaPolicyUrlStr.length() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DNetscapeCaPolicyUrl.ValueReq.message"), getTitle(),
                JOptionPane.WARNING_MESSAGE);
        return;/* w w w  .  jav a2  s  . c om*/
    }

    DERIA5String netscapeCaPolicyUrl = new DERIA5String(netscapeCaPolicyUrlStr);

    try {
        value = netscapeCaPolicyUrl.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.keystore_explorer.gui.dialogs.extensions.DNetscapeCaRevocationUrl.java

License:Open Source License

private void okPressed() {
    String netscapeCaRevocationUrlStr = jtfNetscapeCaRevocationUrl.getText().trim();

    if (netscapeCaRevocationUrlStr.length() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DNetscapeCaRevocationUrl.ValueReq.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;//  w w  w. ja v a  2 s. c  om
    }

    DERIA5String netscapeCaRevocationUrl = new DERIA5String(netscapeCaRevocationUrlStr);

    try {
        value = netscapeCaRevocationUrl.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.keystore_explorer.gui.dialogs.extensions.DNetscapeCertificateRenewalUrl.java

License:Open Source License

private void okPressed() {
    String netscapeCertificateRenewalUrlStr = jtfNetscapeCertificateRenewalUrl.getText().trim();

    if (netscapeCertificateRenewalUrlStr.length() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DNetscapeCertificateRenewalUrl.ValueReq.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;/*  w  ww  .  j  a  va2s  .com*/
    }

    DERIA5String netscapeCertificateRenewalUrl = new DERIA5String(netscapeCertificateRenewalUrlStr);

    try {
        value = netscapeCertificateRenewalUrl.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.keystore_explorer.gui.dialogs.extensions.DNetscapeComment.java

License:Open Source License

private void okPressed() {
    String netscapeCommentStr = jtaNetscapeComment.getText().trim();

    if (netscapeCommentStr.length() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DNetscapeComment.ValueReq.message"), getTitle(),
                JOptionPane.WARNING_MESSAGE);
        return;/*  www  .  j a  v  a  2 s  .  c  o  m*/
    }

    DERIA5String netscapeComment = new DERIA5String(netscapeCommentStr);

    try {
        value = netscapeComment.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.keystore_explorer.gui.dialogs.extensions.DNetscapeRevocationUrl.java

License:Open Source License

private void okPressed() {
    String netscapeRevocationUrlStr = jtfNetscapeRevocationUrl.getText().trim();

    if (netscapeRevocationUrlStr.length() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DNetscapeRevocationUrl.ValueReq.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;//  w w  w.j  a  v  a2s. com
    }

    DERIA5String netscapeRevocationUrl = new DERIA5String(netscapeRevocationUrlStr);

    try {
        value = netscapeRevocationUrl.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.keystore_explorer.gui.dialogs.extensions.DNetscapeSslServerName.java

License:Open Source License

private void okPressed() {
    String netscapeSslServerNameStr = jtfNetscapeSslServerName.getText().trim();

    if (netscapeSslServerNameStr.length() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DNetscapeSslServerName.ValueReq.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;//from  w w  w . j  ava  2s.  co m
    }

    DERIA5String netscapeSslServerName = new DERIA5String(netscapeSslServerNameStr);

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

    closeDialog();
}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

private DERSequence DNtoDERSequence(String thisDN) throws Exception {
    DERSequence this_sequence = null;

    try {//  ww w.  j av a2  s. c  om
        DEREncodableVector this_overall_vector = new ASN1EncodableVector();

        String[] parts = thisDN.split("/");

        for (int p = 1; p < parts.length; p++) {

            int equals_position = parts[p].indexOf("=");

            String oid_string = parts[p].substring(0, equals_position);
            String value_string = parts[p].substring(equals_position + 1);
            String oid = Translate_OID.getOIDFromString(oid_string);
            if (oid.equals(oid_string)) {
                throw new Exception("unrecognised OID string :: " + oid);
            }

            DEREncodableVector this_vector = new ASN1EncodableVector();
            DERObjectIdentifier this_oid = new DERObjectIdentifier(oid);

            this_vector.add(this_oid);

            if (oid_string.equals("E")) {
                DERIA5String this_string = new DERIA5String(value_string);
                this_vector.add(this_string);
            } else {
                DERPrintableString this_string = new DERPrintableString(value_string);
                this_vector.add(this_string);
            }

            DERSet this_single_object_set = new DERSet(new DERSequence(this_vector));

            this_overall_vector.add(this_single_object_set);

        }

        this_sequence = new DERSequence(this_overall_vector);

    } catch (Exception e) {
        throw e;
    }

    return this_sequence;

}

From source file:org.apache.poi.poifs.crypt.PkiTestUtils.java

License:Apache License

static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore,
        Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag,
        int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage)
        throws IOException, OperatorCreationException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X500Name issuerName;/*  w  w w  . j  av  a2 s. c om*/
    if (issuerCertificate != null) {
        issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer();
    } else {
        issuerName = new X500Name(subjectDn);
    }

    RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey;
    RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(),
            rsaPubKey.getPublicExponent());

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec);

    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
            .get(CertificateID.HASH_SHA1);

    X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName,
            new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn),
            subjectPublicKeyInfo);

    X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc);
    SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
    AuthorityKeyIdentifier autKeyId = (issuerCertificate != null)
            ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded()))
            : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo);

    certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId);
    certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId);

    if (caFlag) {
        BasicConstraints bc;

        if (-1 == pathLength) {
            bc = new BasicConstraints(true);
        } else {
            bc = new BasicConstraints(pathLength);
        }
        certificateGenerator.addExtension(Extension.basicConstraints, false, bc);
    }

    if (null != crlUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        DERIA5String crlUriDer = new DERIA5String(crlUri);
        GeneralName gn = new GeneralName(uri, crlUriDer);

        DERSequence gnDer = new DERSequence(gn);
        GeneralNames gns = GeneralNames.getInstance(gnDer);

        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        DERSequence distpDer = new DERSequence(distp);
        certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer);
    }

    if (null != ocspUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        GeneralName ocspName = new GeneralName(uri, ocspUri);

        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);

        certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage);
    }

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
    signerBuilder.setProvider("BC");

    X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey));

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    //        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    //        certificate = (X509Certificate) certificateFactory
    //                .generateCertificate(new ByteArrayInputStream(certificate
    //                        .getEncoded()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}

From source file:org.apache.zookeeper.common.X509TestHelpers.java

License:Apache License

/**
 * Returns subject alternative names for "localhost".
 * @return the subject alternative names for "localhost".
 *///  w  w w  . j a va2s.c om
private static GeneralNames getLocalhostSubjectAltNames() throws UnknownHostException {
    InetAddress[] localAddresses = InetAddress.getAllByName("localhost");
    GeneralName[] generalNames = new GeneralName[localAddresses.length + 1];
    for (int i = 0; i < localAddresses.length; i++) {
        generalNames[i] = new GeneralName(GeneralName.iPAddress,
                new DEROctetString(localAddresses[i].getAddress()));
    }
    generalNames[generalNames.length - 1] = new GeneralName(GeneralName.dNSName, new DERIA5String("localhost"));
    return new GeneralNames(generalNames);
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

/**
 * Generate a CRL or a deltaCRL//from   w  ww  . ja va  2 s.c om
 * 
 * @param certs
 *            list of revoked certificates
 * @param crlnumber
 *            CRLNumber for this CRL
 * @param isDeltaCRL
 *            true if we should generate a DeltaCRL
 * @param basecrlnumber
 *            caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile
 *            certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CryptoTokenOfflineException
 * @throws IllegalCryptoTokenException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod,
        int crlnumber, boolean isDeltaCRL, int basecrlnumber)
        throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }

    // Make DNs
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    final X500Name issuer;
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        final X500NameStyle nameStyle;
        if (getUsePrintableStringSubjectDN()) {
            nameStyle = PrintableStringNameStyle.INSTANCE;
        } else {
            nameStyle = CeSecoreNameStyle.INSTANCE;
        }
        issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    } else {
        issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
    }
    final Date thisUpdate = new Date();
    final Date nextUpdate = new Date();
    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    if (certs != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
        final Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            final RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
        if (log.isDebugEnabled()) {
            log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null);
        if (caSkid != null) {
            // Use subject key id from CA certificate
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid);
            crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
        } else {
            // Generate from SHA1 of public key
            ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken
                    .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN))
                    .getEncoded()));
            try {
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) asn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
            } finally {
                asn1InputStream.close();
            }
        }
    }

    // Authority Information Access  
    final ASN1EncodableVector accessList = new ASN1EncodableVector();
    if (getAuthorityInformationAccess() != null) {
        for (String url : getAuthorityInformationAccess()) {
            if (StringUtils.isNotEmpty(url)) {
                GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier,
                        new DERIA5String(url));
                accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation));
            }
        }
    }
    if (accessList.size() > 0) {
        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(new DERSequence(accessList));
        // "This CRL extension MUST NOT be marked critical." according to rfc4325
        crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(),
                    idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(Extension.freshestCRL, false, ext);
            }

        }
    }

    final X509CRLHolder crl;
    if (log.isDebugEnabled()) {
        log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN);
    try {
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg)
                .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480);
        crl = crlgen.build(signer);
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    final PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA certificate.");
        }
    } else {
        verifyKey = cryptoToken.getPublicKey(alias);
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA token.");
        }
    }
    try {
        final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey);
        if (!crl.isSignatureValid(verifier)) {
            throw new SignatureException("Error verifying CRL to be returned.");
        }
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    } catch (CertException e) {
        throw new SignatureException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    return crl;
}