Example usage for org.bouncycastle.jce.netscape NetscapeCertRequest verify

List of usage examples for org.bouncycastle.jce.netscape NetscapeCertRequest verify

Introduction

In this page you can find the example usage for org.bouncycastle.jce.netscape NetscapeCertRequest verify.

Prototype

public boolean verify(String challenge)
            throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException 

Source Link

Usage

From source file:org.cesecore.certificates.certificate.request.RequestMessageUtils.java

License:Open Source License

public static RequestMessage getSimpleRequestMessageFromType(final String username, final String password,
        final String req, final int reqType) throws SignRequestSignatureException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, IOException, SignatureException,
        InvalidKeySpecException, ParseException, ConstructionException, NoSuchFieldException {
    RequestMessage ret = null;//from   w  w w  . j  ava2s . c  o m
    if (reqType == CertificateConstants.CERT_REQ_TYPE_PKCS10) {
        final RequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes());
        final PublicKey pubKey = pkcs10req.getRequestPublicKey();
        SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password);
        final Extensions ext = pkcs10req.getRequestExtensions();
        simplereq.setRequestExtensions(ext);
        ret = simplereq;
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_SPKAC) {
        byte[] reqBytes = req.getBytes();
        if (reqBytes != null) {
            if (log.isDebugEnabled()) {
                log.debug("Received NS request: " + new String(reqBytes));
            }
            byte[] buffer = Base64.decode(reqBytes);
            if (buffer == null) {
                return null;
            }
            ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer));
            ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject();
            in.close();
            NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq);
            // Verify POPO, we don't care about the challenge, it's not important.
            nscr.setChallenge("challenge");
            if (nscr.verify("challenge") == false) {
                if (log.isDebugEnabled()) {
                    log.debug("SPKAC POPO verification Failed");
                }
                throw new SignRequestSignatureException(
                        "Invalid signature in NetscapeCertRequest, popo-verification failed.");
            }
            if (log.isDebugEnabled()) {
                log.debug("POPO verification successful");
            }
            PublicKey pubKey = nscr.getPublicKey();
            ret = new SimpleRequestMessage(pubKey, username, password);
        }
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CRMF) {
        byte[] request = Base64.decode(req.getBytes());
        ASN1InputStream in = new ASN1InputStream(request);
        try {
            ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject();
            ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0);
            CertRequest certReq = CertRequest.getInstance(reqSeq);
            SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey();
            KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
            KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded());
            PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok
            SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password);
            Extensions ext = certReq.getCertTemplate().getExtensions();
            simplereq.setRequestExtensions(ext);
            ret = simplereq;
        } finally {
            in.close();
        }
        // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class
        //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject());
        //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null);
        //imsg = reqmsg;
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_PUBLICKEY) {
        byte[] request;
        // Request can be Base64 encoded or in PEM format
        try {
            request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY,
                    CertTools.END_PUBLIC_KEY);
        } catch (IOException ex) {
            try {
                request = Base64.decode(req.getBytes());
                if (request == null) {
                    throw new IOException("Base64 decode of buffer returns null");
                }
            } catch (DecoderException de) {
                throw new IOException("Base64 decode fails, message not base64 encoded: " + de.getMessage());
            }
        }
        final PublicKey pubKey = KeyTools.getPublicKeyFromBytes(request);
        ret = new SimpleRequestMessage(pubKey, username, password);
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CVC) {
        CVCObject parsedObject = CertificateParser.parseCVCObject(Base64.decode(req.getBytes()));
        // We will handle both the case if the request is an authenticated request, i.e. with an outer signature
        // and when the request is missing the (optional) outer signature.
        CVCertificate cvccert = null;
        if (parsedObject instanceof CVCAuthenticatedRequest) {
            CVCAuthenticatedRequest cvcreq = (CVCAuthenticatedRequest) parsedObject;
            cvccert = cvcreq.getRequest();
        } else {
            cvccert = (CVCertificate) parsedObject;
        }
        CVCRequestMessage reqmsg = new CVCRequestMessage(cvccert.getDEREncoded());
        reqmsg.setUsername(username);
        reqmsg.setPassword(password);
        // Popo is really actually verified by the CA (in SignSessionBean) as well
        if (reqmsg.verify() == false) {
            if (log.isDebugEnabled()) {
                log.debug("CVC POPO verification Failed");
            }
            throw new SignRequestSignatureException(
                    "Invalid inner signature in CVCRequest, popo-verification failed.");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("POPO verification successful");
            }
        }
        ret = reqmsg;
    }
    return ret;
}

