Example usage for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector

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

Introduction

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

Prototype

public ASN1EncodableVector() 

Source Link

Usage

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;/*w  w w  .j av  a 2  s.co  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:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

public VOMSAttributeCertificate(String holderString, int holderSerialNumber, String issuerString,
        int productionSerial, long fromEpoch, long toEpoch, String[] fqans) throws Exception {
    try {/*from w  ww  .  j  a va2 s . com*/
        DEREncodableVector infoVector = new ASN1EncodableVector();

        this.setVersion();
        this.setHolder(holderString, holderSerialNumber);
        this.setIssuer(issuerString);
        this.setAlgorithmIdentifier();
        this.setSerialNumber(productionSerial);
        this.setTimes(new Date(fromEpoch), new Date(toEpoch));
        this.setVOMSFQANs(fqans);
        this.setExtensions();

        infoVector.add(version);
        infoVector.add(holder);
        infoVector.add(issuer);
        infoVector.add(signature);
        infoVector.add(serialNumber);
        infoVector.add(attrCertValidityPeriod);
        infoVector.add(attributes);
        infoVector.add(extensions);

        ASN1Sequence infoSequence = ASN1Sequence.getInstance(new DERSequence(infoVector));

        this.acinfo = new AttributeCertificateInfo(infoSequence);

        // Do it this way to match Vincenzo as much as possible
        // - rather than this way... this.signatureAlgorithm = new AlgorithmIdentifier( "1.2.840.113549.1.1.4" ) ;
        this.signatureAlgorithm = new AlgorithmIdentifier(new DERObjectIdentifier("1.2.840.113549.1.1.4"),
                (DEREncodable) null);

        this.signatureValue = new DERBitString(this.sign());

        this.ac = new AttributeCertificate(acinfo, signatureAlgorithm, signatureValue);

    } catch (Exception e) {
        // inspect?: 
        throw e;
    }

}

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

License:Apache License

