Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

In this page you can find the example usage for java.lang SecurityException SecurityException.

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.apache.camel.component.box.internal.LoginAuthFlowUI.java

@SuppressWarnings("deprecation")
@Override/* ww w .j  a  v a 2s  .c o  m*/
public void authenticate(IAuthFlowListener listener) {

    // TODO run this on an Executor to make it async

    // create HtmlUnit client
    final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
    final WebClientOptions options = webClient.getOptions();
    options.setRedirectEnabled(true);
    options.setJavaScriptEnabled(false);
    options.setThrowExceptionOnFailingStatusCode(true);
    options.setThrowExceptionOnScriptError(true);
    options.setPrintContentOnFailingStatusCode(LOG.isDebugEnabled());

    // add HTTP proxy if set
    final Map<String, Object> httpParams = configuration.getHttpParams();
    if (httpParams != null && httpParams.get(ConnRoutePNames.DEFAULT_PROXY) != null) {
        final HttpHost proxyHost = (HttpHost) httpParams.get(ConnRoutePNames.DEFAULT_PROXY);
        final Boolean socksProxy = (Boolean) httpParams.get("http.route.socks-proxy");
        final ProxyConfig proxyConfig = new ProxyConfig(proxyHost.getHostName(), proxyHost.getPort(),
                socksProxy != null ? socksProxy : false);
        options.setProxyConfig(proxyConfig);
    }

    // authorize application on user's behalf
    try {
        final String csrfId = String.valueOf(new SecureRandom().nextLong());

        OAuthWebViewData viewData = new OAuthWebViewData(boxClient.getOAuthDataController());
        viewData.setOptionalState(String.valueOf(csrfId));
        final HtmlPage authPage = webClient.getPage(viewData.buildUrl().toString());

        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("login_form");
        final HtmlTextInput login = loginForm.getInputByName("login");
        login.setText(configuration.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("password");
        password.setText(configuration.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("login_submit");

        // submit consent
        final HtmlPage consentPage = submitInput.click();
        final HtmlForm consentForm = consentPage.getFormByName("consent_form");
        final HtmlButton consentAccept = consentForm.getButtonByName("consent_accept");

        // disable redirect to avoid loading redirect URL
        webClient.getOptions().setRedirectEnabled(false);

        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = consentAccept.click();
            redirectQuery = redirectPage.getUrl().getQuery();
        } catch (FailingHttpStatusCodeException e) {
            // escalate non redirect errors
            if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw e;
            }
            final String location = e.getResponse().getResponseHeaderValue("Location");
            redirectQuery = location.substring(location.indexOf('?') + 1);
        }
        final Map<String, String> params = new HashMap<String, String>();
        final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery);
        while (matcher.find()) {
            params.put(matcher.group(1), matcher.group(2));
        }
        final String state = params.get("state");
        if (!csrfId.equals(state)) {
            final SecurityException e = new SecurityException("Invalid CSRF code!");
            listener.onAuthFlowException(e);
            this.listener.onAuthFlowException(e);
        } else {

            // get authorization code
            final String authorizationCode = params.get("code");

            // get OAuth token
            final IBoxOAuthManager oAuthManager = boxClient.getOAuthManager();
            final BoxOAuthToken oAuthToken = oAuthManager.createOAuth(authorizationCode,
                    configuration.getClientId(), configuration.getClientSecret(), null);

            // send initial token to BoxClient and this.listener
            final OAuthDataMessage authDataMessage = new OAuthDataMessage(oAuthToken, boxClient.getJSONParser(),
                    boxClient.getResourceHub());
            listener.onAuthFlowEvent(OAuthEvent.OAUTH_CREATED, authDataMessage);
            this.listener.onAuthFlowEvent(OAuthEvent.OAUTH_CREATED, authDataMessage);
        }

    } catch (Exception e) {
        // forward login exceptions to listener
        listener.onAuthFlowException(e);
        this.listener.onAuthFlowException(e);
    }
}

From source file:be.fedict.eid.applet.service.impl.handler.SignatureDataMessageHandler.java

