List of usage examples for org.apache.commons.codec.binary Base64 Base64
public Base64(final int lineLength)
From source file:com.lucidworks.security.authentication.server.TestKerberosAuthenticationHandler.java
public void testRequestWithAuthorization() throws Exception { String token = KerberosTestUtils.doAsClient(new Callable<String>() { @Override// ww w . j a v a2 s . c om public String call() throws Exception { GSSManager gssManager = GSSManager.getInstance(); GSSContext gssContext = null; try { String servicePrincipal = KerberosTestUtils.getServerPrincipal(); Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL"); GSSName serviceName = gssManager.createName(servicePrincipal, oid); oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID"); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length); Base64 base64 = new Base64(0); return base64.encodeToString(outToken); } finally { if (gssContext != null) { gssContext.dispose(); } } } }); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)) .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token); AuthenticationToken authToken = handler.authenticate(request, response); if (authToken != null) { Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName()); Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName())); Assert.assertEquals(getExpectedType(), authToken.getType()); } else { Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java
/** * Validate the Authentication Cookie/* w w w .j av a 2s . c om*/ * * @param request * @param cookieName * @param secret * @return */ @Override public SimpleCredentials extractCredentials(HttpServletRequest request) { Cookie cookie = CookieUtil.getCookie(request, cookieName); if (cookie == null) { return null; } // Get and decode cookie data String cookieData; try { if (StringUtils.isBlank(cookie.getValue())) { return null; } final String tmp = new Base64(true).decode(cookie.getValue()).toString(); cookieData = URLDecoder.decode(tmp, cookieEncoding); } catch (UnsupportedEncodingException e) { return null; } // Split the cookie data by the DATA_DELIMITER String[] values = splitCookieData(cookieData); if (values == null) { return null; } final String token = StringUtils.trimToNull(values[0]); final String timestamp = StringUtils.trimToNull(values[1]); final String userId = StringUtils.trimToNull(values[2]); // Could not get a required value from the cookie if (userId == null || token == null || timestamp == null) { return null; } final String expectedData; try { expectedData = encryptData(createDataToEncrypt(userId, timestamp)); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (InvalidKeyException ex) { Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex); return null; } // If Cookie token and Expected token don't match, return null if (!StringUtils.equals(token, expectedData)) { return null; } // TODO: Handle cookie timestamping more appropriately. // Check if the current time is greater than the acceptable cookie // expiry timestamp // long cookieTimestamp = Long.parseLong(timestamp); // if (System.currentTimeMillis() > cookieTimestamp) { // return null; // } return new SimpleCredentials(userId, "".toCharArray()); }
From source file:mx.bigdata.sat.cfd.CFDv2.java
String getSignature(PrivateKey key) throws Exception { byte[] bytes = getOriginalBytes(); byte[] signed; String alg = getDigestAlgorithm(); Signature sig = Signature.getInstance(alg); sig.initSign(key);/* w ww . j a va 2 s . c om*/ sig.update(bytes); signed = sig.sign(); Base64 b64 = new Base64(-1); return b64.encodeToString(signed); }
From source file:com.netscape.cmsutil.util.Utils.java
/** * Converts a byte array into a multi-line Base-64 encoded string. * Each line is at most 64-character long and terminated with CRLF. * * @param bytes byte array// w w w .j a v a 2 s. c o m * @return base-64 encoded data */ public static String base64encodeMultiLine(byte[] bytes) { return new Base64(64).encodeToString(bytes); }
From source file:com.sunrun.crportal.util.CRPortalUtil.java
public static String decryptURL(String s) { String sDecrypted = ""; try {//from w ww . j a va 2 s . com // Decrypt using Blowfish algorithm. Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(CP2_URL_ENCRYPTION_KEY.getBytes(), "Blowfish")); sDecrypted = new Base64(true).encodeToString(cipher.doFinal(s.getBytes())); } catch (Exception e) { LOG.error(e.getMessage(), e); } return sDecrypted; }
From source file:com.cloudera.alfredo.server.KerberosAuthenticationHandler.java
/** * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only * after the Kerberos SPNEGO sequence completed successfully. * <p/>//from w w w. j a va 2 s.com * * @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 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. */ @Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION); if (authorization == null) { response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.trace("SPNEGO starts"); } else if (!authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) { response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 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); Subject serverSubject = loginContext.getSubject(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; try { gssContext = gssManager.createContext((GSSCredential) null); byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length); if (serverToken != null && serverToken.length > 0) { String authenticate = base64.encodeToString(serverToken); response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE + " " + authenticate); } if (!gssContext.isEstablished()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.trace("SPNEGO in progress"); } else { String clientPrincipal = gssContext.getSrcName().toString(); int index = clientPrincipal.indexOf("/"); if (index == -1) { index = clientPrincipal.indexOf("@"); } String userName = (index == -1) ? clientPrincipal : clientPrincipal.substring(0, index); token = new AuthenticationToken(userName, clientPrincipal, TYPE); response.setStatus(HttpServletResponse.SC_OK); LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } } return token; } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } } return token; }
From source file:com.hortonworks.registries.auth.server.TestKerberosAuthenticationHandler.java
public void testRequestWithAuthorization() throws Exception { String token = KerberosTestUtils.doAsClient(new Callable<String>() { @Override/*from ww w . j a va 2s .c o m*/ public String call() throws Exception { GSSManager gssManager = GSSManager.getInstance(); GSSContext gssContext = null; try { String servicePrincipal = KerberosTestUtils.getServerPrincipal(); Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL"); GSSName serviceName = gssManager.createName(servicePrincipal, oid); oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID"); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length); Base64 base64 = new Base64(0); return base64.encodeToString(outToken); } finally { if (gssContext != null) { gssContext.dispose(); } } } }); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)) .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token); Mockito.when(request.getServerName()).thenReturn("localhost"); AuthenticationToken authToken = handler.authenticate(request, response); if (authToken != null) { Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName()); Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName())); Assert.assertEquals(getExpectedType(), authToken.getType()); } else { Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
From source file:jp.primecloud.auto.api.ApiFilter.java
/** * * BASE64??LinkedHashMap??//w ww .ja va 2s . co m * ?BASE64 * * @param url URL * @return LinkedHashMap<??, > * @throws UnsupportedEncodingException */ @SuppressWarnings("static-access") private LinkedHashMap<String, String> getDecodedParamMap(URI uri) throws UnsupportedEncodingException { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); String queryUrlText = uri.getQuery(); if (StringUtils.isNotEmpty(queryUrlText)) { try { Base64 base64 = new Base64(true); String decodedUri = new String(base64.decodeBase64(queryUrlText.getBytes("UTF-8")), "UTF-8"); for (String param : decodedUri.split("&")) { String key = param.substring(0, param.indexOf("=")); String value = param.substring(param.indexOf("=") + 1, param.length()); if (PARAM_NAME_SIGNATURE.equals(key)) { map.put(key, value); } else { map.put(key, value); } } } catch (Exception e) { throw new AutoApplicationException("EAPI-000008", e, "URL", uri.toString()); } } return map; }
From source file:eu.europa.esig.dss.DSSUtils.java
/** * This method converts the given certificate into its PEM string. * * @param cert/* ww w.j a v a 2 s. co m*/ * @return * @throws java.security.cert.CertificateEncodingException */ public static String convertToPEM(final CertificateToken cert) throws DSSException { final Base64 encoder = new Base64(64); final byte[] derCert = cert.getEncoded(); final String pemCertPre = new String(encoder.encode(derCert)); final String pemCert = CERT_BEGIN + pemCertPre + CERT_END; return pemCert; }
From source file:com.hortonworks.registries.auth.server.TestKerberosAuthenticationHandler.java
public void testRequestWithInvalidKerberosAuthorization() throws Exception { String token = new Base64(0).encodeToString(new byte[] { 0, 1, 2 }); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)) .thenReturn(KerberosAuthenticator.NEGOTIATE + token); try {/*from w w w . j a v a2 s . c o m*/ handler.authenticate(request, response); Assert.fail(); } catch (AuthenticationException ex) { // Expected } catch (Exception ex) { Assert.fail(); } }