Example usage for org.bouncycastle.asn1 ASN1EncodableVector add

List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector add

Introduction

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

Prototype

public void add(ASN1Encodable element) 

Source Link

Usage

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

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vec = new ASN1EncodableVector();
    Iterator<AccessDescription> it = accessDescriptions.iterator();
    while (it.hasNext()) {
        vec.add(it.next().toASN1Primitive());
    }//from   ww  w.  j  a  v a 2  s .  c o m

    return new DERSequence(vec);
}

From source file:net.sf.keystore_explorer.gui.crypto.generalname.DGeneralNameChooser.java

License:Open Source License

private void okPressed() {
    try {/*from w w  w  .  j av  a 2 s  .  co m*/
        GeneralName newGeneralName = null;

        if (jrbDirectoryName.isSelected()) {
            X500Name directoryName = jdnDirectoryName.getDistinguishedName();

            if (directoryName == null) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.DirectoryNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.directoryName, directoryName);
        } else if (jrbDnsName.isSelected()) {
            String dnsName = jtfDnsName.getText().trim();

            if (dnsName.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.DnsNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName));
        } else if (jrbIpAddress.isSelected()) {

            String ipAddress = jtfIpAddress.getText().trim();

            if (ipAddress.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.IpAddressValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!IPAddress.isValid(ipAddress)) {
                JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.NotAValidIP.message"),
                        getTitle(), JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.iPAddress, ipAddress);
        } else if (jrbRegisteredId.isSelected()) {
            ASN1ObjectIdentifier registeredId = joiRegisteredId.getObjectId();

            if (registeredId == null) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.RegisteredIdValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.registeredID, registeredId);
        } else if (jrbRfc822Name.isSelected()) {
            String rfc822Name = jtfRfc822Name.getText().trim();

            if (rfc822Name.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.Rfc822NameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.rfc822Name, new DERIA5String(rfc822Name));
        } else if (jrbUniformResourceIdentifier.isSelected()) {
            String uniformResourceIdentifier = jtfUniformResourceIdentifier.getText().trim();

            if (uniformResourceIdentifier.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.UniformResourceIdentifierValueReq.message"),
                        getTitle(), JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(uniformResourceIdentifier));
        } else if (jrbPrincipalName.isSelected()) {
            String upnString = jtfPrincipalName.getText().trim();

            if (upnString.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.PrincipalNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            ASN1EncodableVector asn1Vector = new ASN1EncodableVector();
            asn1Vector.add(new ASN1ObjectIdentifier(GeneralNameUtil.UPN_OID));
            asn1Vector.add(new DERTaggedObject(true, 0, new DERUTF8String(upnString)));

            newGeneralName = new GeneralName(GeneralName.otherName, new DERSequence(asn1Vector));
        }

        generalName = newGeneralName;
    } catch (Exception ex) {
        DError dError = new DError(this, ex);
        dError.setLocationRelativeTo(this);
        dError.setVisible(true);
        return;
    }

    closeDialog();
}

From source file:net.sf.keystore_explorer.gui.crypto.policyinformation.DPolicyInformationChooser.java

License:Open Source License

private void okPressed() {
    ASN1ObjectIdentifier policyIdentifer = joiPolicyIdentifier.getObjectId();

    if (policyIdentifer == null) {
        JOptionPane.showMessageDialog(this,
                res.getString("DPolicyInformationChooser.PolicyIdentifierValueReq.message"), getTitle(),
                JOptionPane.WARNING_MESSAGE);
        return;//from  w w w  . j  a  v a2  s  . c o  m
    }

    List<PolicyQualifierInfo> policyQualifierInfo = jpqPolicyQualifiers.getPolicyQualifierInfo();

    if (policyQualifierInfo.size() > 0) {
        ASN1EncodableVector policyQualifiersVec = new ASN1EncodableVector();

        for (PolicyQualifierInfo policyQualInfo : policyQualifierInfo) {
            try {
                policyQualifiersVec.add(policyQualInfo);
            } catch (Exception ex) {
                DError dError = new DError(this, ex);
                dError.setLocationRelativeTo(this);
                dError.setVisible(true);
                return;
            }
        }

        DERSequence policyQualifiersSeq = new DERSequence(policyQualifiersVec);
        policyInformation = new PolicyInformation(policyIdentifer, policyQualifiersSeq);
    } else {

        policyInformation = new PolicyInformation(policyIdentifer);
    }

    closeDialog();
}

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

