List of usage examples for org.apache.commons.codec.binary Base64 isArrayByteBase64
@Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet)
From source file:org.fcrepo.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; logger.error(exceptionMsg + ", header==" + header); throw new Exception(exceptionMsg); }/*from www . j a v a 2 s. com*/ logger.debug(msg + SUCCEEDED); String authschemeUsernamepassword[] = header.split("\\s+"); msg = here + "header split"; if (authschemeUsernamepassword.length != 2) { String exceptionMsg = msg + FAILED; logger.error(exceptionMsg + ", header==" + header); throw new Exception(exceptionMsg); } logger.debug(msg + SUCCEEDED); msg = here + "auth scheme"; String authscheme = authschemeUsernamepassword[0]; if (authscheme == null && !BASIC.equalsIgnoreCase(authscheme)) { String exceptionMsg = msg + FAILED; logger.error(exceptionMsg + ", authscheme==" + authscheme); throw new Exception(exceptionMsg); } logger.debug(msg + SUCCEEDED); msg = here + "digest non-null"; String usernamepassword = authschemeUsernamepassword[1]; if (usernamepassword == null || "".equals(usernamepassword)) { String exceptionMsg = msg + FAILED; logger.error(exceptionMsg + ", usernamepassword==" + usernamepassword); throw new Exception(exceptionMsg); } logger.debug(msg + SUCCEEDED + ", usernamepassword==" + usernamepassword); byte[] encoded = usernamepassword.getBytes(); msg = here + "digest base64-encoded"; if (!Base64.isArrayByteBase64(encoded)) { String exceptionMsg = msg + FAILED; logger.error(exceptionMsg + ", encoded==" + encoded); throw new Exception(exceptionMsg); } if (logger.isDebugEnabled()) { logger.debug(msg + SUCCEEDED + ", encoded==" + encoded); } byte[] decodedAsByteArray = Base64.decodeBase64(encoded); logger.debug(here + "got decoded bytes" + SUCCEEDED + ", decodedAsByteArray==" + decodedAsByteArray); String decoded = new String(decodedAsByteArray); //decodedAsByteArray.toString(); logger.debug(here + "got decoded string" + SUCCEEDED + ", decoded==" + decoded); msg = here + "digest decoded"; if (decoded == null || "".equals(decoded)) { String exceptionMsg = msg + FAILED; logger.error(exceptionMsg + ", digest decoded==" + decoded); throw new Exception(exceptionMsg); } logger.debug(msg + SUCCEEDED); String DELIMITER = ":"; if (decoded == null) { logger.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"; logger.error(exceptionMsg + " . . . throwing exception"); throw new Exception(exceptionMsg); } else if (decoded.startsWith(DELIMITER)) { logger.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; logger.error(exceptionMsg + ", digest decoded==" + decoded); throw new Exception(exceptionMsg); } logger.debug(msg + SUCCEEDED); return usernamePassword; }
From source file:org.jbpm.designer.server.service.DefaultDesignerAssetServiceTest.java
private String decodeUniqueId(String uniqueId) { if (Base64.isArrayByteBase64(uniqueId.getBytes())) { byte[] decoded = Base64.decodeBase64(uniqueId); try {//from w w w. java 2s. c o m String uri = new String(decoded, "UTF-8"); return UriUtils.encode(uri); } catch (UnsupportedEncodingException e) { } } return UriUtils.encode(uniqueId); }
From source file:org.kuali.continuity.security.SecurityUtil.java
/** * Decodes the cookie and splits it into a set of token strings using the ":" delimiter. * * @param cookieValue the value obtained from the submitted cookie * @return the array of tokens./*from w w w . ja v a 2 s . c o m*/ * @throws InvalidCookieException if the cookie was not base64 encoded. */ private static String[] decodeCookie(String cookieValue) throws InvalidCookieException { for (int j = 0; j < cookieValue.length() % 4; j++) { cookieValue = cookieValue + "="; } if (!Base64.isArrayByteBase64(cookieValue.getBytes())) { throw new InvalidCookieException( "Cookie token was not Base64 encoded; value was '" + cookieValue + "'"); } String cookieAsPlainText = decode(cookieValue); return StringUtils.delimitedListToStringArray(cookieAsPlainText, "::"); }
From source file:org.openanzo.security.keystore.TestSecretKeyEncoder.java
/** * @throws Exception//from ww w.jav a 2 s . c o m */ public void testEncryptAndBase64EncodeString() throws Exception { String str = "My string to encrypt, including an uncommon character,\u05D2 (the Hebrew Gimel), to ensure character encoding is handled correctly."; String cyphertext = encoder.encryptAndBase64EncodeString(str); assertTrue(Base64.isArrayByteBase64(cyphertext.getBytes("UTF-8"))); String decrypted = encoder.decryptAndBase64DecodeString(cyphertext); assertEquals(str, decrypted); }
From source file:org.openanzo.security.keystore.TestSecretKeyEncoder.java
/** * @throws Exception/*w ww .j av a 2 s .c o m*/ */ public void testEncryptAndBase64EncodeBytes() throws Exception { byte[] sample = { 0, 1, 2, 3, 4, 5 }; String cyphertext = encoder.encryptAndBase64EncodeBytes(sample); assertTrue(Base64.isArrayByteBase64(cyphertext.getBytes("UTF-8"))); byte[] decrypted = encoder.decryptAndBase64DecodeBytes(cyphertext); assertTrue(Arrays.equals(sample, decrypted)); }
From source file:org.openanzo.services.serialization.XMLBackupReader.java
/** * Parse the data within the reader, passing the results to the IRepositoryHandler * //www . j a v a 2 s .com * @param reader * reader containing the data * @param handler * Handler which will handle the elements within the data * @throws AnzoException */ private void parseBackup(Reader reader, final IBackupHandler handler) throws AnzoException { try { XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { graphUri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri); String meta = parser.getAttributeValue(null, SerializationConstants.metadataGraphUri); String uuidString = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID); namedGraphUri = Constants.valueFactory.createURI(graphUri); metaURI = Constants.valueFactory.createURI(meta); uuid = Constants.valueFactory.createURI(uuidString); revisioned = Boolean .parseBoolean(parser.getAttributeValue(null, SerializationConstants.revisioned)); } else if (SerializationConstants.revisions.equals(parser.getLocalName())) { revisions = new ArrayList<BackupRevision>(); } else if (SerializationConstants.revisionInfo.equals(parser.getLocalName())) { long revision = Long .parseLong(parser.getAttributeValue(null, SerializationConstants.revision)); Long start = Long.valueOf(parser.getAttributeValue(null, SerializationConstants.start)); String endString = parser.getAttributeValue(null, SerializationConstants.end); Long end = (endString != null) ? Long.valueOf(endString) : -1; lastModified = Constants.valueFactory .createURI(parser.getAttributeValue(null, SerializationConstants.lastModifiedBy)); revisions.add(new BackupRevision(revision, start, end, lastModified)); } else if (SerializationConstants.statement.equals(parser.getLocalName())) { if (processGraph) { if (revisioned) { String startString = parser.getAttributeValue(null, SerializationConstants.start); String endString = parser.getAttributeValue(null, SerializationConstants.end); if (startString != null) start = Long.valueOf(startString); if (endString != null) end = Long.valueOf(endString); } } } else if (SerializationConstants.statements.equals(parser.getLocalName())) { if (processGraph) { metadata = !parser.getAttributeValue(null, SerializationConstants.namedGraphUri) .equals(graphUri); } } else if (SerializationConstants.subject.equals(parser.getLocalName())) { if (processGraph) { nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType); } } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { } else if (SerializationConstants.object.equals(parser.getLocalName())) { if (processGraph) { nodeType = parser.getAttributeValue(null, SerializationConstants.objectType); language = parser.getAttributeValue(null, SerializationConstants.language); datatype = parser.getAttributeValue(null, SerializationConstants.dataType); } } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { } break; case XMLStreamConstants.END_ELEMENT: if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { graphUri = null; namedGraphUri = null; metaURI = null; uuid = null; revisioned = true; revisions = null; } else if (SerializationConstants.revisionInfo.equals(parser.getLocalName())) { } else if (SerializationConstants.revisions.equals(parser.getLocalName())) { processGraph = handler.handleNamedGraph(revisioned, namedGraphUri, metaURI, uuid, revisions); revisions = null; } else if (SerializationConstants.statement.equals(parser.getLocalName())) { if (processGraph) { handler.handleStatement(metadata, revisioned, Constants.valueFactory.createStatement(currentSubject, currentPredicate, currentObject, currentNamedGraphURI), start, end); start = null; end = null; } } else if (SerializationConstants.subject.equals(parser.getLocalName())) { if (processGraph) { if (NodeType.BNODE.name().equals(nodeType)) { currentSubject = Constants.valueFactory.createBNode(currentValue); } else { currentSubject = Constants.valueFactory.createURI(currentValue); } currentValue = null; nodeType = null; } } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { if (processGraph) { currentPredicate = Constants.valueFactory.createURI(currentValue); currentValue = null; } } else if (SerializationConstants.object.equals(parser.getLocalName())) { if (processGraph) { if (NodeType.BNODE.name().equals(nodeType)) { currentObject = Constants.valueFactory.createBNode(currentValue); } else if (NodeType.URI.name().equals(nodeType)) { currentObject = Constants.valueFactory.createURI(currentValue); } else if (NodeType.LITERAL.name().equals(nodeType)) { if (currentValue == null) { currentValue = ""; } else if (Base64 .isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) { currentValue = new String( Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)), Constants.byteEncoding); } if (datatype != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, Constants.valueFactory.createURI(datatype)); } else if (language != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, language); } else { currentObject = Constants.valueFactory.createLiteral(currentValue); } } currentValue = null; nodeType = null; language = null; datatype = null; } } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { if (processGraph) { currentNamedGraphURI = Constants.valueFactory.createURI(currentValue); currentValue = null; } } break; case XMLStreamConstants.CHARACTERS: if (parser.hasText()) currentValue = parser.getText(); break; case XMLStreamConstants.CDATA: if (parser.hasText()) currentValue = parser.getText(); break; } } parser.close(); } catch (XMLStreamException ex) { throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage()); } catch (UnsupportedEncodingException uee) { throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee); } }
From source file:org.openanzo.services.serialization.XMLNamedGraphUpdatesReader.java
/** * Parse the data within the reader, passing the results to the IRepositoryHandler * /*w w w.j a v a2s . com*/ * @param reader * reader containing the data * @param handler * Handler which will handle the elements within the data * @throws AnzoException */ public void parseUpdates(Reader reader, final INamedGraphUpdateHandler handler) throws AnzoException { try { XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { String uri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri); String uuid = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID); currentNamedGraphUpdate = new NamedGraphUpdate(MemURI.create(uri)); if (uuid != null) { currentNamedGraphUpdate.setUUID(MemURI.create(uuid)); } String revision = parser.getAttributeValue(null, SerializationConstants.revision); if (revision != null) { currentNamedGraphUpdate.setRevision(Long.parseLong(revision)); } } else if (SerializationConstants.additions.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getAdditions(); } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getMetaAdditions(); } else if (SerializationConstants.removals.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getRemovals(); } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getMetaRemovals(); } else if (SerializationConstants.statement.equals(parser.getLocalName())) { } else if (SerializationConstants.subject.equals(parser.getLocalName())) { nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType); } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { } else if (SerializationConstants.object.equals(parser.getLocalName())) { nodeType = parser.getAttributeValue(null, SerializationConstants.objectType); language = parser.getAttributeValue(null, SerializationConstants.language); datatype = parser.getAttributeValue(null, SerializationConstants.dataType); } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { } break; case XMLStreamConstants.END_ELEMENT: if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { handler.handleNamedGraphUpdate(currentNamedGraphUpdate); currentNamedGraphUpdate = null; } else if (SerializationConstants.additions.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.removals.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.statement.equals(parser.getLocalName())) { currentStatements.add(Constants.valueFactory.createStatement(currentSubject, currentPredicate, currentObject, currentNamedGraphURI)); } else if (SerializationConstants.subject.equals(parser.getLocalName())) { if (NodeType.BNODE.name().equals(nodeType)) { currentSubject = Constants.valueFactory.createBNode(currentValue); } else { currentSubject = Constants.valueFactory.createURI(currentValue); } currentValue = null; nodeType = null; } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { currentPredicate = Constants.valueFactory.createURI(currentValue); currentValue = null; } else if (SerializationConstants.object.equals(parser.getLocalName())) { if (NodeType.BNODE.name().equals(nodeType)) { currentObject = Constants.valueFactory.createBNode(currentValue); } else if (NodeType.URI.name().equals(nodeType)) { currentObject = Constants.valueFactory.createURI(currentValue); } else if (NodeType.LITERAL.name().equals(nodeType)) { if (Base64.isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) { currentValue = new String( Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)), Constants.byteEncoding); } if (datatype != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, Constants.valueFactory.createURI(datatype)); } else if (language != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, language); } else { currentObject = Constants.valueFactory.createLiteral(currentValue); } } currentValue = null; nodeType = null; language = null; datatype = null; } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { currentNamedGraphURI = Constants.valueFactory.createURI(currentValue); currentValue = null; } break; case XMLStreamConstants.CHARACTERS: currentValue = parser.getText(); break; case XMLStreamConstants.CDATA: currentValue = parser.getText(); break; } } parser.close(); } catch (XMLStreamException ex) { throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage()); } catch (UnsupportedEncodingException uee) { throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee); } }
From source file:org.openanzo.services.serialization.XMLUpdatesReader.java
/** * Parse the data within the reader, passing the results to the IRepositoryHandler * //from w w w. ja v a 2 s . c om * @param reader * reader containing the data * @param handler * Handler which will handle the elements within the data * @throws AnzoException */ private void parseUpdateTransactions(Reader reader, final IUpdatesHandler handler) throws AnzoException { try { XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if (SerializationConstants.transaction.equals(parser.getLocalName())) { currentTransaction = parseTransaction(parser); } else if (SerializationConstants.transactionContext.equals(parser.getLocalName())) { currentStatements = currentTransaction.getTransactionContext(); } else if (SerializationConstants.preconditions.equals(parser.getLocalName())) { currentStatements = new ArrayList<Statement>(); } else if (SerializationConstants.namedGraphUpdates.equals(parser.getLocalName())) { currentValue = null; } else if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { String uri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri); String uuid = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID); currentNamedGraphUpdate = new NamedGraphUpdate(MemURI.create(uri)); if (uuid != null) { currentNamedGraphUpdate.setUUID(MemURI.create(uuid)); } String revision = parser.getAttributeValue(null, SerializationConstants.revision); if (revision != null) { currentNamedGraphUpdate.setRevision(Long.parseLong(revision)); } } else if (SerializationConstants.additions.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getAdditions(); } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getMetaAdditions(); } else if (SerializationConstants.removals.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getRemovals(); } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) { currentStatements = currentNamedGraphUpdate.getMetaRemovals(); } else if (SerializationConstants.statement.equals(parser.getLocalName())) { } else if (SerializationConstants.subject.equals(parser.getLocalName())) { nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType); } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { } else if (SerializationConstants.object.equals(parser.getLocalName())) { nodeType = parser.getAttributeValue(null, SerializationConstants.objectType); language = parser.getAttributeValue(null, SerializationConstants.language); datatype = parser.getAttributeValue(null, SerializationConstants.dataType); } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { } else if (SerializationConstants.errorResult.equals(parser.getLocalName())) { String errorCodeStr = parser.getAttributeValue(null, SerializationConstants.errorCode); errorCode = Long.parseLong(errorCodeStr); errorArgs = new ArrayList<String>(); } else if (SerializationConstants.errorMessageArg.equals(parser.getLocalName())) { } break; case XMLStreamConstants.END_ELEMENT: if (SerializationConstants.transaction.equals(parser.getLocalName())) { handler.handleTransaction(currentTransaction); currentTransaction = null; } else if (SerializationConstants.transactionContext.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.preconditions.equals(parser.getLocalName())) { currentTransaction.getPreconditions() .addAll(CommonSerializationUtils.parsePreconditionStatements(currentStatements)); } else if (SerializationConstants.namedGraphUpdates.equals(parser.getLocalName())) { if (currentValue != null) currentTransaction.getUpdatedNamedGraphRevisions() .putAll(CommonSerializationUtils.readNamedGraphRevisions(currentValue)); } else if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { currentTransaction.addNamedGraphUpdate(currentNamedGraphUpdate); } else if (SerializationConstants.additions.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.removals.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) { currentStatements = null; } else if (SerializationConstants.statement.equals(parser.getLocalName())) { currentStatements.add(Constants.valueFactory.createStatement(currentSubject, currentPredicate, currentObject, currentNamedGraphURI)); } else if (SerializationConstants.subject.equals(parser.getLocalName())) { if (NodeType.BNODE.name().equals(nodeType)) { currentSubject = Constants.valueFactory.createBNode(currentValue); } else { currentSubject = Constants.valueFactory.createURI(currentValue); } currentValue = null; nodeType = null; } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { currentPredicate = Constants.valueFactory.createURI(currentValue); currentValue = null; } else if (SerializationConstants.object.equals(parser.getLocalName())) { if (NodeType.BNODE.name().equals(nodeType)) { currentObject = Constants.valueFactory.createBNode(currentValue); } else if (NodeType.URI.name().equals(nodeType)) { currentObject = Constants.valueFactory.createURI(currentValue); } else if (NodeType.LITERAL.name().equals(nodeType)) { if (currentValue == null) { currentValue = ""; } else if (Base64.isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) { currentValue = new String( Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)), Constants.byteEncoding); } if (datatype != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, Constants.valueFactory.createURI(datatype)); } else if (language != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, language); } else { currentObject = Constants.valueFactory.createLiteral(currentValue); } } currentValue = null; nodeType = null; language = null; datatype = null; } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { currentNamedGraphURI = Constants.valueFactory.createURI(currentValue); currentValue = null; } else if (SerializationConstants.errorResult.equals(parser.getLocalName())) { currentTransaction.getErrors() .add(new AnzoException(errorCode, errorArgs.toArray(new String[0]))); errorCode = 0; errorArgs = null; } else if (SerializationConstants.errorMessageArg.equals(parser.getLocalName())) { errorArgs.add(currentValue); currentValue = null; } break; case XMLStreamConstants.CHARACTERS: if (parser.hasText()) currentValue = parser.getText(); break; case XMLStreamConstants.CDATA: if (parser.hasText()) currentValue = parser.getText(); break; } } parser.close(); } catch (XMLStreamException ex) { throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage()); } catch (UnsupportedEncodingException uee) { throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee); } }
From source file:org.sipfoundry.sipxconfig.security.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"); }//from w w w .j a v a 2 s .c o 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 + "'"); } // START SIPXECS CUSTOM CODE: XX-8253 // commented original code //UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user, // user.getPassword()); // creates digest token to be handled by org.sipfoundry.sipxconfig.security.DaoAuthenticationProvider UsernamePasswordAuthenticationToken authRequest = new DigestUsernamePasswordAuthenticationToken(user, user.getPassword()); // END SIPXECS CUSTOM CODE: XX-8253 authRequest.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext().setAuthentication(authRequest); } chain.doFilter(request, response); }
From source file:org.sonar.api.config.AesCipherTest.java
@Test public void generateRandomSecretKey() { AesCipher cipher = new AesCipher(new Settings()); String key = cipher.generateRandomSecretKey(); assertThat(StringUtils.isNotBlank(key), is(true)); assertThat(Base64.isArrayByteBase64(key.getBytes()), is(true)); }