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: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);//from ww  w. ja  v  a  2s .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.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

License:Apache License

/**
 * Gets the OCSP status for the specified subject and issuer certificates.
 *
 * @param ocspStatusKey status key// w  w w . j ava2s.  co  m
 * @return ocsp status
 */
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
    final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
    final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();

    // initialize the default status
    final OcspStatus ocspStatus = new OcspStatus();
    ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
    ocspStatus.setValidationStatus(ValidationStatus.Unknown);

    try {
        // prepare the request
        final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
        final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build();
        final CertificateID certificateId = new CertificateID(
                calculatorProviderBuilder.get(CertificateID.HASH_SHA1),
                new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);

        // generate the request
        final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
        requestGenerator.addRequest(certificateId);

        // Create a nonce to avoid replay attack
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
                new DEROctetString(nonce.toByteArray()));
        requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));

        final OCSPReq ocspRequest = requestGenerator.build();

        // perform the request
        final Response response = getClientResponse(ocspRequest);

        // ensure the request was completed successfully
        if (Response.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
            return ocspStatus;
        }

        // interpret the response
        OCSPResp ocspResponse = new OCSPResp(response.readEntity(InputStream.class));

        // verify the response status
        switch (ocspResponse.getStatus()) {
        case OCSPRespBuilder.SUCCESSFUL:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
            break;
        case OCSPRespBuilder.INTERNAL_ERROR:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
            break;
        case OCSPRespBuilder.MALFORMED_REQUEST:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
            break;
        case OCSPRespBuilder.SIG_REQUIRED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
            break;
        case OCSPRespBuilder.TRY_LATER:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
            break;
        case OCSPRespBuilder.UNAUTHORIZED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
            break;
        default:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
            break;
        }

        // only proceed if the response was successful
        if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).",
                    ocspStatus.getResponseStatus().toString()));
            return ocspStatus;
        }

        // ensure the appropriate response object
        final Object ocspResponseObject = ocspResponse.getResponseObject();
        if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
            logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
            return ocspStatus;
        }

        // get the response object
        final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        // attempt to locate the responder certificate
        final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
        if (responderCertificates.length != 1) {
            logger.warn(String.format("Unexpected number of OCSP responder certificates: %s",
                    responderCertificates.length));
            return ocspStatus;
        }

        // get the responder certificate
        final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(
                responderCertificates[0], issuerCertificate);
        if (trustedResponderCertificate != null) {
            // verify the response
            if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC")
                    .build(trustedResponderCertificate.getPublicKey()))) {
                ocspStatus.setVerificationStatus(VerificationStatus.Verified);
            } else {
                ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
            }
        } else {
            ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
        }

        // validate the response
        final SingleResp[] responses = basicOcspResponse.getResponses();
        for (SingleResp singleResponse : responses) {
            final CertificateID responseCertificateId = singleResponse.getCertID();
            final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();

            if (responseSerialNumber.equals(subjectSerialNumber)) {
                Object certStatus = singleResponse.getCertStatus();

                // interpret the certificate status
                if (CertificateStatus.GOOD == certStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Good);
                } else if (certStatus instanceof RevokedStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Revoked);
                } else {
                    ocspStatus.setValidationStatus(ValidationStatus.Unknown);
                }
            }
        }
    } catch (final OCSPException | IOException | ProcessingException | OperatorCreationException e) {
        logger.error(e.getMessage(), e);
    } catch (CertificateException e) {
        e.printStackTrace();
    }

    return ocspStatus;
}

From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java

License:Apache License

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(
            new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure
            .getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo()
            .getAlgorithmId();/*from   www .j  av a  2  s . c om*/
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(),
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId());
    cipher.init(1, x509certificate.getPublicKey());
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}

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

License:Apache License

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked,
        X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate,
        PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis)
        throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
            .get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());

    // request//from www .j a v  a  2 s .  c  om
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);

    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1,
            ocspResponderCertificate.getPublicKey().getEncoded());

    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);

    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }

    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()),
                issuerHolder };
    }

    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC")
            .build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));

    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);

    return ocspResp;
}

From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java

License:Apache License

