Search in sources :

Example 6 with Request

use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.

the class ESTService method getCSRAttributes.

/**
 * Fetch he CSR Attributes from the server.
 *
 * @return A CSRRequestResponse with the attributes.
 * @throws ESTException
 */
public CSRRequestResponse getCSRAttributes() throws ESTException {
    if (!clientProvider.isTrusted()) {
        throw new IllegalStateException("No trust anchors.");
    }
    ESTResponse resp = null;
    CSRAttributesResponse response = null;
    Exception finalThrowable = null;
    URL url = null;
    try {
        url = new URL(server + CSRATTRS);
        ESTClient client = clientProvider.makeClient();
        ESTRequest req = new ESTRequestBuilder("GET", url).withClient(client).build();
        resp = client.doRequest(req);
        switch(resp.getStatusCode()) {
            case 200:
                try {
                    if (resp.getContentLength() != null && resp.getContentLength() > 0) {
                        ASN1InputStream ain = new ASN1InputStream(resp.getInputStream());
                        ASN1Sequence seq = ASN1Sequence.getInstance(ain.readObject());
                        response = new CSRAttributesResponse(CsrAttrs.getInstance(seq));
                    }
                } catch (Throwable ex) {
                    throw new ESTException("Decoding CACerts: " + url.toString() + " " + ex.getMessage(), ex, resp.getStatusCode(), resp.getInputStream());
                }
                break;
            case 204:
                response = null;
                break;
            case 404:
                response = null;
                break;
            default:
                throw new ESTException("CSR Attribute request: " + req.getURL().toString(), null, resp.getStatusCode(), resp.getInputStream());
        }
    } catch (Throwable t) {
        if (t instanceof ESTException) {
            throw (ESTException) t;
        } else {
            throw new ESTException(t.getMessage(), t);
        }
    } finally {
        if (resp != null) {
            try {
                resp.close();
            } catch (Exception ex) {
                finalThrowable = ex;
            }
        }
    }
    if (finalThrowable != null) {
        if (finalThrowable instanceof ESTException) {
            throw (ESTException) finalThrowable;
        }
        throw new ESTException(finalThrowable.getMessage(), finalThrowable, resp.getStatusCode(), null);
    }
    return new CSRRequestResponse(response, resp.getSource());
}
Also used : ASN1InputStream(com.github.zhenwei.core.asn1.ASN1InputStream) IOException(java.io.IOException) CMCException(com.github.zhenwei.pkix.cmc.CMCException) URL(java.net.URL) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence)

Example 7 with Request

use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.

the class HttpAuth method doDigestFunction.

