List of usage examples for org.apache.commons.codec.binary Base64 isArrayByteBase64
@Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet)
From source file:info.magnolia.setup.HashUsersPasswords.java
@Override protected void operateOnChildNode(Content node, InstallContext ctx) throws RepositoryException, TaskExecutionException { if (NodeTypes.User.NAME.equals(node.getNodeTypeName())) { String encodedPassword = node.getNodeData("pswd").getString(); if (StringUtils.isNotBlank(encodedPassword)) { byte[] pwdBytes; try { pwdBytes = encodedPassword.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { String message = node.getName() + " password could not be hashed. User might need to reset the password before logging again."; log.warn(message);//ww w. ja v a 2 s.c o m ctx.warn(message); pwdBytes = encodedPassword.getBytes(); } if (Base64.isArrayByteBase64(pwdBytes)) { String pwd = new String(Base64.decodeBase64(pwdBytes)); String hashedPwd = SecurityUtil.getBCrypt(pwd); node.setNodeData("pswd", hashedPwd); } } } else { // AllChildrennodeOp is not recursive! for (Content child : node.getChildren(filter)) { operateOnChildNode(child, ctx); } } }
From source file:fedora.server.security.servletfilters.ExtendedHttpServletRequestWrapper.java
private final String[] parseUsernamePassword(String header) throws Exception { String here = "parseUsernamePassword():"; String[] usernamePassword = null; String msg = here + "header intact"; if (header == null || "".equals(header)) { String exceptionMsg = msg + FAILED; log.fatal(exceptionMsg + ", header==" + header); throw new Exception(exceptionMsg); }//from w ww . j av a2 s .com log.debug(msg + SUCCEEDED); String authschemeUsernamepassword[] = header.split("\\s+"); msg = here + "header split"; if (authschemeUsernamepassword.length != 2) { String exceptionMsg = msg + FAILED; log.fatal(exceptionMsg + ", header==" + header); throw new Exception(exceptionMsg); } log.debug(msg + SUCCEEDED); msg = here + "auth scheme"; String authscheme = authschemeUsernamepassword[0]; if (authscheme == null && !BASIC.equalsIgnoreCase(authscheme)) { String exceptionMsg = msg + FAILED; log.fatal(exceptionMsg + ", authscheme==" + authscheme); throw new Exception(exceptionMsg); } log.debug(msg + SUCCEEDED); msg = here + "digest non-null"; String usernamepassword = authschemeUsernamepassword[1]; if (usernamepassword == null || "".equals(usernamepassword)) { String exceptionMsg = msg + FAILED; log.fatal(exceptionMsg + ", usernamepassword==" + usernamepassword); throw new Exception(exceptionMsg); } log.debug(msg + SUCCEEDED + ", usernamepassword==" + usernamepassword); byte[] encoded = usernamepassword.getBytes(); msg = here + "digest base64-encoded"; if (!Base64.isArrayByteBase64(encoded)) { String exceptionMsg = msg + FAILED; log.fatal(exceptionMsg + ", encoded==" + encoded); throw new Exception(exceptionMsg); } if (log.isDebugEnabled()) { log.debug(msg + SUCCEEDED + ", encoded==" + encoded); } byte[] decodedAsByteArray = Base64.decodeBase64(encoded); log.debug(here + "got decoded bytes" + SUCCEEDED + ", decodedAsByteArray==" + decodedAsByteArray); String decoded = new String(decodedAsByteArray); //decodedAsByteArray.toString(); log.debug(here + "got decoded string" + SUCCEEDED + ", decoded==" + decoded); msg = here + "digest decoded"; if (decoded == null || "".equals(decoded)) { String exceptionMsg = msg + FAILED; log.fatal(exceptionMsg + ", digest decoded==" + decoded); throw new Exception(exceptionMsg); } log.debug(msg + SUCCEEDED); String DELIMITER = ":"; if (decoded == null) { log.error("decoded user/password is null . . . returning 0-length strings"); usernamePassword = new String[2]; usernamePassword[0] = ""; usernamePassword[1] = ""; } else if (decoded.indexOf(DELIMITER) < 0) { String exceptionMsg = "decoded user/password lacks delimiter"; log.fatal(exceptionMsg + " . . . throwing exception"); throw new Exception(exceptionMsg); } else if (decoded.startsWith(DELIMITER)) { log.error("decoded user/password is lacks user . . . returning 0-length strings"); usernamePassword = new String[2]; usernamePassword[0] = ""; usernamePassword[1] = ""; } else if (decoded.endsWith(DELIMITER)) { // no password, e.g., user == "guest" usernamePassword = new String[2]; usernamePassword[0] = decoded.substring(0, decoded.length() - 1); usernamePassword[1] = ""; } else { // usual, expected case usernamePassword = decoded.split(DELIMITER); } msg = here + "user/password split"; if (usernamePassword.length != 2) { String exceptionMsg = msg + FAILED; log.fatal(exceptionMsg + ", digest decoded==" + decoded); throw new Exception(exceptionMsg); } log.debug(msg + SUCCEEDED); return usernamePassword; }
From source file:it.doqui.index.ecmengine.business.publishing.EcmEnginePublisherBean.java
/** * Controlla se il DTO {@link EncryptionInfo} specificato è valido per operazioni * di criptazione o decriptazione.//from w w w . j a v a 2 s. com * * <p>Un {@link EncryptionInfo} deve rispettare le seguenti condizioni:</p> * <ul> * <li>deve essere diverso da {@code null};</li> * <li>il suo campo {@code key} deve essere una stringa valida secondo quanto * definito in {@link #isValidName(String)}, <i>a meno che il contenuto non sia criptato alla fonte * e l'operazione sia una criptazione</i>;</li> * <li>se il contenuto &ergave; criptato alla fonte l'IV sorgente deve essere specificato * (<i>solo nel caso di operazioni di criptazione</i>);</li> * <li>il suo campo {@code algorithm} deve essere una stringa valida secondo quanto * definito in {@link #isValidName(String)};</li> * <li>i campi {@code mode} e {@code padding} devono essere entrambi specificati oppure nessuno dei due deve essere * specificato;</li> * <li>il suo campo {@code sourceIv} deve essere valorizzato con una stringa BASE64 se viene caricato * un contenuto già criptato con modalità di criptazione non specificata oppure diversa da ECB;</li> * <li>il suo campo {@code keyId} deve essere una stringa valida secondo quanto * definito in {@link #isValidName(String)} (<i>solo nel caso di operazioni di criptazione</i>).</li> * </ul> * * @param encInfo L'{@link EncryptionInfo} da controllare. * @param forDecrypt {@code true} se la verifica deve essere effettuata per un'operazione di decriptazione. * * @return {@code true} se è un {@link EncryptionInfo} valido, {@code false} altrimenti. */ protected static boolean isValidEncryptionInfo(EncryptionInfo encInfo, boolean forDecrypt) { // Decrypting if (forDecrypt) { return (encInfo != null && isValidName(encInfo.getKey()) && isValidName(encInfo.getAlgorithm())); } // Encrypting /* * L'IV e` richiesto solo se viene inviato un contenuto gia` criptato e il mode e` * specificato ed e` diverso da ECB. */ final boolean needsIv = encInfo != null && encInfo.isSourceEncrypted() && (encInfo.getMode() != null && !encInfo.getMode().equalsIgnoreCase("ECB")); /* * La chiave serve quando non viene caricato un contenuto gia` criptato alla fonte. */ final boolean needsKey = !(encInfo != null && encInfo.isSourceEncrypted()); /* * Mode e padding devono essere entrambi specificati e validi (etrambi non nulli e non stringhe vuote) * oppure nessuno dei due deve essere specificato (entrambi null). */ final boolean bothOrNoneModeAndPadding = encInfo != null && (isValidName(encInfo.getMode()) && isValidName(encInfo.getPadding()) || (encInfo.getMode() == null && encInfo.getPadding() == null)); /* * Algoritmo e keyId sono sempre necessari, gli altri casi dipendono da quanto valutato sopra. */ return (encInfo != null && (!needsKey || (needsKey && isValidName(encInfo.getKey()))) && (!needsIv || (needsIv && encInfo.getSourceIV() != null && Base64.isArrayByteBase64(encInfo.getSourceIV().getBytes()))) && isValidName(encInfo.getAlgorithm()) && bothOrNoneModeAndPadding && isValidName(encInfo.getKeyId())); }
From source file:org.acegisecurity.ui.digestauth.DigestProcessingFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); }//w w w. ja va2 s . co m if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; String header = httpRequest.getHeader("Authorization"); if (logger.isDebugEnabled()) { logger.debug("Authorization header received from user agent: " + header); } if ((header != null) && header.startsWith("Digest ")) { String section212response = header.substring(7); String[] headerEntries = StringSplitUtils.splitIgnoringQuotes(section212response, ','); Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); String username = (String) headerMap.get("username"); String realm = (String) headerMap.get("realm"); String nonce = (String) headerMap.get("nonce"); String uri = (String) headerMap.get("uri"); String responseDigest = (String) headerMap.get("response"); String qop = (String) headerMap.get("qop"); // RFC 2617 extension String nc = (String) headerMap.get("nc"); // RFC 2617 extension String cnonce = (String) headerMap.get("cnonce"); // RFC 2617 extension // Check all required parameters were supplied (ie RFC 2069) if ((username == null) || (realm == null) || (nonce == null) || (uri == null) || (response == null)) { if (logger.isDebugEnabled()) { logger.debug("extracted username: '" + username + "'; realm: '" + username + "'; nonce: '" + username + "'; uri: '" + username + "'; response: '" + username + "'"); } fail(request, response, new BadCredentialsException(messages.getMessage("DigestProcessingFilter.missingMandatory", new Object[] { section212response }, "Missing mandatory digest value; received header {0}"))); return; } // Check all required parameters for an "auth" qop were supplied (ie RFC 2617) if ("auth".equals(qop)) { if ((nc == null) || (cnonce == null)) { if (logger.isDebugEnabled()) { logger.debug("extracted nc: '" + nc + "'; cnonce: '" + cnonce + "'"); } fail(request, response, new BadCredentialsException(messages.getMessage("DigestProcessingFilter.missingAuth", new Object[] { section212response }, "Missing mandatory digest value; received header {0}"))); return; } } // Check realm name equals what we expected if (!this.getAuthenticationEntryPoint().getRealmName().equals(realm)) { fail(request, response, new BadCredentialsException(messages.getMessage("DigestProcessingFilter.incorrectRealm", new Object[] { realm, this.getAuthenticationEntryPoint().getRealmName() }, "Response realm name '{0}' does not match system realm name of '{1}'"))); return; } // Check nonce was a Base64 encoded (as sent by DigestProcessingFilterEntryPoint) if (!Base64.isArrayByteBase64(nonce.getBytes())) { fail(request, response, new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceEncoding", new Object[] { nonce }, "Nonce is not encoded in Base64; received nonce {0}"))); return; } // Decode nonce from Base64 // format of nonce is: // base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key)) String nonceAsPlainText = new String(Base64.decodeBase64(nonce.getBytes())); String[] nonceTokens = StringUtils.delimitedListToStringArray(nonceAsPlainText, ":"); if (nonceTokens.length != 2) { fail(request, response, new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceNotTwoTokens", new Object[] { nonceAsPlainText }, "Nonce should have yielded two tokens but was {0}"))); return; } // Extract expiry time from nonce long nonceExpiryTime; try { nonceExpiryTime = new Long(nonceTokens[0]).longValue(); } catch (NumberFormatException nfe) { fail(request, response, new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceNotNumeric", new Object[] { nonceAsPlainText }, "Nonce token should have yielded a numeric first token, but was {0}"))); return; } // Check signature of nonce matches this expiry time String expectedNonceSignature = DigestUtils .md5Hex(nonceExpiryTime + ":" + this.getAuthenticationEntryPoint().getKey()); if (!expectedNonceSignature.equals(nonceTokens[1])) { fail(request, response, new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceCompromised", new Object[] { nonceAsPlainText }, "Nonce token compromised {0}"))); return; } // Lookup password for presented username // NB: DAO-provided password MUST be clear text - not encoded/salted // (unless this instance's passwordAlreadyEncoded property is 'false') boolean loadedFromDao = false; UserDetails user = userCache.getUserFromCache(username); if (user == null) { loadedFromDao = true; try { user = userDetailsService.loadUserByUsername(username); } catch (UsernameNotFoundException notFound) { fail(request, response, new BadCredentialsException( messages.getMessage("DigestProcessingFilter.usernameNotFound", new Object[] { username }, "Username {0} not found"))); return; } if (user == null) { throw new AuthenticationServiceException( "AuthenticationDao returned null, which is an interface contract violation"); } userCache.putUserInCache(user); } // Compute the expected response-digest (will be in hex form) String serverDigestMd5; // Don't catch IllegalArgumentException (already checked validity) serverDigestMd5 = generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(), ((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce); // If digest is incorrect, try refreshing from backend and recomputing if (!serverDigestMd5.equals(responseDigest) && !loadedFromDao) { if (logger.isDebugEnabled()) { logger.debug( "Digest comparison failure; trying to refresh user from DAO in case password had changed"); } try { user = userDetailsService.loadUserByUsername(username); } catch (UsernameNotFoundException notFound) { // Would very rarely happen, as user existed earlier fail(request, response, new BadCredentialsException( messages.getMessage("DigestProcessingFilter.usernameNotFound", new Object[] { username }, "Username {0} not found"))); } userCache.putUserInCache(user); // Don't catch IllegalArgumentException (already checked validity) serverDigestMd5 = generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(), ((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce); } // If digest is still incorrect, definitely reject authentication attempt if (!serverDigestMd5.equals(responseDigest)) { if (logger.isDebugEnabled()) { logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + responseDigest + "'; is AuthenticationDao returning clear text passwords?"); } fail(request, response, new BadCredentialsException( messages.getMessage("DigestProcessingFilter.incorrectResponse", "Incorrect response"))); return; } // To get this far, the digest must have been valid // Check the nonce has not expired // We do this last so we can direct the user agent its nonce is stale // but the request was otherwise appearing to be valid if (nonceExpiryTime < System.currentTimeMillis()) { fail(request, response, new NonceExpiredException( messages.getMessage("DigestProcessingFilter.nonceExpired", "Nonce has expired/timed out"))); return; } if (logger.isDebugEnabled()) { logger.debug("Authentication success for user: '" + username + "' with response: '" + responseDigest + "'"); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user, user.getPassword()); authRequest.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext().setAuthentication(authRequest); } chain.doFilter(request, response); }
From source file:org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.java
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { return null; }//w w w.java 2 s. c om for (int i = 0; i < cookies.length; i++) { if (cookieName.equals(cookies[i].getName())) { String cookieValue = cookies[i].getValue(); for (int j = 0; j < cookieValue.length() % 4; j++) { cookieValue = cookieValue + "="; } if (Base64.isArrayByteBase64(cookieValue.getBytes())) { if (logger.isDebugEnabled()) { logger.debug("Remember-me cookie detected"); } // Decode token from Base64 // format of token is: // username + ":" + expiryTime + ":" + // Md5Hex(username + ":" + expiryTime + ":" + password + ":" // + key) String cookieAsPlainText = new String(Base64.decodeBase64(cookieValue.getBytes())); String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ":"); if (cookieTokens.length == 3) { long tokenExpiryTime; try { tokenExpiryTime = new Long(cookieTokens[1]).longValue(); } catch (NumberFormatException nfe) { cancelCookie(request, response, "Cookie token[1] did not contain a valid number (contained '" + cookieTokens[1] + "')"); return null; } if (isTokenExpired(tokenExpiryTime)) { cancelCookie(request, response, "Cookie token[1] has expired (expired on '" + new Date(tokenExpiryTime) + "'; current time is '" + new Date() + "')"); return null; } // Check the user exists // Defer lookup until after expiry time checked, to // possibly avoid expensive lookup UserDetails userDetails = loadUserDetails(request, response, cookieTokens); if (userDetails == null) { cancelCookie(request, response, "Cookie token[0] contained username '" + cookieTokens[0] + "' but was not found"); return null; } if (!isValidUserDetails(request, response, userDetails, cookieTokens)) { return null; } // Check signature of token matches remaining details // Must do this after user lookup, as we need the // DAO-derived password // If efficiency was a major issue, just add in a // UserCache implementation, // but recall this method is usually only called one per // HttpSession // (as if the token is valid, it will cause // SecurityContextHolder population, whilst // if invalid, will cause the cookie to be cancelled) String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails); if (!expectedTokenSignature.equals(cookieTokens[2])) { cancelCookie(request, response, "Cookie token[2] contained signature '" + cookieTokens[2] + "' but expected '" + expectedTokenSignature + "'"); return null; } // By this stage we have a valid token if (logger.isDebugEnabled()) { logger.debug("Remember-me cookie accepted"); } RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(this.key, userDetails, userDetails.getAuthorities()); auth.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request)); return auth; } else { cancelCookie(request, response, "Cookie token did not contain 3 tokens; decoded value was '" + cookieAsPlainText + "'"); return null; } } else { cancelCookie(request, response, "Cookie token was not Base64 encoded; value was '" + cookieValue + "'"); return null; } } } return null; }
From source file:org.apache.archiva.redback.integration.filter.authentication.digest.HttpDigestHeader.java
public void parseClientHeader(String rawHeader, String expectedRealm, String digestKey) throws HttpAuthenticationException { Properties authHeaderProps = HttpUtils.complexHeaderToProperties(rawHeader, ",", "="); username = authHeaderProps.getProperty("username"); realm = authHeaderProps.getProperty("realm"); nonce = authHeaderProps.getProperty("nonce"); uri = authHeaderProps.getProperty("uri"); response = authHeaderProps.getProperty("response"); qop = authHeaderProps.getProperty("qop"); nc = authHeaderProps.getProperty("nc"); cnonce = authHeaderProps.getProperty("cnonce"); // [RFC 2067] Validate all required values if (StringUtils.isEmpty(username) || StringUtils.isEmpty(realm) || StringUtils.isEmpty(nonce) || StringUtils.isEmpty(uri) || StringUtils.isEmpty(response)) { log.debug("Missing mandatory fields: Raw Digest Header : [{}]", rawHeader); throw new HttpAuthenticationException("Missing mandatory digest fields per RFC2069."); }/*from w w w . j a v a 2 s. c o m*/ // [RFC 2617] Validate realm. if (!StringUtils.equals(expectedRealm, realm)) { log.debug("Realm name is invalid: expected [{}] but got [{}]", expectedRealm, realm); throw new HttpAuthenticationException("Response realm does not match expected realm."); } // [RFC 2617] Validate "auth" qop if (StringUtils.equals("auth", qop)) { if (StringUtils.isEmpty(nc) || StringUtils.isEmpty(cnonce)) { log.debug("Missing mandatory qop fields: nc [{}] cnonce [{}]", nc, cnonce); throw new HttpAuthenticationException("Missing mandatory qop digest fields per RFC2617."); } } // [RFC 2617] Validate nonce if (!Base64.isArrayByteBase64(nonce.getBytes())) { log.debug("Nonce is not encoded in Base64: nonce [{}]", nonce); throw new HttpAuthenticationException("Response nonce is not encoded in Base64."); } // Decode nonce String decodedNonce = new String(Base64.decodeBase64(nonce.getBytes())); String nonceTokens[] = StringUtils.split(decodedNonce, ":"); // Validate nonce format if (nonceTokens.length != 2) { log.debug("Nonce format expected [2] elements, but got [{}] instead. Decoded nonce [{}]", nonceTokens.length, decodedNonce); throw new HttpAuthenticationException( "Nonce format is invalid. " + "Received an unexpected number of sub elements."); } // Extract nonce timestamp long nonceTimestamp = 0; try { nonceTimestamp = Long.parseLong(nonceTokens[0]); } catch (NumberFormatException e) { throw new HttpAuthenticationException("Unexpected nonce timestamp."); } // Extract nonce signature String expectedSignature = Digest.md5Hex(nonceTimestamp + ":" + digestKey); if (!StringUtils.equals(expectedSignature, nonceTokens[1])) { log.error("Nonce parameter has been compromised."); throw new HttpAuthenticationException("Nonce parameter has been compromised."); } }
From source file:org.apache.hadoop.hive.serde2.lazy.LazyBinary.java
public static byte[] decodeIfNeeded(byte[] recv) { boolean arrayByteBase64 = Base64.isArrayByteBase64(recv); if (LOG.isDebugEnabled() && arrayByteBase64) { LOG.debug("Data only contains Base64 alphabets only so try to decode the data."); }/*ww w . jav a2 s. c o m*/ return arrayByteBase64 ? Base64.decodeBase64(recv) : recv; }
From source file:org.apache.hawq.pxf.service.utilities.ProtocolData.java
private byte[] parseBase64(String key, String errName) { String encoded = getOptionalProperty(key); if (encoded == null) { return null; }// w ww .j av a 2 s. c o m if (!Base64.isArrayByteBase64(encoded.getBytes())) { throw new IllegalArgumentException( errName + " must be Base64 encoded." + "(Bad value: " + encoded + ")"); } byte[] parsed = Base64.decodeBase64(encoded); LOG.debug("decoded " + key + ": " + new String(parsed)); return parsed; }
From source file:org.eclipse.jubula.client.ui.preferences.utils.Utils.java
/** * Checks correctness of the stored preferences. * @param pref The readed, base64-coded preference. * @throws JBException if the prefrence is not base64-coded. *///from w ww . j ava 2 s . co m public static void checkPreferences(String pref) throws JBException { if (!Base64.isArrayByteBase64(pref.getBytes())) { throw new JBException(StringConstants.EMPTY, new Integer(0)); } }
From source file:org.eclipse.jubula.client.ui.rcp.utils.AutAgentManager.java
/** * @param encodedString A base64 encoded string. * @return the decoded string./*from w w w .j av a2 s. c o m*/ * @throws JBException in case of not base64 encoded string */ String decodeString(String encodedString) throws JBException { if (!Base64.isArrayByteBase64(encodedString.getBytes())) { throw new JBException(StringConstants.EMPTY, new Integer(0)); } return new String(Base64.decodeBase64(encodedString.getBytes())); }