public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    LOG.debug("signature data message received");

    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }/*from   w w  w  . java2  s  .c o  m*/
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());

    for (X509Certificate certificate : certificateChain) {
        LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal());

    }
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    /*
     * Verify the signature.
     */
    String digestAlgo = SignatureDataMessageHandler.getDigestAlgo(session);
    byte[] expectedDigestValue = SignatureDataMessageHandler.getDigestValue(session);
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.signatureError(remoteAddress, signingCertificate);
                }
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        String userId = UserIdentifierUtil.getUserId(signingCertificate);
        auditService.signed(userId);
    }

    SignatureService signatureService = this.signatureServiceLocator.locateService();
    try {
        signatureService.setHttpSessionObject(request.getSession());
        signatureService.postSign(signatureValue, certificateChain);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    } catch (Exception e) {
        /*
         * We don't want to depend on the full JavaEE profile in this
         * artifact.
         */
        if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
            Exception exception;
            try {
                Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                        new Class[] {});
                exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
            } catch (Exception e2) {
                LOG.debug("error: " + e.getMessage(), e);
                throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
            }
            if (exception instanceof ExpiredCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
            }
            if (exception instanceof RevokedCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
            }
            if (exception instanceof TrustCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
            }
            if (exception instanceof CertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE);
            }
        }
        throw new SecurityException("signature service error: " + e.getMessage(), e);
    }

    return new FinishedMessage();
}

From source file:net.lightbody.bmp.proxy.jetty.util.URLResource.java

/**
 * Rename the given resource//from w ww. j a  v a  2  s  . c  om
 */
public boolean renameTo(Resource dest) throws SecurityException {
    throw new SecurityException("RenameTo not supported");
}

From source file:fr.gael.dhus.service.SystemService.java

@PreAuthorize("hasRole('ROLE_SYSTEM_MANAGER')")
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void changeRootPassword(String new_pwd, String old_pwd) {
    User root = userDao.getByName(cfgManager.getAdministratorConfiguration().getName());
    PasswordEncryption encryption = root.getPasswordEncryption();
    if (encryption != PasswordEncryption.NONE) {
        try {/*from  w  ww.  j  av a  2 s. co m*/
            MessageDigest md = MessageDigest.getInstance(encryption.getAlgorithmKey());
            old_pwd = new String(Hex.encode(md.digest(old_pwd.getBytes("UTF-8"))));
        } catch (Exception e) {
            throw new UserBadEncryptionException("There was an error while encrypting password of root user",
                    e);
        }
    }
    if ((old_pwd == null) || ("".equals(old_pwd)) || (!root.getPassword().equals(old_pwd)))
        throw new SecurityException("Wrong password.");

    if ((new_pwd == null) || "".equals(new_pwd.trim()))
        throw new SecurityException("New password cannot be empty.");

    String password = new_pwd.trim();
    root.setPassword(password);
    userDao.update(root);
}

From source file:com.compomics.pladipus.controller.setup.InstallPladipus.java

/**
 * Queries the user for the valid user login and password
 *
 * @throws IOException//from ww w.ja  v  a  2 s.c  o m
 */
public boolean validateUser() throws IOException {

    JPanel panel = new JPanel(new BorderLayout(5, 5));

    JPanel label = new JPanel(new GridLayout(0, 1, 2, 2));
    label.add(new JLabel("Username", SwingConstants.RIGHT));
    label.add(new JLabel("Password", SwingConstants.RIGHT));
    panel.add(label, BorderLayout.WEST);

    JPanel controls = new JPanel(new GridLayout(0, 1, 2, 2));
    JTextField username = new JTextField();
    controls.add(username);
    JPasswordField password = new JPasswordField();
    controls.add(password);

    panel.add(controls, BorderLayout.CENTER);

    int showConfirmDialog = JOptionPane.showConfirmDialog(null, panel, "Pladipus Login",
            JOptionPane.OK_CANCEL_OPTION);

    if (showConfirmDialog == JOptionPane.CANCEL_OPTION) {
        return false;
    }

    String user = username.getText();
    String pass = new String(password.getPassword());

    if (login(user, pass)) {
        writeWorkerBash(user, pass);
        return true;
    } else {
        throw new SecurityException("User credentials are incorrect!");
    }
}

From source file:com.edgenius.wiki.security.strategy.PatternStrategy.java