private ESTResponse doDigestFunction(ESTResponse res) throws IOException {
    // Close off the last request.
    res.close();
    ESTRequest req = res.getOriginalRequest();
    Map<String, String> parts = null;
    try {
        parts = HttpUtil.splitCSL("Digest", res.getHeader("WWW-Authenticate"));
    } catch (Throwable t) {
        throw new ESTException("Parsing WWW-Authentication header: " + t.getMessage(), t, res.getStatusCode(), new ByteArrayInputStream(res.getHeader("WWW-Authenticate").getBytes()));
    }
    String uri = null;
    try {
        uri = req.getURL().toURI().getPath();
    } catch (Exception e) {
        throw new IOException("unable to process URL in request: " + e.getMessage());
    }
    for (Iterator it = parts.keySet().iterator(); it.hasNext(); ) {
        Object k = it.next();
        if (!validParts.contains(k)) {
            throw new ESTException("Unrecognised entry in WWW-Authenticate header: '" + k + "'");
        }
    }
    String method = req.getMethod();
    String realm = parts.get("realm");
    String nonce = parts.get("nonce");
    String opaque = parts.get("opaque");
    String algorithm = parts.get("algorithm");
    String qop = parts.get("qop");
    // Preserve ordering.
    List<String> qopMods = new ArrayList<String>();
    if (this.realm != null) {
        if (!this.realm.equals(realm)) {
            // Not equal then fail.
            throw new ESTException("Supplied realm '" + this.realm + "' does not match server realm '" + realm + "'", null, 401, null);
        }
    }
    // If an algorithm is not specified, default to MD5.
    if (algorithm == null) {
        algorithm = "MD5";
    }
    if (algorithm.length() == 0) {
        throw new ESTException("WWW-Authenticate no algorithm defined.");
    }
    algorithm = Strings.toUpperCase(algorithm);
    if (qop != null) {
        if (qop.length() == 0) {
            throw new ESTException("QoP value is empty.");
        }
        qop = Strings.toLowerCase(qop);
        String[] s = qop.split(",");
        for (int j = 0; j != s.length; j++) {
            if (!s[j].equals("auth") && !s[j].equals("auth-int")) {
                throw new ESTException("QoP value unknown: '" + j + "'");
            }
            String jt = s[j].trim();
            if (qopMods.contains(jt)) {
                continue;
            }
            qopMods.add(jt);
        }
    } else {
        throw new ESTException("Qop is not defined in WWW-Authenticate header.");
    }
    AlgorithmIdentifier digestAlg = lookupDigest(algorithm);
    if (digestAlg == null || digestAlg.getAlgorithm() == null) {
        throw new IOException("auth digest algorithm unknown: " + algorithm);
    }
    DigestCalculator dCalc = getDigestCalculator(algorithm, digestAlg);
    OutputStream dOut = dCalc.getOutputStream();
    // TODO arbitrary?
    String crnonce = makeNonce(10);
    update(dOut, username);
    update(dOut, ":");
    update(dOut, realm);
    update(dOut, ":");
    update(dOut, password);
    dOut.close();
    byte[] ha1 = dCalc.getDigest();
    if (algorithm.endsWith("-SESS")) {
        DigestCalculator sessCalc = getDigestCalculator(algorithm, digestAlg);
        OutputStream sessOut = sessCalc.getOutputStream();
        String cs = Hex.toHexString(ha1);
        update(sessOut, cs);
        update(sessOut, ":");
        update(sessOut, nonce);
        update(sessOut, ":");
        update(sessOut, crnonce);
        sessOut.close();
        ha1 = sessCalc.getDigest();
    }
    String hashHa1 = Hex.toHexString(ha1);
    DigestCalculator authCalc = getDigestCalculator(algorithm, digestAlg);
    OutputStream authOut = authCalc.getOutputStream();
    if (qopMods.get(0).equals("auth-int")) {
        DigestCalculator reqCalc = getDigestCalculator(algorithm, digestAlg);
        OutputStream reqOut = reqCalc.getOutputStream();
        req.writeData(reqOut);
        reqOut.close();
        byte[] b = reqCalc.getDigest();
        update(authOut, method);
        update(authOut, ":");
        update(authOut, uri);
        update(authOut, ":");
        update(authOut, Hex.toHexString(b));
    } else if (qopMods.get(0).equals("auth")) {
        update(authOut, method);
        update(authOut, ":");
        update(authOut, uri);
    }
    authOut.close();
    String hashHa2 = Hex.toHexString(authCalc.getDigest());
    DigestCalculator responseCalc = getDigestCalculator(algorithm, digestAlg);
    OutputStream responseOut = responseCalc.getOutputStream();
    if (qopMods.contains("missing")) {
        update(responseOut, hashHa1);
        update(responseOut, ":");
        update(responseOut, nonce);
        update(responseOut, ":");
        update(responseOut, hashHa2);
    } else {
        update(responseOut, hashHa1);
        update(responseOut, ":");
        update(responseOut, nonce);
        update(responseOut, ":");
        update(responseOut, "00000001");
        update(responseOut, ":");
        update(responseOut, crnonce);
        update(responseOut, ":");
        if (qopMods.get(0).equals("auth-int")) {
            update(responseOut, "auth-int");
        } else {
            update(responseOut, "auth");
        }
        update(responseOut, ":");
        update(responseOut, hashHa2);
    }
    responseOut.close();
    String digest = Hex.toHexString(responseCalc.getDigest());
    Map<String, String> hdr = new HashMap<String, String>();
    hdr.put("username", username);
    hdr.put("realm", realm);
    hdr.put("nonce", nonce);
    hdr.put("uri", uri);
    hdr.put("response", digest);
    if (qopMods.get(0).equals("auth-int")) {
        hdr.put("qop", "auth-int");
        hdr.put("nc", "00000001");
        hdr.put("cnonce", crnonce);
    } else if (qopMods.get(0).equals("auth")) {
        hdr.put("qop", "auth");
        hdr.put("nc", "00000001");
        hdr.put("cnonce", crnonce);
    }
    hdr.put("algorithm", algorithm);
    if (opaque == null || opaque.length() == 0) {
        hdr.put("opaque", makeNonce(20));
    }
    ESTRequestBuilder answer = new ESTRequestBuilder(req).withHijacker(null);
    answer.setHeader("Authorization", HttpUtil.mergeCSL("Digest", hdr));
    return req.getClient().doRequest(answer.build());
}
Also used : HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) DigestCalculator(com.github.zhenwei.pkix.operator.DigestCalculator) IOException(java.io.IOException) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) IOException(java.io.IOException) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) ByteArrayInputStream(java.io.ByteArrayInputStream) Iterator(java.util.Iterator)

