Search in sources :

Example 51 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project substitution-schedule-parser by vertretungsplanme.

the class LoginHandler method handleLogin.

private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse) throws JSONException, IOException, CredentialInvalidException {
    if (auth == null)
        return null;
    if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) {
        throw new IllegalArgumentException("Wrong authentication type");
    }
    String login;
    String password;
    if (auth instanceof UserPasswordCredential) {
        login = ((UserPasswordCredential) auth).getUsername();
        password = ((UserPasswordCredential) auth).getPassword();
    } else {
        login = null;
        password = ((PasswordCredential) auth).getPassword();
    }
    JSONObject data = scheduleData.getData();
    JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG);
    String type = loginConfig.optString(PARAM_TYPE, "post");
    switch(type) {
        case "post":
            List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null;
            String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
            String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
            if (cookieList != null && !needsResponse && !(checkUrl == null && checkText != null)) {
                for (Cookie cookie : cookieList) cookieStore.addCookie(cookie);
                if (checkUrl != null && checkText != null) {
                    try {
                        String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                        if (!response.contains(checkText)) {
                            return null;
                        }
                    } catch (HttpResponseException e) {
                        return null;
                    }
                } else {
                    return null;
                }
            }
            executor.clearCookies();
            Document preDoc = null;
            if (loginConfig.has(PARAM_PRE_URL)) {
                String preUrl = loginConfig.getString(PARAM_PRE_URL);
                String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString();
                preDoc = Jsoup.parse(preHtml);
            }
            String postUrl = loginConfig.getString(PARAM_URL);
            JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA);
            List<NameValuePair> nvps = new ArrayList<>();
            String typo3Challenge = null;
            BigInteger typo3RsaN = null;
            BigInteger typo3RsaE = null;
            if (loginData.has("_hiddeninputs") && preDoc != null) {
                for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) {
                    if (loginData.has(hidden.attr("name")))
                        continue;
                    nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
                    if (hidden.attr("name").equals("challenge")) {
                        typo3Challenge = hidden.attr("value");
                    } else if (hidden.attr("name").equals("n") && hidden.attr("id").equals("rsa_n")) {
                        typo3RsaN = new BigInteger(hidden.attr("value"), 16);
                    } else if (hidden.attr("name").equals("e") && hidden.attr("id").equals("rsa_e")) {
                        typo3RsaE = new BigInteger(hidden.attr("value"), 16);
                    }
                }
            }
            for (String name : JSONObject.getNames(loginData)) {
                String value = loginData.getString(name);
                if (name.equals("_hiddeninputs"))
                    continue;
                switch(value) {
                    case "_login":
                        value = login;
                        break;
                    case "_password":
                        value = password;
                        break;
                    case "_password_md5":
                        value = DigestUtils.md5Hex(password);
                        break;
                    case "_password_md5_typo3":
                        value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge);
                        break;
                    case "_password_rsa_typo3":
                        try {
                            final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                            if (typo3RsaE == null && typo3RsaN == null) {
                                String key = executor.execute(Request.Get(new URL(new URL(postUrl), "/index.php?eID=FrontendLoginRsaPublicKey").toString())).returnContent().asString();
                                typo3RsaN = new BigInteger(key.split(":")[0], 16);
                                typo3RsaE = new BigInteger(key.split(":")[1], 16);
                            }
                            cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(typo3RsaN, typo3RsaE)));
                            byte[] result = cipher.doFinal(password.getBytes());
                            value = "rsa:" + new Base64().encodeAsString(result);
                        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException e) {
                            e.printStackTrace();
                        }
                        break;
                }
                nvps.add(new BasicNameValuePair(name, value));
            }
            Request request = Request.Post(postUrl);
            if (loginConfig.optBoolean("form-data", false)) {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                for (NameValuePair nvp : nvps) {
                    builder.addTextBody(nvp.getName(), nvp.getValue());
                }
                request.body(builder.build());
            } else {
                request.bodyForm(nvps, Charset.forName("UTF-8"));
            }
            String html = executor.execute(request).returnContent().asString();
            if (cookieProvider != null)
                cookieProvider.saveCookies(auth, cookieStore.getCookies());
            if (checkUrl != null && checkText != null) {
                try {
                    String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                    if (response.contains(checkText))
                        throw new CredentialInvalidException();
                } catch (HttpResponseException e) {
                    throw new CredentialInvalidException();
                }
            } else if (checkText != null) {
                if (html.contains(checkText))
                    throw new CredentialInvalidException();
            }
            return html;
        case "basic":
            if (login == null)
                throw new IOException("wrong auth type");
            executor.auth(login, password);
            if (loginConfig.has(PARAM_URL)) {
                String url = loginConfig.getString(PARAM_URL);
                if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                    throw new CredentialInvalidException();
                }
            }
            break;
        case "ntlm":
            if (login == null)
                throw new IOException("wrong auth type");
            executor.auth(login, password, null, null);
            if (loginConfig.has(PARAM_URL)) {
                String url = loginConfig.getString(PARAM_URL);
                if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                    throw new CredentialInvalidException();
                }
            }
            break;
        case "fixed":
            String loginFixed = loginConfig.optString(PARAM_LOGIN, null);
            String passwordFixed = loginConfig.getString(PARAM_PASSWORD);
            if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) {
                throw new CredentialInvalidException();
            }
            break;
    }
    return null;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) Element(org.jsoup.nodes.Element) PasswordCredential(me.vertretungsplan.objects.credential.PasswordCredential) UserPasswordCredential(me.vertretungsplan.objects.credential.UserPasswordCredential) ArrayList(java.util.ArrayList) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) HttpResponseException(org.apache.http.client.HttpResponseException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) UserPasswordCredential(me.vertretungsplan.objects.credential.UserPasswordCredential) Document(org.jsoup.nodes.Document) URL(java.net.URL) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CredentialInvalidException(me.vertretungsplan.exception.CredentialInvalidException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Cookie(org.apache.http.cookie.Cookie) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) Request(org.apache.http.client.fluent.Request) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) JSONObject(org.json.JSONObject) BigInteger(java.math.BigInteger) Cipher(javax.crypto.Cipher)

