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.jruby.ext.openssl.impl.PKCS7DataData.java

License:LGPL

@Override
public ASN1Encodable asASN1() {
    if (data == null) {
        return new DEROctetString(new byte[0]).toASN1Primitive();
    }//from   w  ww .j a v a 2  s  .  c  o m
    return data.toASN1Primitive();
}

From source file:org.jruby.ext.openssl.X509Extension.java

License:LGPL

ASN1Sequence toASN1Sequence() throws IOException {
    final ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(getRealObjectID());//  w w w. ja v a 2  s  .c  o  m
    if (critical)
        vec.add(DERBoolean.TRUE);
    vec.add(new DEROctetString(getRealValueEncoded()));
    return new DLSequence(vec);
}

From source file:org.jruby.ext.openssl.X509ExtensionFactory.java

License:LGPL

@JRubyMethod(rest = true)
public IRubyObject create_ext(final ThreadContext context, final IRubyObject[] args) {
    final Ruby runtime = context.runtime;
    IRubyObject critical;// www  .  j a  va 2s  .  c  o  m
    if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3 && !args[2].isNil()) {
        critical = args[2];
    } else {
        critical = runtime.getFalse();
    }
    final String oid = args[0].toString();
    String valuex = args[1].toString();
    final ASN1ObjectIdentifier objectId;
    try {
        objectId = ASN1.getObjectID(runtime, oid);
    } catch (IllegalArgumentException e) {
        debug(runtime, "ASN1.getObjectIdentifier() at ExtensionFactory.create_ext", e);
        throw newExtensionError(runtime, "unknown OID `" + oid + "'");
    }
    final String critical_ = "critical,";
    if (valuex.startsWith(critical_)) {
        critical = runtime.getTrue();
        valuex = valuex.substring(critical_.length()).trim();
    }
    final ASN1Encodable value;
    try {
        final String id = objectId.getId();
        if (id.equals("2.5.29.14")) { //subjectKeyIdentifier
            value = new DEROctetString(parseSubjectKeyIdentifier(context, oid, valuex));
        } else if (id.equals("2.5.29.35")) { //authorityKeyIdentifier
            value = parseAuthorityKeyIdentifier(context, valuex);
        } else if (id.equals("2.5.29.17")) { //subjectAltName
            value = parseSubjectAltName(valuex);
        } else if (id.equals("2.5.29.18")) { //issuerAltName
            value = parseIssuerAltName(context, valuex);
        } else if (id.equals("2.5.29.19")) { //basicConstraints
            value = parseBasicConstrains(valuex);
        } else if (id.equals("2.5.29.15")) { //keyUsage
            value = parseKeyUsage(oid, valuex);
        } else if (id.equals("2.16.840.1.113730.1.1")) { //nsCertType
            value = parseNsCertType(oid, valuex);
        } else if (id.equals("2.5.29.37")) { //extendedKeyUsage
            value = parseExtendedKeyUsage(valuex);
        } else {
            value = new DEROctetString(new DEROctetString(ByteList.plain(valuex)).getEncoded(ASN1Encoding.DER));
        }
    } catch (IOException e) {
        throw newExtensionError(runtime, "Unable to create extension: " + e.getMessage());
    }
    return newExtension(runtime, objectId, value, critical.isNil() ? null : critical.isTrue());
}

From source file:org.jruby.ext.openssl.X509ExtensionFactory.java

License:LGPL

private DLSequence parseAuthorityKeyIdentifier(final ThreadContext context, final String valuex) {
    final ASN1EncodableVector vec = new ASN1EncodableVector();
    if (valuex.startsWith("keyid:always")) {
        vec.add(new DEROctetString(derDigest(context)));
    } else if (valuex.startsWith("keyid")) {
        vec.add(new DEROctetString(derDigest(context)));
    }/*from   ww w  .j  a v  a2 s . c  om*/
    return new DLSequence(vec);
}

From source file:org.jruby.ext.openssl.X509ExtensionFactory.java