Example 8 with Request

use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.

the class Challenge method toASN1Primitive.

/**
 * <pre>
 * Challenge ::= SEQUENCE {
 *                 owf                 AlgorithmIdentifier  OPTIONAL,
 *
 *                 -- MUST be present in the first Challenge; MAY be omitted in
 *                 -- any subsequent Challenge in POPODecKeyChallContent (if
 *                 -- omitted, then the owf used in the immediately preceding
 *                 -- Challenge is to be used).
 *
 *                 witness             OCTET STRING,
 *                 -- the result of applying the one-way function (owf) to a
 *                 -- randomly-generated INTEGER, A.  [Note that a different
 *                 -- INTEGER MUST be used for each Challenge.]
 *                 challenge           OCTET STRING
 *                 -- the encryption (under the public key for which the cert.
 *                 -- request is being made) of Rand, where Rand is specified as
 *                 --   Rand ::= SEQUENCE {
 *                 --      int      INTEGER,
 *                 --       - the randomly-generated INTEGER A (above)
 *                 --      sender   GeneralName
 *                 --       - the sender's name (as included in PKIHeader)
 *                 --   }
 *      }
 * </pre>
 *
 * @return a basic ASN.1 object representation.
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(3);
    addOptional(v, owf);
    v.add(witness);
    v.add(challenge);
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 9 with Request

use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.

the class PKIHeader method toASN1Primitive.

/**
 * <pre>
 *  PKIHeader ::= SEQUENCE {
 *            pvno                INTEGER     { cmp1999(1), cmp2000(2) },
 *            sender              GeneralName,
 *            -- identifies the sender
 *            recipient           GeneralName,
 *            -- identifies the intended recipient
 *            messageTime     [0] GeneralizedTime         OPTIONAL,
 *            -- time of production of this message (used when sender
 *            -- believes that the transport will be "suitable"; i.e.,
 *            -- that the time will still be meaningful upon receipt)
 *            protectionAlg   [1] AlgorithmIdentifier     OPTIONAL,
 *            -- algorithm used for calculation of protection bits
 *            senderKID       [2] KeyIdentifier           OPTIONAL,
 *            recipKID        [3] KeyIdentifier           OPTIONAL,
 *            -- to identify specific keys used for protection
 *            transactionID   [4] OCTET STRING            OPTIONAL,
 *            -- identifies the transaction; i.e., this will be the same in
 *            -- corresponding request, response, certConf, and PKIConf
 *            -- messages
 *            senderNonce     [5] OCTET STRING            OPTIONAL,
 *            recipNonce      [6] OCTET STRING            OPTIONAL,
 *            -- nonces used to provide replay protection, senderNonce
 *            -- is inserted by the creator of this message; recipNonce
 *            -- is a nonce previously inserted in a related message by
 *            -- the intended recipient of this message
 *            freeText        [7] PKIFreeText             OPTIONAL,
 *            -- this may be used to indicate context-specific instructions
 *            -- (this field is intended for human consumption)
 *            generalInfo     [8] SEQUENCE SIZE (1..MAX) OF
 *                                 InfoTypeAndValue     OPTIONAL
 *            -- this may be used to convey context-specific information
 *            -- (this field not primarily intended for human consumption)
 * }
 * </pre>
 *
 * @return a basic ASN.1 object representation.
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(12);
    v.add(pvno);
    v.add(sender);
    v.add(recipient);
    addOptional(v, 0, messageTime);
    addOptional(v, 1, protectionAlg);
    addOptional(v, 2, senderKID);
    addOptional(v, 3, recipKID);
    addOptional(v, 4, transactionID);
    addOptional(v, 5, senderNonce);
    addOptional(v, 6, recipNonce);
    addOptional(v, 7, freeText);
    addOptional(v, 8, generalInfo);
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 10 with Request

use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.

the class CVCertificateRequest method initCertBody.

private void initCertBody(ASN1ApplicationSpecific request) throws IOException {
    if (request.getApplicationTag() == EACTags.CARDHOLDER_CERTIFICATE) {
        int valid = 0;
        ASN1Sequence seq = ASN1Sequence.getInstance(request.getObject(BERTags.SEQUENCE));
        for (Enumeration en = seq.getObjects(); en.hasMoreElements(); ) {
            ASN1ApplicationSpecific obj = ASN1ApplicationSpecific.getInstance(en.nextElement());
            switch(obj.getApplicationTag()) {
                case EACTags.CERTIFICATE_CONTENT_TEMPLATE:
                    certificateBody = CertificateBody.getInstance(obj);
                    valid |= bodyValid;
                    break;
                case EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP:
                    innerSignature = obj.getContents();
                    valid |= signValid;
                    break;
                default:
                    throw new IOException("Invalid tag, not an CV Certificate Request element:" + obj.getApplicationTag());
            }
        }
        if ((valid & (bodyValid | signValid)) == 0) {
            throw new IOException("Invalid CARDHOLDER_CERTIFICATE in request:" + request.getApplicationTag());
        }
    } else {
        throw new IOException("not a CARDHOLDER_CERTIFICATE in request:" + request.getApplicationTag());
    }
}
Also used : ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) Enumeration(java.util.Enumeration) ASN1ApplicationSpecific(com.github.zhenwei.core.asn1.ASN1ApplicationSpecific) IOException(java.io.IOException)

Aggregations

ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)18 DERSequence (com.github.zhenwei.core.asn1.DERSequence)15 IOException (java.io.IOException)14 OutputStream (java.io.OutputStream)6 ArrayList (java.util.ArrayList)6 Iterator (java.util.Iterator)5 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)4 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)4 DERBitString (com.github.zhenwei.core.asn1.DERBitString)4 DERTaggedObject (com.github.zhenwei.core.asn1.DERTaggedObject)4 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)4 OCSPRequest (org.bouncycastle.asn1.ocsp.OCSPRequest)4 Request (org.bouncycastle.asn1.ocsp.Request)4 ASN1GeneralizedTime (com.github.zhenwei.core.asn1.ASN1GeneralizedTime)3 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 URL (java.net.URL)3 BasicOCSPResponse (com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse)2 OCSPRequest (com.github.zhenwei.core.asn1.ocsp.OCSPRequest)2 ResponseData (com.github.zhenwei.core.asn1.ocsp.ResponseData)2