public List<Policy> getPolicies(RESOURCE_TYPES type, String... args) {
    List<Policy> policies = null;
    if (type == RESOURCE_TYPES.SPACE) {
        if (args.length < 1)
            throw new SecurityException(
                    "Failed get space level policy without enough parameters : " + Arrays.toString(args));
        //need spaceUname
        policies = getSpacePolicies(args[0]);
    } else if (type == RESOURCE_TYPES.PAGE) {
        if (args.length < 2)
            throw new SecurityException(
                    "Failed get page level policy without enough parameters : " + Arrays.toString(args));
        //need spaceUname, pageUuid
        policies = getPagePolicies(args[0], args[1]);
    } else if (type == RESOURCE_TYPES.INSTANCE) {
        policies = getInstancePolicies();
    } else if (type == RESOURCE_TYPES.WIDGET) {
        policies = getWidgetPolicies(args[0]);
    }/*w  ww .  j  a v  a2s.  c  o  m*/

    return policies;
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * keystore?/*from  w  w w  .j av  a 2 s.com*/
 * 
 * @return X509Certificate ?
 */
public static X509Certificate getCertFromKeystore(InputStream keystoreInputStream, String alias,
        String password) {
    try {
        X509Certificate x509cert = null;
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(keystoreInputStream, password.toCharArray());
        x509cert = (X509Certificate) ks.getCertificate(alias);
        return x509cert;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}

From source file:it.greenvulcano.gvesb.gviamx.service.internal.SignUpManager.java

public SignUpRequest retrieveSignUpRequest(String email, String token) {

    SignUpRequest signupRequest = signupRepository.get(email.toLowerCase(), SignUpRequest.class)
            .orElseThrow(() -> new IllegalArgumentException("No sign-up request found for this email"));

    if (DigestUtils.sha256Hex(token).equals(signupRequest.getToken())) {

        if (System.currentTimeMillis() > signupRequest.getIssueTime().getTime()
                + signupRequest.getExpireTime()) {
            signupRepository.remove(signupRequest);
            throw new IllegalArgumentException("No sign-up request found for this email");
        }/*from w w  w  . j  a  va2 s. c om*/

        return signupRequest;

    } else {
        throw new SecurityException("Token missmatch");
    }

}

From source file:be.e_contract.mycarenet.etee.Unsealer.java

@SuppressWarnings("unchecked")
private byte[] decrypt(byte[] encryptedData) throws CMSException, IOException {
    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(encryptedData);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    RecipientId recipientId = new JceKeyTransRecipientId(this.decryptionCertificate);
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients(recipientId);
    LOG.debug("number of recipients for given decryption cert: " + recipients.size());
    if (0 == recipients.size()) {
        recipients = recipientInformationStore.getRecipients();
        LOG.debug("number of all recipients: " + recipients.size());
        Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
        while (recipientsIterator.hasNext()) {
            RecipientInformation recipientInformation = recipientsIterator.next();
            RecipientId actualRecipientId = recipientInformation.getRID();
            LOG.debug("actual recipient id type: " + actualRecipientId.getClass().getName());
            if (actualRecipientId instanceof KeyTransRecipientId) {
                KeyTransRecipientId actualKeyTransRecipientId = (KeyTransRecipientId) actualRecipientId;
                LOG.debug("actual recipient issuer: " + actualKeyTransRecipientId.getIssuer());
                LOG.debug("actual recipient serial number: " + actualKeyTransRecipientId.getSerialNumber());
            }//www .j a v a  2 s  . c  o  m
        }
        throw new SecurityException("message does not seem to be addressed to you");
    }
    Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
    RecipientInformation recipientInformation = recipientsIterator.next();

    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(this.decryptionPrivateKey.getEncoded());
    BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams);
    byte[] decryptedContent = recipientInformation.getContent(recipient);
    return decryptedContent;
}

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

private byte[] getCmsData(byte[] cms) throws Exception {
    CMSSignedData cmsSignedData = new CMSSignedData(cms);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);

    X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
    // we trust SSL here, no need for explicit verification of CMS signing
    // certificate

    LOG.debug("CMS signing certificate subject: " + certificate.getSubjectX500Principal());

    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(certificate);/*from   w w w. j a  v a2 s  .  c  o m*/
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] responseData = (byte[]) signedContent.getContent();

    return responseData;
}