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;
}
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));
}
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);
}
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);
}
}
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));
}
Aggregations