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.KerberosAuthenticationHandler.java
/** * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only * after the Kerberos SPNEGO sequence has completed successfully. * <p/>/*from ww w . j a v a 2 s . c om*/ * * @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. */ @Override 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"); } 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); Subject serverSubject = loginContext.getSubject(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; GSSCredential gssCreds = null; try { if (PlatformName.IBM_JAVA) { // IBM JDK needs non-null credentials to be passed to createContext here, with // SPNEGO mechanism specified, otherwise JGSS will use its default mechanism // only, which is Kerberos V5. gssCreds = gssManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY); } gssContext = gssManager.createContext(gssCreds); 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(); KerberosName kerberosName = new KerberosName(clientPrincipal); String userName = kerberosName.getShortName(); token = new AuthenticationToken(userName, clientPrincipal, getType()); response.setStatus(HttpServletResponse.SC_OK); LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } if (gssCreds != null) { gssCreds.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.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.java
/** * Produces Negotiate authorization string based on token created by * processChallenge.//from w w w. j a v a 2s . co m * * @param credentials Never used be the Negotiate scheme but must be provided to * satisfy common-httpclient API. Credentials from JAAS will be used insted. * @param method The method being authenticated * * @throws org.apache.commons.httpclient.auth.AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return an Negotiate authorization string * * @since 3.0 */ public synchronized String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { LOG.info("enter CustomNegotiateScheme.authenticate(Credentials, HttpMethod)"); if (state == UNINITIATED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { try { if (context == null) { LOG.info("host: " + method.getURI().getHost()); init(method.getURI().getHost(), (UsernamePasswordCredentials) credentials); } } catch (org.apache.commons.httpclient.URIException urie) { LOG.severe(urie.getMessage()); state = FAILED; throw new AuthenticationException(urie.getMessage()); } // HTTP 1.1 issue: // Mutual auth will never complete do to 200 insted of 401 in // return from server. "state" will never reach ESTABLISHED // but it works anyway // token = context.initSecContext(token, 0, token.length); LOG.info("got token, sending " + token.length + " to server"); } catch (GSSException gsse) { LOG.severe(gsse.getMessage()); state = FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) { throw new InvalidCredentialsException(gsse.getMessage(), gsse); } if (gsse.getMajor() == GSSException.NO_CRED) { throw new CredentialsNotAvailableException(gsse.getMessage(), gsse); } if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) { throw new AuthChallengeException(gsse.getMessage(), gsse); } // other error throw new AuthenticationException(gsse.getMessage()); } return "Negotiate " + new String(new Base64(-1).encode(token)); }
From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java
/** * * @param userId/* w w w. j a v a 2s. c o m*/ * @param token * @param timestamp * @return * @throws UnsupportedEncodingException */ private String createCookieData(String userId, String timestamp) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { /* HmacSHA1(<secret>,<expirytime>@<userID>)@<expirytime>@<userID> */ final String data = createPlainTextData(userId, timestamp); final String encyptedData = encryptData(createDataToEncrypt(userId, timestamp)); String tmp = encyptedData + DATA_DELIMITER + data; tmp = new Base64(true).encodeToString(tmp.getBytes()).toString(); return URLEncoder.encode(tmp, cookieEncoding); }
From source file:mx.bigdata.sat.cfdi.CFDv33.java
String getSignature(PrivateKey key) throws Exception { byte[] bytes = getOriginalBytes(); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initSign(key);//from w w w .j a v a2 s .co m sig.update(bytes); byte[] signed = sig.sign(); Base64 b64 = new Base64(-1); return b64.encodeToString(signed); }
From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java
/** * Encrypt token data//from ww w. ja v a 2 s . c o m * * @param data * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ private String encryptData(String data) throws NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), encryptionType); Mac mac = Mac.getInstance(encryptionType); mac.init(keySpec); byte[] result = mac.doFinal(data.getBytes()); return StringUtils.trim(new Base64(true).encodeToString(result)); }
From source file:eu.europa.ec.markt.dss.DSSUtils.java
/** * This method converts the given certificate into its PEM string. * * @param cert/*from w ww . j ava2 s . c om*/ * @return * @throws CertificateEncodingException */ public static String convertToPEM(final X509Certificate cert) throws CertificateEncodingException { 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:io.druid.security.kerberos.KerberosAuthenticator.java
private String getPrincipalFromRequestNew(HttpServletRequest req) { String authorization = req/*from w ww .java 2 s . c om*/ .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) { return null; } else { authorization = authorization.substring( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length()) .trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); try { DerInputStream ticketStream = new DerInputStream(clientToken); DerValue[] values = ticketStream.getSet(clientToken.length, true); // see this link for AP-REQ format: https://tools.ietf.org/html/rfc1510#section-5.5.1 for (DerValue value : values) { if (isValueAPReq(value)) { APReq apReq = new APReq(value); Ticket ticket = apReq.ticket; EncryptedData encData = ticket.encPart; int eType = encData.getEType(); // find the server's key EncryptionKey finalKey = null; Subject serverSubj = loginContext.getSubject(); Set<Object> serverCreds = serverSubj.getPrivateCredentials(Object.class); for (Object cred : serverCreds) { if (cred instanceof KeyTab) { KeyTab serverKeyTab = (KeyTab) cred; KerberosPrincipal serverPrincipal = new KerberosPrincipal(this.serverPrincipal); KerberosKey[] serverKeys = serverKeyTab.getKeys(serverPrincipal); for (KerberosKey key : serverKeys) { if (key.getKeyType() == eType) { finalKey = new EncryptionKey(key.getKeyType(), key.getEncoded()); break; } } } } if (finalKey == null) { log.error("Could not find matching key from server creds."); return null; } // decrypt the ticket with the server's key byte[] decryptedBytes = encData.decrypt(finalKey, KeyUsage.KU_TICKET); decryptedBytes = encData.reset(decryptedBytes); EncTicketPart decrypted = new EncTicketPart(decryptedBytes); String clientPrincipal = decrypted.cname.toString(); return clientPrincipal; } } } catch (Exception ex) { Throwables.propagate(ex); } } return null; }
From source file:de.zib.scalaris.TransactionSingleOpTest.java
/** * Tests how long it takes to read a large string with different compression * schemes./*from w w w .j a v a2 s . c o m*/ * * @param compressed * how to compress * @param key * the key to append to the {@link #testTime} * * @throws ConnectionException * @throws UnknownException * @throws AbortException * @throws NotFoundException * @throws IOException */ protected void testReadLargeString(final int compression, final String key) throws ConnectionException, UnknownException, AbortException, NotFoundException, IOException { final StringBuilder sb = new StringBuilder(testData.length * 8 * 100); for (int i = 0; i < 100; ++i) { for (final String data : testData) { sb.append(data); } } final String expected = sb.toString(); final TransactionSingleOp conn = new TransactionSingleOp(); conn.setCompressed(true); switch (compression) { case 1: conn.setCompressed(false); case 2: conn.write(testTime + key, expected); break; case 3: conn.setCompressed(false); case 4: final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final GZIPOutputStream gos = new GZIPOutputStream(bos); gos.write(expected.getBytes("UTF-8")); gos.flush(); gos.close(); conn.write(testTime + key, new Base64(0).encodeToString(bos.toByteArray())); break; default: return; } try { for (int i = 0; i < 500; ++i) { String actual = conn.read(testTime + key).stringValue(); if (compression >= 3) { final byte[] packed = new Base64(0).decode(actual); final ByteArrayOutputStream unpacked = new ByteArrayOutputStream(); final ByteArrayInputStream bis = new ByteArrayInputStream(packed); final GZIPInputStream gis = new GZIPInputStream(bis); final byte[] bbuf = new byte[256]; int read = 0; while ((read = gis.read(bbuf)) >= 0) { unpacked.write(bbuf, 0, read); } gis.close(); actual = new String(unpacked.toString("UTF-8")); } assertEquals(expected, actual); } } finally { conn.closeConnection(); } }