License:Open Source License

private void okPressed() {
    List<AccessDescription> accessDescriptions = jadAccessDescriptions.getAccessDescriptions();

    if (accessDescriptions.size() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DAuthorityInformationAccess.ValueReq.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;//w  ww  .  j a  v a  2s. c om
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();
    for (AccessDescription accessDescription : accessDescriptions) {
        vec.add(accessDescription);
    }
    AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
            .getInstance(new DERSequence(vec));

    try {
        value = authorityInformationAccess.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.DPrivateKeyUsagePeriod.java

License:Open Source License

private void okPressed() {

    Date notBefore = jdtNotBefore.getDateTime();
    Date notAfter = jdtNotAfter.getDateTime();

    if ((notBefore == null) && (notAfter == null)) {
        JOptionPane.showMessageDialog(this, res.getString("DPrivateKeyUsagePeriod.ValueReq.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;/*from w w w . ja  v a 2  s. c o  m*/
    }

    // BC forgot the value constructor for PrivateKeyUsagePeriod...
    ASN1EncodableVector v = new ASN1EncodableVector();
    if (notBefore != null) {
        DERGeneralizedTime notBeforeGenTime = new DERGeneralizedTime(notBefore);
        v.add(new DERTaggedObject(false, 0, notBeforeGenTime));
    }
    if (notAfter != null) {
        DERGeneralizedTime notAfterGenTime = new DERGeneralizedTime(notAfter);
        v.add(new DERTaggedObject(false, 1, notAfterGenTime));
    }

    PrivateKeyUsagePeriod privateKeyUsagePeriod = PrivateKeyUsagePeriod.getInstance(new DERSequence(v));

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

    closeDialog();
}

From source file:no.difi.oxalis.as2.util.SMimeBC.java

License:EUPL

public static byte[] createSignature(byte[] digest, SMimeDigestMethod digestMethod, PrivateKey privateKey,
        X509Certificate certificate) throws OxalisSecurityException {
    try {/*from  w  w w  .ja  v a 2  s . c  om*/
        ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
        signedAttributes.add(new Attribute(CMSAttributes.contentType, new DERSet(digestMethod.getOid())));
        signedAttributes
                .add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest))));
        signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));

        AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
        signedAttributesTable.toASN1EncodableVector();
        DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        /* Build the SignerInfo generator builder, that will build the generator... that will generate the SignerInformation... */
        SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .build());
        signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator);
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(digestMethod.getMethod())
                .setProvider(BouncyCastleProvider.PROVIDER_NAME);

        generator.addSignerInfoGenerator(signerInfoBuilder.build(contentSigner.build(privateKey),
                new X509CertificateHolder(certificate.getEncoded())));
        generator.addCertificates(new JcaCertStore(Collections.singletonList(certificate)));

        return generator.generate(new CMSAbsentContent()).getEncoded();
    } catch (CMSException | IOException | CertificateEncodingException | OperatorCreationException e) {
        throw new OxalisSecurityException(e.getMessage(), e);
    }
}

From source file:org.apache.http.contrib.auth.BouncySpnegoTokenGenerator.java

License:Apache License