From source file:org.ejbca.core.ejb.ra.CertificateRequestSessionBean.java

License:Open Source License

@Override
public byte[] processCertReq(Admin admin, UserDataVO userdata, String req, int reqType, String hardTokenSN,
        int responseType) throws CADoesntExistsException, AuthorizationDeniedException, NotFoundException,
        InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException,
        SignatureException, IOException, ObjectNotFoundException, CertificateException,
        UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException {
    byte[] retval = null;

    // Check tokentype
    if (userdata.getTokenType() != SecConst.TOKEN_SOFT_BROWSERGEN) {
        throw new WrongTokenTypeException(
                "Error: Wrong Token Type of user, must be 'USERGENERATED' for PKCS10/SPKAC/CRMF/CVC requests");
    }//ww w  .j  a  v a 2 s.c om
    // This is the secret sauce, do the end entity handling automagically here before we get the cert
    addOrEditUser(admin, userdata, false, true);
    // Process request
    try {
        String password = userdata.getPassword();
        String username = userdata.getUsername();
        IRequestMessage imsg = null;
        if (reqType == SecConst.CERT_REQ_TYPE_PKCS10) {
            IRequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes());
            PublicKey pubKey = pkcs10req.getRequestPublicKey();
            imsg = new SimpleRequestMessage(pubKey, username, password);
        } else if (reqType == SecConst.CERT_REQ_TYPE_SPKAC) {
            // parts copied from request helper.
            byte[] reqBytes = req.getBytes();
            if (reqBytes != null) {
                log.debug("Received NS request: " + new String(reqBytes));
                byte[] buffer = Base64.decode(reqBytes);
                if (buffer == null) {
                    return null;
                }
                ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer));
                ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject();
                in.close();
                NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq);
                // Verify POPO, we don't care about the challenge, it's not important.
                nscr.setChallenge("challenge");
                if (nscr.verify("challenge") == false) {
                    log.debug("POPO verification Failed");
                    throw new SignRequestSignatureException(
                            "Invalid signature in NetscapeCertRequest, popo-verification failed.");
                }
                log.debug("POPO verification successful");
                PublicKey pubKey = nscr.getPublicKey();
                imsg = new SimpleRequestMessage(pubKey, username, password);
            }
        } else if (reqType == SecConst.CERT_REQ_TYPE_CRMF) {
            byte[] request = Base64.decode(req.getBytes());
            ASN1InputStream in = new ASN1InputStream(request);
            ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject();
            ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0);
            CertRequest certReq = new CertRequest(reqSeq);
            SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey();
            KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
            KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded());
            PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok
            imsg = new SimpleRequestMessage(pubKey, username, password);
            // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class
            //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject());
            //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null);
            //imsg = reqmsg;
        } else if (reqType == SecConst.CERT_REQ_TYPE_PUBLICKEY) {
            byte[] request;
            // Request can be Base64 encoded or in PEM format
            try {
                request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY,
                        CertTools.END_PUBLIC_KEY);
            } catch (IOException ex) {
                try {
                    request = Base64.decode(req.getBytes());
                    if (request == null) {
                        throw new IOException("Base64 decode of buffer returns null");
                    }
                } catch (ArrayIndexOutOfBoundsException ae) {
                    throw new IOException(
                            "Base64 decode fails, message not base64 encoded: " + ae.getMessage());
                }
            }
            final ASN1InputStream in = new ASN1InputStream(request);
            final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject());
            final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithmId();
            final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes());
            final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getObjectId().getId(), "BC");
            final PublicKey pubKey = keyFact.generatePublic(xKeySpec);
            imsg = new SimpleRequestMessage(pubKey, username, password);
        }
        if (imsg != null) {
            retval = getCertResponseFromPublicKey(admin, imsg, hardTokenSN, responseType, userdata);
        }
    } catch (NotFoundException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (InvalidKeyException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (NoSuchAlgorithmException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (InvalidKeySpecException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (NoSuchProviderException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (SignatureException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (IOException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (CertificateException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (EjbcaException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    }
    return retval;
}

From source file:org.ejbca.externalra.gui.EnrollInterfaceBean.java

License:Open Source License

/**
 * Action that requests a certificate from EJBCA using the given credentials and the Certificate Signing Request created by the browser.
 */// w ww.  j a va2 s  . c o  m
public void createCertFromBrowser() {
    log.info("Recieved a browser generated certificate request of type " + certificateRequestType
            + " for username '" + username + "' from " + getRemoteAddress());
    if (log.isDebugEnabled()) {
        log.debug("certificateRequest: " + certificateRequest);
    }
    FacesContext context = FacesContext.getCurrentInstance();
    if (username == null || username.length() == 0 || password == null || password.length() == 0
            || certificateRequest == null || certificateRequest.length() == 0 || certificateRequestType == null
            || certificateRequestType.length() == 0) {
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.incompletefields"), null));
        return;
    }
    // Verify that we got a valid certificate request and determine response type
    byte[] buf = null;
    int requestType = Integer.parseInt(certificateRequestType);
    int responseType;
    switch (requestType) {
    case CertificateRequestRequest.REQUEST_TYPE_CRMF:
        responseType = CertificateRequestRequest.RESPONSE_TYPE_PKCS7;
        buf = Base64.decode(certificateRequest.getBytes());
        ASN1InputStream asn1InputStream = new ASN1InputStream(buf);
        try {
            // Verify that we can parse this as a CRMF object
            CertReqMessages.getInstance(asn1InputStream.readObject()).getCertReqMsg(0);
        } catch (IOException e) {
            context.addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.invalidreqdata"), null));
            log.error("", e);
        }
        break;
    case CertificateRequestRequest.REQUEST_TYPE_PKCS10:
        responseType = CertificateRequestRequest.RESPONSE_TYPE_PKCS7;
        try {
            if (!isWindowsNT5()) {
                responseType = CertificateRequestRequest.RESPONSE_TYPE_UNSIGNEDPKCS7;
            }
            // Replace Vista PEM markers
            certificateRequest = certificateRequest.replaceAll(PEM_CSR_BEGIN_VISTA, PEM_CSR_BEGIN);
            certificateRequest = certificateRequest.replaceAll(PEM_CSR_END_VISTA, PEM_CSR_END);
            if (certificateRequest.indexOf(PEM_CSR_BEGIN) == -1) {
                certificateRequest = PEM_CSR_BEGIN + "\n" + certificateRequest + "\n" + PEM_CSR_END;
            }
            buf = FileTools.getBytesFromPEM(certificateRequest.getBytes(), PEM_CSR_BEGIN, PEM_CSR_END);
            new PKCS10CertificationRequest(buf);
        } catch (Exception e) {
            log.error("", e);
            context.addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.invalidreqdata"), null));
            return;
        }
        break;
    case CertificateRequestRequest.REQUEST_TYPE_KEYGEN:
        responseType = CertificateRequestRequest.RESPONSE_TYPE_PKCS7;
        try {
            buf = Base64.decode(certificateRequest.getBytes());
            ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buf));
            ASN1Sequence spkac = (ASN1Sequence) in.readObject();
            in.close();
            NetscapeCertRequest nscr = new NetscapeCertRequest(spkac);
            // Verify POPO, we don't care about the challenge, it's not important.
            nscr.setChallenge("challenge");
            if (nscr.verify("challenge") == false) {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        getMessage("enroll.invalidreqdata"), null));
                return;
            }
        } catch (Exception e) {
            log.error("", e);
            context.addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.invalidreqdata"), null));
            return;
        }
        break;
    case -1:
        // This is a workaround to hide errors when we use the KeyGenServlet..
        return;
    default:
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.unknownrequesttype"), null));
        return;
    }
    // Request the certificate from the CA
    if (log.isDebugEnabled()) {
        log.debug("Got requestType " + requestType + " and is expecting responseType " + responseType
                + " for user " + username);
    }
    ResponseData responseData = getRequestDispatcher().getCertificateResponse(username, password, requestType,
            buf, responseType);
    // Check if got a valid result
    if (responseData == null) {
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.noresponse"), null));
        log.error("Certificate request for '" + username + "' failed. No response from CA.");
        return;
    } else if (responseData.getErrorMessage() != null) {
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                getMessage("enroll.browsercert.couldnotcreate"), null));
        log.info("Certificate request for '" + username + "' failed. " + responseData.getErrorMessage());
        return;
    }
    // Handle response
    certificateResponseType = "" + responseData.getResponseType();
    switch (responseData.getResponseType()) {
    case CertificateRequestRequest.RESPONSE_TYPE_PKCS7:
        if (isInternetExplorer()) {
            // Working for XP+IE7
            certificateResponse = new String(Base64.encode(responseData.getResponseData(), false));
        } else {
            resource = new ByteArrayResource(responseData.getResponseData());
            mimeType = "application/x-x509-user-cert";
        }
        break;
    case CertificateRequestRequest.RESPONSE_TYPE_UNSIGNEDPKCS7:
        // Working for Vista+IE8
        certificateResponse = new String(Base64.encode(responseData.getResponseData(), false));
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            String pkcs7 = PEM_PKCS7_BEGIN + "\n"
                    + new String(Base64.encode(responseData.getResponseData(), true)) + "\n" + PEM_PKCS7_END
                    + "\n";
            log.debug("pkcs7=" + pkcs7);
            CertPath certPath = cf.generateCertPath(new ByteArrayInputStream(responseData.getResponseData()),
                    "PKCS7");
            List<? extends Certificate> certList = certPath.getCertificates();
            Certificate caCert = certList.get(certList.size() - 1);
            String caCertificate = new String(Base64.encode(caCert.getEncoded(), false));
            resource = new ByteArrayResource(caCertificate.getBytes());
            mimeType = "application/x-x509-ca-cert";
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        if (log.isDebugEnabled()) {
            log.debug("certificateResponse: " + certificateResponse);
        }
        break;
    default:
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.unknownresponsetype"), null));
        log.error("Unknown result type: " + certificateResponseType);
        break;
    }
    log.info("Certificate request with response-type " + responseData.getResponseType() + " for '" + username
            + "' was successful.");
}

From source file:org.ejbca.ui.web.RequestHelper.java

License:Open Source License

/**
 * Handles Firefox certificate request (KEYGEN), these are constructed as: <code>
 * SignedPublicKeyAndChallenge ::= SEQUENCE { publicKeyAndChallenge    PublicKeyAndChallenge,
 * signatureAlgorithm   AlgorithmIdentifier, signature        BIT STRING }</code> PublicKey's
 * encoded-format has to be RSA X.509.//  w  w w  .  j av  a 2s .co  m
 *
 * @param signsession EJB session to signature bean.
 * @param reqBytes buffer holding te request from NS.
 * @param username username in EJBCA for authoriation.
 * @param password users password for authorization.
 *
 * @return byte[] containing DER-encoded certificate.
 *
 * @throws CesecoreException 
 * @throws AuthorizationDeniedException 
 * @throws EjbcaException 
 * @throws CADoesntExistsException 
 * @throws ObjectNotFoundException 
 * @throws CertificateEncodingException 
 * @throws NoSuchProviderException 
 * @throws SignatureException 
 * @throws NoSuchAlgorithmException 
 * @throws InvalidKeyException 
 */
public byte[] nsCertRequest(SignSessionLocal signsession, byte[] reqBytes, String username, String password)
        throws ObjectNotFoundException, CADoesntExistsException, EjbcaException, AuthorizationDeniedException,
        CesecoreException, CertificateEncodingException, InvalidKeyException, NoSuchAlgorithmException,
        SignatureException, NoSuchProviderException {
    byte[] buffer = Base64.decode(reqBytes);

    if (buffer == null) {
        return null;
    }

    ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer));
    ASN1Sequence spkac;
    try {
        spkac = (ASN1Sequence) in.readObject();
        in.close();
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException was caught.", e);
    }

    NetscapeCertRequest nscr = new NetscapeCertRequest(spkac);

    // Verify POPO, we don't care about the challenge, it's not important.
    nscr.setChallenge("challenge");

    if (nscr.verify("challenge") == false) {
        throw new SignRequestSignatureException(
                "Invalid signature in NetscapeCertRequest, popo-verification failed.");
    }
    if (log.isDebugEnabled()) {
        log.debug("POPO verification successful");
    }
    X509Certificate cert = (X509Certificate) signsession.createCertificate(administrator, username, password,
            nscr.getPublicKey());
    if (log.isDebugEnabled()) {
        log.debug("Created certificate for " + username);
    }
    if (debug != null) {
        debug.print("<h4>Generated certificate:</h4>");
        debug.printInsertLineBreaks(cert.toString().getBytes());
    }
    return cert.getEncoded();

    /* ECA-2065: the <keygen> specification doesn't say anything about the
     * returned certificate.  Originally EJBCA used a PKCS7 container but
     * this has proved to be incompatible with Safari and Chrome.  ECA-2065
     * changes returned data to just a DER-encoded certificate which has
     * been verified to work in Firefox, Chrome and Safari.  The mime-type
     * remains application/x-x509-user-certificate.  Below is the deleted
     * code: 
            // Don't include certificate chain in the PKCS7 to Firefox
            byte[] pkcs7 = signsession.createPKCS7(administrator, cert, false);
            log.debug("Created certificate (PKCS7) for " + username);
            if (debug != null) {
    debug.print("<h4>Generated certificate:</h4>");
    debug.printInsertLineBreaks(cert.toString().getBytes());
            }
            
            return pkcs7;
    */
}