use of org.apache.commons.codec.binary.Base64.encodeBase64String in project commons by twitter.
the class TTextProtocolTest method setUp.
/**
* Load a file containing a serialized thrift message in from disk
* @throws IOException
*/
@Before
public void setUp() throws IOException {
fileContents = Resources.toString(Resources.getResource(getClass(), "/com/twitter/common/thrift/text/TTextProtocol_TestData.txt"), Charsets.UTF_8);
base64Encoder = new Base64();
}
use of org.apache.commons.codec.binary.Base64.encodeBase64String in project zeppelin by apache.
the class KerberosRealm method authenticate.
/**
* It enforces the the Kerberos SPNEGO authentication sequence returning an
* {@link AuthenticationToken} only after the Kerberos SPNEGO sequence has
* completed successfully.
*
* @param request the HTTP client request.
* @param response the HTTP client response.
* @return an authentication token if the Kerberos SPNEGO sequence is complete
* and valid, <code>null</code> if it is in progress (in this case the handler
* handles the response to the client).
* @throws IOException thrown if an IO error occurred.
* @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
*/
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException {
AuthenticationToken token = null;
String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);
if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
if (authorization == null) {
LOG.trace("SPNEGO starting for url: {}", request.getRequestURL());
} else {
LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' : {}", authorization);
}
} else {
authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
final Base64 base64 = new Base64(0);
final byte[] clientToken = base64.decode(authorization);
try {
final String serverPrincipal = KerberosUtil.getTokenServerName(clientToken);
if (!serverPrincipal.startsWith("HTTP/")) {
throw new IllegalArgumentException("Invalid server principal " + serverPrincipal + "decoded from client request");
}
token = Subject.doAs(serverSubject, (PrivilegedExceptionAction<AuthenticationToken>) () -> runWithPrincipal(serverPrincipal, clientToken, base64, response));
} catch (PrivilegedActionException ex) {
if (ex.getException() instanceof IOException) {
throw (IOException) ex.getException();
} else {
throw new AuthenticationException(ex.getException());
}
} catch (Exception ex) {
throw new AuthenticationException(ex);
}
}
return token;
}
use of org.apache.commons.codec.binary.Base64.encodeBase64String in project perun by CESNET.
the class ExtSourceISMU method querySource.
protected List<Map<String, String>> querySource(String query, String searchString, int maxResults) {
try {
HttpURLConnection http = getHttpConnection(query, searchString);
// Prepare the basic auth, if the username and password was specified
if (getAttributes().get("user") != null && getAttributes().get("password") != null) {
String val = getAttributes().get("user") + ":" + getAttributes().get("password");
Base64 encoder = new Base64();
String base64Encoded = new String(encoder.encode(val.getBytes()));
// Java bug : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459815
base64Encoded = base64Encoded.trim();
String authorizationString = "Basic " + base64Encoded;
http.setRequestProperty("Authorization", authorizationString);
}
http.setAllowUserInteraction(false);
http.setRequestMethod("GET");
http.connect();
InputStream is = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
List<Map<String, String>> subjects = new ArrayList<>();
while ((line = reader.readLine()) != null) {
Map<String, String> map = new HashMap<>();
// Each line looks like:
// UCO ;; ;"title before. title before. firstName lastName, title after
// 39700;;“RNDr. Michal Procházka";Procházka;Michal;
// Parse the line
String[] entries = line.split(";");
// Get the UCO
if (entries[0].equals("")) {
// skip this subject, because it doesn't have UCO defined
continue;
}
String login = entries[0];
if (login.isEmpty())
login = null;
map.put("login", login);
String name = entries[2];
// Remove "" from name
name = name.replaceAll("^\"|\"$", "");
// entries[3] contains name of the user, so parse it to get titleBefore, firstName, lastName and titleAfter in separate fields
map.putAll(Utils.parseCommonName(name));
// Add additional userExtSource for MU IdP with loa 2
map.put(ExtSourcesManagerImpl.USEREXTSOURCEMAPPING + "1", "https://idp2.ics.muni.cz/idp/shibboleth|cz.metacentrum.perun.core.impl.ExtSourceIdp|" + login + "@muni.cz|2");
subjects.add(map);
}
return subjects;
} catch (Exception e) {
throw new InternalErrorException(e);
}
}
use of org.apache.commons.codec.binary.Base64.encodeBase64String in project perun by CESNET.
the class ISServiceCallerImpl method makeCall.
/**
* Makes secure SSL connection to IS MU and perform required password manager action
*
* @param dataToPass XML request body
* @param requestId unique ID of a request
* @return InputStream response to be parsed
* @throws InternalErrorException
* @throws IOException
*/
public InputStream makeCall(String dataToPass, int requestId) throws IOException {
// prepare sslFactory
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
HttpsURLConnection.setDefaultSSLSocketFactory(factory);
// we want to log what we send
StringBuilder logBuilder = new StringBuilder();
String uri = BeansUtils.getPropertyFromCustomConfiguration("pwchange.mu.is", "uri");
String login = BeansUtils.getPropertyFromCustomConfiguration("pwchange.mu.is", "login");
String password = BeansUtils.getPropertyFromCustomConfiguration("pwchange.mu.is", "password");
URL myurl = new URL(uri);
HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
// random number for purpose of creating boundaries in multipart
String boundary = Long.toHexString(System.currentTimeMillis());
// Prepare the basic auth, if the username and password was specified
if (login != null && password != null) {
String val = login + ":" + password;
Base64 encoder = new Base64();
String base64Encoded = new String(encoder.encode(val.getBytes()));
base64Encoded = base64Encoded.trim();
String authorizationString = "Basic " + base64Encoded;
con.setRequestProperty("Authorization", authorizationString);
}
con.setAllowUserInteraction(false);
// set request header if is required (set in extSource xml)
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
log.trace("[IS Request {}] Content-Type: multipart/form-data; boundary={}", requestId, boundary);
try (OutputStream output = con.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {
// Send param about return
writer.append("--" + boundary).append(CRLF);
logBuilder.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"out\"").append(CRLF);
logBuilder.append("Content-Disposition: form-data; name=\"out\"").append(CRLF);
writer.append(CRLF).append("xml").append(CRLF).flush();
logBuilder.append(CRLF).append("xml").append(CRLF);
// Send xml file.
writer.append("--" + boundary).append(CRLF);
logBuilder.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"xml\"; filename=\"perun-pwd-manager.xml\"").append(CRLF);
logBuilder.append("Content-Disposition: form-data; name=\"xml\"; filename=\"perun-pwd-manager.xml\"").append(CRLF);
// Text file itself must be saved in this charset!
writer.append("Content-Type: text/xml; charset=" + StandardCharsets.UTF_8).append(CRLF);
logBuilder.append("Content-Type: text/xml; charset=" + StandardCharsets.UTF_8).append(CRLF);
writer.append(CRLF).flush();
logBuilder.append(CRLF);
writer.append(dataToPass);
logBuilder.append("\n--File content is logged separately--\n");
// Important before continuing with writer!
output.flush();
// CRLF is important! It indicates end of boundary.
writer.append(CRLF).flush();
logBuilder.append(CRLF);
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
logBuilder.append("--" + boundary + "--").append(CRLF);
log.trace("[IS Request {}] {}", requestId, logBuilder.toString());
}
int responseCode = con.getResponseCode();
if (responseCode == 200) {
return con.getInputStream();
} else {
String response = null;
try {
response = convertStreamToString(con.getErrorStream(), StandardCharsets.UTF_8);
} catch (IOException ex) {
log.error("Unable to convert InputStream to String.", ex);
}
log.trace("[IS Request {}] Response: {}", requestId, response);
}
throw new InternalErrorException("Wrong response code while opening connection on uri '" + uri + "'. Response code: " + responseCode + ". Request ID: " + requestId);
}
use of org.apache.commons.codec.binary.Base64.encodeBase64String in project camel by apache.
the class XAdESSignatureProperties method calculateDigest.
protected String calculateDigest(String algorithm, byte[] bytes) throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] digestBytes = digest.digest(bytes);
return new Base64().encodeAsString(digestBytes);
}
Aggregations