public byte[] generateSpnegoDERObject(byte[] kerbTicket) throws IOException {
    DEROctetString ourKerberosTicket = new DEROctetString(kerbTicket);

    DERSequence kerbOidSeq = new DERSequence(kerbOid);
    DERTaggedObject tagged0 = new DERTaggedObject(0, kerbOidSeq);
    DERTaggedObject tagged2 = new DERTaggedObject(2, ourKerberosTicket);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tagged0);
    v.add(tagged2);/*from ww w  . j av a2 s . c  o  m*/
    DERSequence seq = new DERSequence(v);
    DERTaggedObject taggedSpnego = new DERTaggedObject(0, seq);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ASN1OutputStream asn1Out = new ASN1OutputStream(out);

    ASN1Object spnegoOIDASN1 = (ASN1Object) spnegoOid.toASN1Object();
    ASN1Object taggedSpnegoASN1 = (ASN1Object) taggedSpnego.toASN1Object();

    int length = spnegoOIDASN1.getDEREncoded().length + taggedSpnegoASN1.getDEREncoded().length;
    byte[] lenBytes = writeLength(length);
    byte[] appWrap = new byte[lenBytes.length + 1];

    appWrap[0] = 0x60;
    for (int i = 1; i < appWrap.length; i++) {
        appWrap[i] = lenBytes[i - 1];
    }

    asn1Out.write(appWrap);
    asn1Out.writeObject(spnegoOid.toASN1Object());
    asn1Out.writeObject(taggedSpnego.toASN1Object());

    byte[] app = out.toByteArray();
    ASN1InputStream in = new ASN1InputStream(app);

    if (log.isDebugEnabled()) {
        int skip = 12;
        byte[] manipBytes = new byte[app.length - skip];
        for (int i = skip; i < app.length; i++) {
            manipBytes[i - skip] = app[i];
        }
        ASN1InputStream ourSpnego = new ASN1InputStream(manipBytes);
        log.debug(ASN1Dump.dumpAsString(ourSpnego.readObject()));
    }

    return in.readObject().getDEREncoded();
}

From source file:org.apache.kerby.pkix.EndEntityGenerator.java

License:Apache License