Example 52 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project vespa by vespa-engine.

the class Base64EncodeExpression method doExecute.

@Override
protected void doExecute(ExecutionContext ctx) {
    long input = ((LongFieldValue) ctx.getValue()).getLong();
    byte[] output = new byte[8];
    for (int i = 0; i < output.length; ++i) {
        output[i] = (byte) (input & 0xffL);
        input >>>= 8;
    }
    String encoded = new Base64(0).encodeToString(output);
    ctx.setValue(new StringFieldValue(encoded));
}
Also used : Base64(org.apache.commons.codec.binary.Base64) StringFieldValue(com.yahoo.document.datatypes.StringFieldValue) LongFieldValue(com.yahoo.document.datatypes.LongFieldValue)

Example 53 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project vespa by vespa-engine.

the class JsonWriterTestCase method rawTest.

@Test
public final void rawTest() throws IOException {
    String payload = new String(new JsonStringEncoder().quoteAsString(new Base64().encodeToString(Utf8.toBytes("smoketest"))));
    String docId = "id:unittest:testraw::whee";
    String fields = "{ \"actualraw\": \"" + payload + "\"" + " }";
    roundTripEquality(docId, fields);
}
Also used : Base64(org.apache.commons.codec.binary.Base64) JsonStringEncoder(com.fasterxml.jackson.core.io.JsonStringEncoder) Test(org.junit.Test)

Example 54 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project azure-tools-for-java by Microsoft.

the class SimpleAuthenticationHelper method getAuthenticationEndPoint.