public void setVOMSFQANs(String[] fqans) throws Exception {
    try {/*  w  w w  .j a  v a 2  s . c om*/
        //--------------------------------------------------------------------------
        // put the FQANs into the SEQUENCE

        DEREncodableVector fqanVector = new ASN1EncodableVector();

        for (int f = 0; f < fqans.length; f++) {
            DERGeneralString fqan = new DERGeneralString(fqans[f]);
            ASN1OctetString fqanOctetString = ASN1OctetString.getInstance(new DEROctetString(fqan.getOctets()));
            fqanVector.add(fqanOctetString);
        }

        ASN1Sequence fqanSequence = ASN1Sequence.getInstance(new DERSequence(fqanVector));

        //--------------------------------------------------------------------------
        // put something into the undocumented TaggedObject

        DERGeneralString origin = new DERGeneralString("gridportal://newvoms:15000");

        ASN1OctetString originOctetString = ASN1OctetString.getInstance(new DEROctetString(origin.getOctets()));

        /*
         ASN1TaggedObject taggedObject2 = ASN1TaggedObject.getInstance( new DERTaggedObject( 6 , originOctetString ) , true ) ;
                
         ASN1TaggedObject taggedObject = ASN1TaggedObject.getInstance( new DERTaggedObject( 0 , taggedObject2 ) , true ) ;
                
         DEROctetString originOctetString = new DEROctetString( origin.getOctets() ) ;
         */

        DERTaggedObject taggedObject2 = new DERTaggedObject(6, originOctetString);

        DERTaggedObject taggedObject = new DERTaggedObject(0, taggedObject2);

        //--------------------------------------------------------------------------
        // put the taggedObject and then the fqanSequence into sequence2

        DEREncodableVector sequence2Vector = new ASN1EncodableVector();
        sequence2Vector.add(taggedObject);
        sequence2Vector.add(fqanSequence);
        ASN1Sequence sequence2 = ASN1Sequence.getInstance(new DERSequence(sequence2Vector));

        //--------------------------------------------------------------------------
        // the SET has one member - sequence2

        ASN1Set set = ASN1Set.getInstance(new DERSet(sequence2));

        //--------------------------------------------------------------------------
        // SEQUENCE sequence has an OID and the set

        DERObjectIdentifier voms4oid = new DERObjectIdentifier("1.3.6.1.4.1.8005.100.100.4");

        DEREncodableVector sequenceVector = new ASN1EncodableVector();
        sequenceVector.add(voms4oid);
        sequenceVector.add(set);
        ASN1Sequence sequence = ASN1Sequence.getInstance(new DERSequence(sequenceVector));

        //--------------------------------------------------------------------------

        this.attributes = ASN1Sequence.getInstance(new DERSequence(sequence));

    } catch (Exception e) {
        throw e;
    }

}

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 {//from  ww w. j  a  v  a2 s . c  o m
        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: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  ww w .j a v a 2s. co m
        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:no.difi.oxalis.as2.util.SMimeMessageFactory.java

License:EUPL

/**
 * Creates an S/MIME message using the supplied MimeBodyPart. The signature is generated using the private key
 * as supplied in the constructor. Our certificate, which is required to verify the signature is enclosed.
 *//*from  w  ww  . j a  v  a2 s. c  o m*/
public MimeMessage createSignedMimeMessage(MimeBodyPart mimeBodyPart, SMimeDigestMethod digestMethod)
        throws OxalisTransmissionException {

    //
    // S/MIME capabilities are required, but we simply supply an empty vector
    //
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();

    //
    // create the generator for creating an smime/signed message
    //
    SMIMESignedGenerator smimeSignedGenerator = new SMIMESignedGenerator("binary"); //also see CMSSignedGenerator ?

    //
    // add a signer to the generator - this specifies we are using SHA1 and
    // adding the smime attributes above to the signed attributes that
    // will be generated as part of the signature. The encryption algorithm
    // used is taken from the key - in this RSA with PKCS1Padding
    //
    try {
        smimeSignedGenerator.addSignerInfoGenerator(
                new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                        // .build("SHA1withRSA", privateKey, ourCertificate));
                        .build(digestMethod.getMethod(), privateKey, ourCertificate));
    } catch (OperatorCreationException e) {
        throw new OxalisTransmissionException("Unable to add Signer information. " + e.getMessage(), e);
    } catch (CertificateEncodingException e) {
        throw new OxalisTransmissionException(String.format(
                "Certificate encoding problems while adding signer information. %s", e.getMessage()), e);
    }

    //
    // create a CertStore containing the certificates we want carried
    // in the signature
    //
    Store certs;
    try {
        certs = new JcaCertStore(Collections.singleton(ourCertificate));
    } catch (CertificateEncodingException e) {
        throw new OxalisTransmissionException(
                "Unable to create JcaCertStore with our certificate. " + e.getMessage(), e);
    }
    smimeSignedGenerator.addCertificates(certs);

    //
    // Signs the supplied MimeBodyPart
    //
    MimeMultipart mimeMultipart;
    try {
        mimeMultipart = smimeSignedGenerator.generate(mimeBodyPart);
    } catch (SMIMEException e) {
        throw new OxalisTransmissionException("Unable to generate signed mime multipart." + e.getMessage(), e);
    }

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage mimeMessage = new MimeMessage(session);

    try {
        mimeMessage.setContent(mimeMultipart, mimeMultipart.getContentType());
    } catch (MessagingException e) {
        throw new OxalisTransmissionException("Unable to  set Content type of MimeMessage. " + e.getMessage(),
                e);
    }
    try {
        mimeMessage.saveChanges();
    } catch (MessagingException e) {
        throw new OxalisTransmissionException("Unable to save changes to Mime message. " + e.getMessage(), e);
    }

    return mimeMessage;
}

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);//  w  w w .  jav  a2  s.c o m
    v.add(tagged2);
    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.//  ww w.j a v a2 s.  co  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.
 * /*from   w  ww.j  a  va2 s .  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  a  v a 2s  .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);
}