/**
 * Generate certificate.//from   w w w  . ja  v a2 s . c  o  m
 *
 * @param issuerCert
 * @param issuerPrivateKey
 * @param publicKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey,
        PublicKey publicKey, String dn, int validityDays, String friendlyName)
        throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException,
        DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert));
    certGen.setSubjectDN(new X509Principal(dn));

    certGen.setNotBefore(new Date());

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    // MAY set BasicConstraints=false or not at all.
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(issuerCert));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment));

    ASN1EncodableVector keyPurposeVector = new ASN1EncodableVector();
    keyPurposeVector.add(KeyPurposeId.id_kp_smartcardlogon);
    //keyPurposeVector.add( KeyPurposeId.id_kp_serverAuth );
    DERSequence keyPurposeOids = new DERSequence(keyPurposeVector);

    // If critical, will throw unsupported EKU.
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, keyPurposeOids);

    ASN1EncodableVector pkinitSanVector = new ASN1EncodableVector();
    pkinitSanVector.add(ID_PKINIT_SAN);
    pkinitSanVector.add(new DERTaggedObject(0, new DERSequence()));
    DERSequence pkinitSan = new DERSequence(pkinitSanVector);

    String dnsName = "localhost";

    GeneralName name1 = new GeneralName(GeneralName.otherName, pkinitSan);
    GeneralName name2 = new GeneralName(GeneralName.dNSName, dnsName);

    GeneralNamesBuilder genNamesBuilder = new GeneralNamesBuilder();

    genNamesBuilder.addName(name1);
    genNamesBuilder.addName(name2);

    GeneralNames sanGeneralNames = genNamesBuilder.build();

    certGen.addExtension(X509Extensions.SubjectAlternativeName, true, sanGeneralNames);

    /*
     * The KDC MAY require the presence of an Extended Key Usage (EKU) KeyPurposeId
     * [RFC3280] id-pkinit-KPClientAuth in the extensions field of the client's
     * X.509 certificate.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the client's X.509 certificate is restricted with
     * the id-pkinit-KPClientAuth EKU.
     */

    /*
     * KDCs implementing this requirement SHOULD also accept the EKU KeyPurposeId
     * id-ms-kp-sc-logon (1.3.6.1.4.1.311.20.2.2) as meeting the requirement, as
     * there are a large number of X.509 client certificates deployed for use
     * with PKINIT that have this EKU.
     */

    // KDC
    /*
     * In addition, unless the client can otherwise verify that the public key
     * used to verify the KDC's signature is bound to the KDC of the target realm,
     * the KDC's X.509 certificate MUST contain a Subject Alternative Name extension
     * [RFC3280] carrying an AnotherName whose type-id is id-pkinit-san (as defined
     * in Section 3.2.2) and whose value is a KRB5PrincipalName that matches the
     * name of the TGS of the target realm (as defined in Section 7.3 of [RFC4120]).
     */

    /*
     * Unless the client knows by some other means that the KDC certificate is
     * intended for a Kerberos KDC, the client MUST require that the KDC certificate
     * contains the EKU KeyPurposeId [RFC3280] id-pkinit-KPKdc.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the KDC's X.509 certificate is restricted with the
     * id-pkinit-KPKdc EKU.
     */

    /*
     * If the KDC certificate contains the Kerberos TGS name encoded as an id-pkinit-san
     * SAN, this certificate is certified by the issuing CA as a KDC certificate,
     * therefore the id-pkinit-KPKdc EKU is not required.
     */

    /*
     * KDC certificates issued by Windows 2000 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, and the id-kp-serverAuth
     * EKU [RFC3280].
     */

    /*
     * KDC certificates issued by Windows 2003 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, the id-kp-serverAuth
     * EKU, and the id-ms-kp-sc-logon EKU.
     */

    /*
     * RFC: KDC certificates with id-pkinit-san SAN as specified in this RFC.
     * 
     * MS:  dNSName SAN containing the domain name of the KDC
     *      id-pkinit-KPKdc EKU
     *      id-kp-serverAuth EKU.
     */

    /*
     * Client certificates accepted by Windows 2000 and Windows 2003 Server KDCs
     * must contain an id-ms-san-sc-logon-upn (1.3.6.1.4.1.311.20.2.3) SAN and
     * the id-ms-kp-sc-logon EKU.  The id-ms-san-sc-logon-upn SAN contains a
     * UTF8-encoded string whose value is that of the Directory Service attribute
     * UserPrincipalName of the client account object, and the purpose of including
     * the id-ms-san-sc-logon-upn SAN in the client certificate is to validate
     * the client mapping (in other words, the client's public key is bound to
     * the account that has this UserPrincipalName value).
     */

    X509Certificate cert = certGen.generate(issuerPrivateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.cagrid.security.ssl.proxy.trust.ProxyCertInfo.java

License:Open Source License

/**
 * Returns the DER-encoded ASN.1 representation of the extension.
 * // w  w  w.ja v  a2s. c o m
 * @return <code>DERObject</code> the encoded representation of the
 *         extension.
 */
public DERObject getDERObject() {
    ASN1EncodableVector vec = new ASN1EncodableVector();

    if (this.pathLenConstraint != null) {
        vec.add(this.pathLenConstraint);
    }

    vec.add(this.proxyPolicy.getDERObject());

    return new DERSequence(vec);
}

From source file:org.cagrid.security.ssl.proxy.trust.ProxyPolicy.java

License:Open Source License

/**
 * Returns the DER-encoded ASN.1 representation of proxy policy.
 * /*from   w w  w.j  ava2s  .c om*/
 * @return <code>DERObject</code> the encoded representation of the proxy
 *         policy.
 */
public DERObject getDERObject() {
    ASN1EncodableVector vec = new ASN1EncodableVector();

    vec.add(this.policyLanguage);

    if (this.policy != null) {
        vec.add(this.policy);
    }

    return new DERSequence(vec);
}