/**
 * This method generates an OCSP Request to be sent to an OCSP endpoint.
 *
 * @param issuerCert   is the Certificate of the Issuer of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request./*from w  w w  . j  a v  a  2s .c  o m*/
 * @throws CertificateVerificationException
 *
 */
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateVerificationException {

    //TODO: Have to check if this is OK with synapse implementation.
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {
        //  CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560
        CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);

        // basic request generation with nonce
        OCSPReqGenerator generator = new OCSPReqGenerator();
        generator.addRequest(id);

        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent replay attacks. As the name implies,
        // the nonce value is something that the client should only use once within a reasonably small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector<ASN1ObjectIdentifier> objectIdentifiers = new Vector<ASN1ObjectIdentifier>();
        Vector<X509Extension> values = new Vector<X509Extension>();

        //to create the request Extension
        objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values));

        return generator.generate();
    } catch (OCSPException e) {
        throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate",
                e);
    }
}

From source file:org.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java

License:Apache License

/**
 * This method generates an OCSP Request to be sent to an OCSP endpoint.
 *
 * @param issuerCert   is the Certificate of the Issuer of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request./* www .j av a  2s. c  om*/
 * @throws CertificateVerificationException
 */
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateVerificationException {

    //TODO: Have to check if this is OK with synapse implementation.
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {
        //  CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined
        // in RFC 2560
        CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);

        // basic request generation with nonce
        OCSPReqGenerator generator = new OCSPReqGenerator();
        generator.addRequest(id);

        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent replay attacks. As the name implies,
        // the nonce value is something that the client should only use once within a reasonably
        // small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector<ASN1ObjectIdentifier> objectIdentifiers = new Vector<ASN1ObjectIdentifier>();
        Vector<X509Extension> values = new Vector<X509Extension>();

        //to create the request Extension
        objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values));

        return generator.generate();
    } catch (OCSPException e) {
        throw new CertificateVerificationException(
                "Cannot generate OCSP Request with the " + "given certificate", e);
    }
}

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".
 *///from w ww  . j  a  v  a2s  .co  m
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.cagrid.security.ssl.proxy.trust.ProxyPolicy.java

License:Open Source License

/**
 * Creates a new instance of the ProxyPolicy object.
 * /*from w w  w  .ja  v  a2 s. c o m*/
 * @param policyLanguage
 *            the language policy Oid.
 * @param policy
 *            the policy.
 */
public ProxyPolicy(DERObjectIdentifier policyLanguage, byte[] policy) {
    if (policyLanguage == null) {
        throw new IllegalArgumentException("Policy langauge oid required");
    }
    this.policyLanguage = policyLanguage;
    if (policy != null) {
        this.policy = new DEROctetString(policy);
    }
    checkConstraints();
}

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

License:Open Source License

/**
 * Creates a new instance of the ProxyPolicy object.
 * /*from w ww  . j  a  va  2  s  .c  o m*/
 * @param policyLanguageOid
 *            the language policy Oid.
 * @param policy
 *            the policy.
 */
public ProxyPolicy(String policyLanguageOid, byte[] policy) {
    if (policyLanguageOid == null) {
        throw new IllegalArgumentException("Policy langauge oid required");
    }
    this.policyLanguage = new DERObjectIdentifier(policyLanguageOid);
    if (policy != null) {
        this.policy = new DEROctetString(policy);
    }
    checkConstraints();
}

From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java

License:Open Source License

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions,
        Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair,
        BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X509Certificate caCert = reader.getCACert();
    // set cert fields
    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(startDate);//from w w  w  . j av  a  2s.  c o  m
    certGen.setNotAfter(endDate);

    X500Principal subjectPrincipal = new X500Principal(dn);
    certGen.setSubjectDN(subjectPrincipal);
    certGen.setPublicKey(clientKeyPair.getPublic());
    certGen.setSignatureAlgorithm(SIGNATURE_ALGO);

    // set key usage - required for proper x509 function
    KeyUsage keyUsage = new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);

    // add SSL extensions - required for proper x509 function
    NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);

    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType.toString(), false, certType);
    certGen.addExtension(X509Extensions.KeyUsage.toString(), false, keyUsage);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

    // Add an alternate name if provided
    if (alternateName != null) {
        GeneralName name = new GeneralName(GeneralName.uniformResourceIdentifier, "CN=" + alternateName);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(name));
    }

    if (extensions != null) {
        for (X509ExtensionWrapper wrapper : extensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            String value = wrapper.getValue() == null ? "" : wrapper.getValue();
            certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DERUTF8String(value));
        }
    }

    if (byteExtensions != null) {
        for (X509ByteExtensionWrapper wrapper : byteExtensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
            certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DEROctetString(value));
        }
    }

    // Generate the certificate
    return certGen.generate(reader.getCaKey());
}