Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

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

Introduction

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

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:net.jsign.asn1.authenticode.SpcSerializedObject.java

License:Apache License

public SpcSerializedObject(byte[] serializedData) {
    this.serializedData = new DEROctetString(serializedData);
}

From source file:net.maritimecloud.pki.ocsp.OCSPClient.java

License:Open Source License

private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateEncodingException, OperatorCreationException, OCSPException, IOException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(new JcaDigestCalculatorProviderBuilder()
            .setProvider(PKIConstants.BC_PROVIDER_NAME).build().get(CertificateID.HASH_SHA1), issuerCert,
            serialNumber));/*from  ww  w  .j a  v  a  2  s .  c  om*/

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
            new DEROctetString(nonce.toByteArray()));
    gen.setRequestExtensions(new Extensions(new Extension[] { ext }));
    sentNonce = ext.getExtnId().getEncoded();

    return gen.build();
}

From source file:net.ripe.rpki.commons.crypto.rfc3779.AddressFamily.java

License:BSD License

public DEROctetString toDer() {
    int length = hasSubsequentAddressFamilyIdentifier() ? AFI_OCTET_COUNT_WITH_SAFI
            : AFI_OCTET_COUNT_WITHOUT_SAFI;

    byte[] encoded = new byte[length];
    encoded[0] = (byte) (addressFamilyIdentifier >> Byte.SIZE);
    encoded[1] = (byte) (addressFamilyIdentifier);
    if (hasSubsequentAddressFamilyIdentifier()) {
        encoded[2] = subsequentAddressFamilyIdentifier.byteValue();
    }/*from   w w  w.j  a  v a2 s. co  m*/

    return new DEROctetString(encoded);
}

From source file:net.ripe.rpki.commons.provisioning.x509.pkcs10.RpkiCaCertificateRequestBuilder.java

License:BSD License

private Extensions createExtensions() throws IOException {
    // Make extension for SIA in request. See here:
    // http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation
    List<Extension> extensions = new ArrayList<Extension>();

    X509CertificateInformationAccessDescriptor[] descriptors = new X509CertificateInformationAccessDescriptor[] {
            new X509CertificateInformationAccessDescriptor(
                    X509CertificateInformationAccessDescriptor.ID_AD_CA_REPOSITORY, caRepositoryUri),
            new X509CertificateInformationAccessDescriptor(
                    X509CertificateInformationAccessDescriptor.ID_AD_RPKI_MANIFEST, manifestUri), };
    AccessDescription[] subjectInformationAccess = X509CertificateInformationAccessDescriptor
            .convertAccessDescriptors(descriptors);
    DERSequence derSequence = new DERSequence(subjectInformationAccess);

    extensions.add(//from w  w w  .jav a  2  s  . c  o  m
            new Extension(Extension.subjectInfoAccess, false, new DEROctetString(derSequence.getEncoded())));
    KeyUsage keyUsage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign);
    extensions.add(new Extension(Extension.keyUsage, true, new DEROctetString(keyUsage)));

    extensions.add(
            new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(true))));

    return new Extensions(extensions.toArray(new Extension[extensions.size()]));
}

From source file:net.sf.dsig.verify.OCSPHelper.java

License:Apache License

/**
 * Check with OCSP protocol whether a certificate is valid
 * /*from  www.  ja  v  a 2  s.c om*/
 * @param certificate an {@link X509Certificate} object
 * @return true if the certificate is valid; false otherwise
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an OCSP related error occurs
 */