License:LGPL

private static ASN1Encodable parseSubjectAltName(final String valuex) throws IOException {
    if (valuex.startsWith(DNS_)) {
        final String dns = valuex.substring(DNS_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }/* ww w  . j av a  2  s  .  co m*/
    if (valuex.startsWith(DNS_Name_)) {
        final String dns = valuex.substring(DNS_Name_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }
    if (valuex.startsWith(URI_)) {
        final String uri = valuex.substring(URI_.length());
        return new GeneralName(GeneralName.uniformResourceIdentifier, uri);
    }
    if (valuex.startsWith(RID_)) {
        final String rid = valuex.substring(RID_.length());
        return new GeneralName(GeneralName.registeredID, rid);
    }
    if (valuex.startsWith(email_)) {
        final String mail = valuex.substring(email_.length());
        return new GeneralName(GeneralName.rfc822Name, mail);
    }
    if (valuex.startsWith("IP:") || valuex.startsWith("IP Address:")) {
        final int idx = valuex.charAt(2) == ':' ? 3 : 11;
        String[] vals = valuex.substring(idx).split("\\.|::");
        final byte[] ip = new byte[vals.length];
        for (int i = 0; i < vals.length; i++) {
            ip[i] = (byte) (Integer.parseInt(vals[i]) & 0xff);
        }
        return new GeneralName(GeneralName.iPAddress, new DEROctetString(ip));
    }
    if (valuex.startsWith("other")) { // otherName || othername
        final String other = valuex.substring(otherName_.length());
        return new GeneralName(GeneralName.otherName, other);
    }
    if (valuex.startsWith("dir")) { // dirName || dirname
        final String dir = valuex.substring(dirName_.length());
        return new GeneralName(GeneralName.directoryName, dir);
    }

    throw new IOException("could not parse SubjectAltName: " + valuex);

}

From source file:org.jruby.ext.openssl.X509ExtensionFactory.java

License:LGPL

private DEROctetString parseSubjectKeyIdentifier(final ThreadContext context, final String oid,
        final String valuex) {
    if ("hash".equalsIgnoreCase(valuex)) {
        return new DEROctetString(derDigest(context));
    }//  www  .  jav  a2s.c o m
    if (valuex.length() == 20 || !isHex(valuex)) {
        return new DEROctetString(ByteList.plain(valuex));
    }

    final int len = valuex.length();
    final ByteList hex = new ByteList(len / 2 + 1);
    for (int i = 0; i < len; i += 2) {
        if (i + 1 >= len) {
            throw newExtensionError(context.runtime, oid + " = " + valuex + ": odd number of digits");
        }
        final int c1 = upHex(valuex.charAt(i));
        final int c2 = upHex(valuex.charAt(i + 1));
        if (c1 != -1 && c2 != -1) {
            hex.append(((c1 << 4) & 0xF0) | (c2 & 0xF));
        } else {
            throw newExtensionError(context.runtime, oid + " = " + valuex + ": illegal hex digit");
        }
        while ((i + 2) < len && valuex.charAt(i + 2) == ':') {
            i++;
        }
    }
    final byte[] hexBytes = new byte[hex.length()];
    System.arraycopy(hex.getUnsafeBytes(), hex.getBegin(), hexBytes, 0, hexBytes.length);
    return new DEROctetString(hexBytes);
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

public void writeX509Aux(Writer _out, X509AuxCertificate obj) throws IOException {
    BufferedWriter out = makeBuffered(_out);
    byte[] encoding = null;
    try {/*  w  ww .  j  a  va2  s .  c  om*/
        if (obj.getAux() == null) {
            encoding = obj.getEncoded();
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] ymp = obj.getEncoded();
            baos.write(ymp, 0, ymp.length);

            X509Aux aux = obj.getAux();
            ASN1EncodableVector a1 = new ASN1EncodableVector();
            if (aux.trust.size() > 0) {
                ASN1EncodableVector a2 = new ASN1EncodableVector();
                for (String trust : aux.trust) {
                    a2.add(new DERObjectIdentifier(trust));
                }
                a1.add(new DERSequence(a2));
            }
            if (aux.reject.size() > 0) {
                ASN1EncodableVector a2 = new ASN1EncodableVector();
                for (String reject : aux.reject) {
                    a2.add(new DERObjectIdentifier(reject));
                }
                a1.add(new DERTaggedObject(0, new DERSequence(a2)));
            }
            if (aux.alias != null) {
                a1.add(new DERUTF8String(aux.alias));
            }
            if (aux.keyid != null) {
                a1.add(new DEROctetString(aux.keyid));
            }
            if (aux.other.size() > 0) {
                ASN1EncodableVector a2 = new ASN1EncodableVector();
                for (DERObject other : aux.other) {
                    a2.add(other);
                }
                a1.add(new DERTaggedObject(1, new DERSequence(a2)));
            }
            ymp = new DERSequence(a1).getEncoded();
            baos.write(ymp, 0, ymp.length);
            encoding = baos.toByteArray();
        }
    } catch (CertificateEncodingException e) {
        throw new IOException("problem with encoding object in write_X509_AUX");
    }
    out.write(BEF_G + PEM_STRING_X509_TRUSTED + AFT);
    out.newLine();
    writeEncoded(out, encoding);
    out.write(BEF_E + PEM_STRING_X509_TRUSTED + AFT);
    out.newLine();
    out.flush();
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

public static void writeX509Aux(Writer _out, X509AuxCertificate obj) throws IOException {
    BufferedWriter out = makeBuffered(_out);
    byte[] encoding = null;
    try {//from w ww  .j  a v  a2  s .  c  o m
        if (obj.getAux() == null) {
            encoding = obj.getEncoded();
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] ymp = obj.getEncoded();
            baos.write(ymp, 0, ymp.length);

            X509Aux aux = obj.getAux();
            ASN1EncodableVector a1 = new ASN1EncodableVector();
            if (aux.trust.size() > 0) {
                ASN1EncodableVector a2 = new ASN1EncodableVector();
                for (String trust : aux.trust) {
                    a2.add(new ASN1ObjectIdentifier(trust));
                }
                a1.add(new DLSequence(a2));
            }
            if (aux.reject.size() > 0) {
                ASN1EncodableVector a2 = new ASN1EncodableVector();
                for (String reject : aux.reject) {
                    a2.add(new ASN1ObjectIdentifier(reject));
                }
                a1.add(new DERTaggedObject(0, new DLSequence(a2)));
            }
            if (aux.alias != null) {
                a1.add(new DERUTF8String(aux.alias));
            }
            if (aux.keyid != null) {
                a1.add(new DEROctetString(aux.keyid));
            }
            if (aux.other.size() > 0) {
                ASN1EncodableVector a2 = new ASN1EncodableVector();
                for (ASN1Primitive other : aux.other) {
                    a2.add(other);
                }
                a1.add(new DERTaggedObject(1, new DLSequence(a2)));
            }
            ymp = new DLSequence(a1).getEncoded();
            baos.write(ymp, 0, ymp.length);
            encoding = baos.toByteArray();
        }
    } catch (CertificateEncodingException e) {
        throw new IOException("problem with encoding object in write_X509_AUX");
    }
    out.write(BEF_G + PEM_STRING_X509_TRUSTED + AFT);
    out.newLine();
    writeEncoded(out, encoding);
    out.write(BEF_E + PEM_STRING_X509_TRUSTED + AFT);
    out.newLine();
    out.flush();
}

From source file:org.jscep.message.PkiMessage.java

License:Open Source License

ASN1Set toSet(Nonce nonce) {
    return new DERSet(new DEROctetString(nonce.getBytes()));
}

From source file:org.keycloak.common.util.OCSPUtils.java

License:Apache License

/**
 * Requests certificate revocation status using OCSP.
 * @param cert the certificate to be checked
 * @param issuerCertificate the issuer certificate
 * @param responderURIs the OCSP responder URIs
 * @param responderCert the OCSP responder certificate
 * @param date if null, the current time is used.
 * @return a revocation status/*from   www  .  j  a va  2s  .c  o  m*/
 * @throws CertPathValidatorException
 */
private static OCSPRevocationStatus check(X509Certificate cert, X509Certificate issuerCertificate,
        List<URI> responderURIs, X509Certificate responderCert, Date date) throws CertPathValidatorException {
    if (responderURIs == null || responderURIs.size() == 0)
        throw new IllegalArgumentException("Need at least one responder");
    try {
        DigestCalculator digCalc = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));

        JcaCertificateID certificateID = new JcaCertificateID(digCalc, issuerCertificate,
                cert.getSerialNumber());

        // Create a nounce extension to protect against replay attacks
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger nounce = BigInteger.valueOf(Math.abs(random.nextInt()));

        DEROctetString derString = new DEROctetString(nounce.toByteArray());
        Extension nounceExtension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, derString);
        Extensions extensions = new Extensions(nounceExtension);

        OCSPReq ocspReq = new OCSPReqBuilder().addRequest(certificateID, extensions).build();

        URI responderURI = responderURIs.get(0);
        logger.log(Level.INFO, "OCSP Responder {0}", responderURI);

        try {
            OCSPResp resp = getResponse(ocspReq, responderURI);
            logger.log(Level.FINE, "Received a response from OCSP responder {0}, the response status is {1}",
                    new Object[] { responderURI, resp.getStatus() });
            switch (resp.getStatus()) {
            case OCSPResp.SUCCESSFUL:
                if (resp.getResponseObject() instanceof BasicOCSPResp) {
                    return processBasicOCSPResponse(issuerCertificate, responderCert, date, certificateID,
                            nounce, (BasicOCSPResp) resp.getResponseObject());
                } else {
                    throw new CertPathValidatorException(
                            "OCSP responder returned an invalid or unknown OCSP response.");
                }

            case OCSPResp.INTERNAL_ERROR:
            case OCSPResp.TRY_LATER:
                throw new CertPathValidatorException(
                        "Internal error/try later. OCSP response error: " + resp.getStatus(), (Throwable) null,
                        (CertPath) null, -1,
                        CertPathValidatorException.BasicReason.UNDETERMINED_REVOCATION_STATUS);

            case OCSPResp.SIG_REQUIRED:
                throw new CertPathValidatorException(
                        "Invalid or missing signature. OCSP response error: " + resp.getStatus(),
                        (Throwable) null, (CertPath) null, -1,
                        CertPathValidatorException.BasicReason.INVALID_SIGNATURE);

            case OCSPResp.UNAUTHORIZED:
                throw new CertPathValidatorException(
                        "Unauthorized request. OCSP response error: " + resp.getStatus(), (Throwable) null,
                        (CertPath) null, -1, CertPathValidatorException.BasicReason.UNSPECIFIED);

            case OCSPResp.MALFORMED_REQUEST:
            default:
                throw new CertPathValidatorException(
                        "OCSP request is malformed. OCSP response error: " + resp.getStatus(), (Throwable) null,
                        (CertPath) null, -1, CertPathValidatorException.BasicReason.UNSPECIFIED);
            }
        } catch (IOException e) {
            logger.log(Level.FINE, "OCSP Responder \"{0}\" failed to return a valid OCSP response\n{1}",
                    new Object[] { responderURI, e.getMessage() });
            throw new CertPathValidatorException("OCSP check failed", e);
        }
    } catch (CertificateNotYetValidException | CertificateExpiredException | OperatorCreationException
            | OCSPException | CertificateEncodingException | NoSuchAlgorithmException
            | NoSuchProviderException e) {
        logger.log(Level.FINE, e.getMessage());
        throw new CertPathValidatorException(e.getMessage(), e);
    }
}