private String getAuthenticationEndPoint(final HttpServletRequest httpRequest, final Token token, final Boolean isError) {
    if (httpRequest == null) {
        throw new PreconditionException("Required parameter is null");
    }
    try {
        final String requestURI = httpRequest.getRequestURI();
        final String queryString = httpRequest.getQueryString();
        final ApplicationSettings applicationSettings = applicationSettingsLoader.load();
        final Configuration configuration = configurationCache.load();
        if (configuration == null) {
            throw new GeneralException("Error loading configuration");
        }
        final HttpSession session = httpRequest.getSession(false);
        final String sessionName = session == null ? "" : session.getId();
        final StringBuilder uriStringBuilder = new StringBuilder();
        Base64 encoder = new Base64();
        if (isError) {
            final State previousState = getState(httpRequest);
            uriStringBuilder.append(previousState.getRequestURI());
        } else {
            uriStringBuilder.append(requestURI);
            if (queryString != null && !"".equals(queryString.trim())) {
                uriStringBuilder.append("?");
                uriStringBuilder.append(queryString);
            }
        }
        final String userID = token == null ? "" : token.getUserID().getValue();
        final State state = stateFactory.createState(userID, sessionName, uriStringBuilder.toString());
        final ObjectMapper mapper = new ObjectMapper();
        final String stateString = mapper.writeValueAsString(state);
        final String urlString = String.format("%s%sclient_Id=%s&state=%s&nonce=defaultNonce&redirect_uri=%s&scope=openid%%20offline_access&response_type=code+id_token&prompt=%s&response_mode=form_post", configuration.getAuthenticationEndPoint(), configuration.getAuthenticationEndPoint().getName().contains("?") ? "&" : "?", applicationSettings.getApplicationId(), new String(encoder.encode(stateString.getBytes()), "UTF-8"), URLEncoder.encode(applicationSettings.getRedirectURL().getValue(), "UTF-8"), token == null ? "login" : "none");
        return urlString;
    } catch (IOException e) {
        throw new GeneralException("IO Exception", e);
    }
}
Also used : ApplicationSettings(com.microsoft.azure.oidc.application.settings.ApplicationSettings) GeneralException(com.microsoft.azure.oidc.exception.GeneralException) Base64(org.apache.commons.codec.binary.Base64) Configuration(com.microsoft.azure.oidc.configuration.Configuration) HttpSession(javax.servlet.http.HttpSession) State(com.microsoft.azure.oidc.common.state.State) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PreconditionException(com.microsoft.azure.oidc.exception.PreconditionException)

Example 55 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class HttpsBatchMessageTest method addMessageEncodesBodyCorrectly.

// Tests_SRS_HTTPSBATCHMESSAGE_11_002: [The function shall add the message as a JSON object appended to the current JSON array.]
// Tests_SRS_HTTPSBATCHMESSAGE_11_003: [The JSON object shall have the field "body" set to the raw message  encoded in Base64.]
@Test
public void addMessageEncodesBodyCorrectly(@Mocked final HttpsSingleMessage mockMsg) throws IotHubSizeExceededException {
    final String msgBody = "test-msg-body";
    new NonStrictExpectations() {

        {
            mockMsg.getBody();
            result = msgBody.getBytes(StandardCharsets.UTF_8);
        }
    };
    List<HttpsSingleMessage> mockMessageList = new ArrayList<>();
    mockMessageList.add(mockMsg);
    HttpsBatchMessage batchMsg = new HttpsBatchMessage(mockMessageList);
    String testBatchBody = new String(batchMsg.getBody(), UTF8).replaceAll("\\s", "");
    final String expectedMsgBody = encodeBase64String(msgBody.getBytes(StandardCharsets.UTF_8));
    assertThat(testBatchBody, containsString(expectedMsgBody));
}
Also used : HttpsBatchMessage(com.microsoft.azure.sdk.iot.device.transport.https.HttpsBatchMessage) ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) NonStrictExpectations(mockit.NonStrictExpectations) HttpsSingleMessage(com.microsoft.azure.sdk.iot.device.transport.https.HttpsSingleMessage) Test(org.junit.Test)

Aggregations

Base64 (org.apache.commons.codec.binary.Base64)135 IOException (java.io.IOException)30 Test (org.junit.Test)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 InputStream (java.io.InputStream)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 HashMap (java.util.HashMap)10 SecretKeySpec (javax.crypto.spec.SecretKeySpec)9 MessageDigest (java.security.MessageDigest)8 File (java.io.File)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 URL (java.net.URL)7 Mac (javax.crypto.Mac)7 ServletException (javax.servlet.ServletException)7 X509Certificate (java.security.cert.X509Certificate)6 FileNotFoundException (java.io.FileNotFoundException)5 Signature (java.security.Signature)5