public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException {
    PostMethod post = null;

    try {
        CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate,
                certificate.getSerialNumber());

        OCSPReqGenerator gen = new OCSPReqGenerator();
        gen.addRequest(cid);

        // Nonce
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector oids = new Vector();
        Vector values = new Vector();
        oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        values.add(new X509Extension(false,
                new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray())));
        gen.setRequestExtensions(new X509Extensions(oids, values));

        // Requestor name - not really required, but added for completeness
        //          gen.setRequestorName(
        //                  new GeneralName(
        //                          new X509Name(
        //                                  certificate.getSubjectX500Principal().getName())));

        logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16)
                + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName="
                + caCertificate.getSubjectX500Principal().getName());

        // TODO Need to call the generate(...) method, that signs the 
        // request. Which means, need to have a keypair for that, too
        OCSPReq req = gen.generate();

        // First try finding the OCSP access location in the X.509 certificate
        String uriAsString = getOCSPAccessLocationUri(certificate);

        // If not found, try falling back to the default
        if (uriAsString == null) {
            uriAsString = defaultOcspAccessLocation;
        }

        // If still null, bail out
        if (uriAsString == null) {
            throw new ConfigurationException(
                    "OCSP AccessLocation not found on certificate, and no default set");
        }

        HostConfiguration config = getHostConfiguration();

        post = new PostMethod(uriAsString);
        post.setRequestHeader("Content-Type", "application/ocsp-request");
        post.setRequestHeader("Accept", "application/ocsp-response");
        post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded()));

        getHttpClient().executeMethod(config, post);

        logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine="
                + post.getStatusLine());

        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine());
        }

        byte[] responseBodyBytes = post.getResponseBody();

        OCSPResp ocspRes = new OCSPResp(responseBodyBytes);
        if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
            // One possible exception is the use of a wrong CA certificate
            throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate"
                    + "; status=" + ocspRes.getStatus());
        }

        BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject();
        SingleResp[] responses = res.getResponses();
        SingleResp response = responses[0];

        CertificateStatus status = (CertificateStatus) response.getCertStatus();
        // Normal OCSP protocol allows a null status
        return status == null || status == CertificateStatus.GOOD;
    } catch (IOException e) {
        throw new NetworkAccessException("I/O error occured", e);
    } catch (OCSPException e) {
        throw new VerificationException("Error while following OCSP protocol", e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:net.sf.taverna.t2.activities.wsdl.servicedescriptions.ConfirmTrustedCertificateDialog.java

License:Open Source License

/**
 * Gets the intended certificate uses, i.e. Netscape Certificate Type
 * extension (2.16.840.1.113730.1.1) value as a string
 * //w w  w. j  a  v  a2s . c  om
 * @param value
 *            Extension value as a DER-encoded OCTET string
 * @return Extension value as a string
 */
private String getIntendedUses(byte[] value) {

    // Netscape Certificate Types (2.16.840.1.113730.1.1)
    int[] INTENDED_USES = new int[] { NetscapeCertType.sslClient, NetscapeCertType.sslServer,
            NetscapeCertType.smime, NetscapeCertType.objectSigning, NetscapeCertType.reserved,
            NetscapeCertType.sslCA, NetscapeCertType.smimeCA, NetscapeCertType.objectSigningCA, };

    // Netscape Certificate Type strings (2.16.840.1.113730.1.1)
    HashMap<String, String> INTENDED_USES_STRINGS = new HashMap<String, String>();
    INTENDED_USES_STRINGS.put("128", "SSL Client");
    INTENDED_USES_STRINGS.put("64", "SSL Server");
    INTENDED_USES_STRINGS.put("32", "S/MIME");
    INTENDED_USES_STRINGS.put("16", "Object Signing");
    INTENDED_USES_STRINGS.put("8", "Reserved");
    INTENDED_USES_STRINGS.put("4", "SSL CA");
    INTENDED_USES_STRINGS.put("2", "S/MIME CA");
    INTENDED_USES_STRINGS.put("1", "Object Signing CA");

    // Get octet string from extension value
    ASN1OctetString fromByteArray = new DEROctetString(value);
    byte[] octets = fromByteArray.getOctets();
    DERBitString fromByteArray2 = new DERBitString(octets);
    int val = new NetscapeCertType(fromByteArray2).intValue();
    StringBuffer strBuff = new StringBuffer();
    for (int i = 0, len = INTENDED_USES.length; i < len; i++) {
        int use = INTENDED_USES[i];
        if ((val & use) == use) {
            strBuff.append(INTENDED_USES_STRINGS.get(String.valueOf(use)) + ", \n");
        }
    }
    // remove the last ", \n" from the end of the buffer
    String str = strBuff.toString();
    str = str.substring(0, str.length() - 3);
    return str;
}

From source file:net.sourceforge.javacardsign.iso7816_15.CommonAuthenticationObjectAttributes.java

License:Open Source License

public DERObject getDERObject() {
    return new DERSequence(new ASN1Encodable[] { new DEROctetString(this.authId) });
}

From source file:net.sourceforge.javacardsign.iso7816_15.CommonKeyAttributes.java

License:Open Source License

public DERObject getDERObject() {
    DERBitString usage = new DERBitString(CommonObjectAttributes.encodeBits(this.usage),
            CommonObjectAttributes.getPad(this.usage));
    DEROctetString id = new DEROctetString(this.id);
    return new DERSequence(new ASN1Encodable[] { id, usage });
}

From source file:net.sourceforge.javacardsign.iso7816_15.CommonObjectAttributes.java

License:Open Source License

public DERObject getDERObject() {
    DERUTF8String label = new DERUTF8String(this.label);
    DERBitString flags = new DERBitString(encodeBits(this.flags), getPad(this.flags));
    if (authId != -1) {
        DEROctetString authId = new DEROctetString(new byte[] { this.authId });
        return new DERSequence(new ASN1Encodable[] { label, flags, authId });
    } else {/* w ww .  ja  va2  s  .  c  o m*/
        return new DERSequence(new ASN1Encodable[] { label, flags });
    }
}

From source file:net.sourceforge.javacardsign.iso7816_15.ObjectDirectoryEntry.java

License:Open Source License

public DERObject getDERObject() {
    byte[] p = new byte[2];
    p[0] = (byte) (this.fid >> 8 & 0xFF);
    p[1] = (byte) (this.fid & 0xFF);
    DERSequence path = new DERSequence(new ASN1Encodable[] { new DEROctetString(p) });
    return new DERTaggedObject(tag, path);
}