Example usage for org.apache.commons.codec.digest DigestUtils sha1

List of usage examples for org.apache.commons.codec.digest DigestUtils sha1

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils sha1.

Prototype

public static byte[] sha1(String data) 

Source Link

Usage

From source file:org.springside.fi.common.httpclient.HttpClientTemplate.java

/**
 * Execute post method.//from w w w  . j av a  2  s .c  om
 * 
 * @param   uri             URI to use when processing this HTTP request instead 
 *                          of using the default URI.
 * @param   requestPayload  <code>RequestEntity</code> data to post.
 * @param   hParams         Parameters for the HTTP post.
 * @param   callback        Callback with HTTP method's response.
 */
public byte[] executePostMethod(String uri, RequestEntity requestPayload, Map<String, String> hParams) {
    PostMethod post = new PostMethod(uri);

    //??
    String nonce = getRandom();
    String timestamp = String.valueOf(new Date().getTime() / 1000);
    byte[] sign = DigestUtils.sha1(appSecret + nonce + timestamp);
    String signature = "";
    for (int i = 0; i < sign.length; i++) {
        signature += Integer.toString((sign[i] & 0xff) + 0x100, 16).substring(1);
    }
    post.addRequestHeader("App-Key", appKey);
    post.addRequestHeader("Nonce", nonce);
    post.addRequestHeader("Timestamp", timestamp);
    post.addRequestHeader("Signature", signature);

    if (requestPayload != null) {
        post.setRequestEntity(requestPayload);
    }

    processHttpMethodParams(post, hParams);

    return processHttpMethod(post);
}

From source file:org.tallison.cc.CCGetter.java

private void fetch(CCIndexRecord r, Path rootDir, BufferedWriter writer) throws IOException {
    Path targFile = rootDir.resolve(r.getDigest().substring(0, 2) + "/" + r.getDigest());

    if (Files.isRegularFile(targFile)) {
        writeStatus(r, FETCH_STATUS.ALREADY_IN_REPOSITORY, writer);
        logger.info("already retrieved:" + targFile.toAbsolutePath());
        return;//from   w ww. ja  va 2  s .co  m
    }

    String url = AWS_BASE + r.getFilename();
    URI uri = null;
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        logger.warn("Bad url: " + url);
        writeStatus(r, FETCH_STATUS.BAD_URL, writer);
        return;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpHost target = new HttpHost(uri.getHost());
    String urlPath = uri.getRawPath();
    if (uri.getRawQuery() != null) {
        urlPath += "?" + uri.getRawQuery();
    }
    HttpGet httpGet = null;
    try {
        httpGet = new HttpGet(urlPath);
    } catch (Exception e) {
        logger.warn("bad path " + uri.toString(), e);
        writeStatus(r, FETCH_STATUS.BAD_URL, writer);
        return;
    }
    if (proxyHost != null && proxyPort > -1) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);
    }
    httpGet.addHeader("Range", r.getOffsetHeader());
    HttpCoreContext coreContext = new HttpCoreContext();
    CloseableHttpResponse httpResponse = null;
    URI lastURI = null;
    try {
        httpResponse = httpClient.execute(target, httpGet, coreContext);
        RedirectLocations redirectLocations = (RedirectLocations) coreContext
                .getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);
        if (redirectLocations != null) {
            for (URI redirectURI : redirectLocations.getAll()) {
                lastURI = redirectURI;
            }
        } else {
            lastURI = httpGet.getURI();
        }
    } catch (IOException e) {
        logger.warn("IOException for " + uri.toString(), e);
        writeStatus(r, FETCH_STATUS.FETCHED_IO_EXCEPTION, writer);
        return;
    }
    lastURI = uri.resolve(lastURI);

    if (httpResponse.getStatusLine().getStatusCode() != 200
            && httpResponse.getStatusLine().getStatusCode() != 206) {
        logger.warn("Bad status for " + uri.toString() + " : " + httpResponse.getStatusLine().getStatusCode());
        writeStatus(r, FETCH_STATUS.FETCHED_NOT_200, writer);
        return;
    }
    Path tmp = null;
    Header[] headers = null;
    boolean isTruncated = false;
    try {
        //this among other parts is plagiarized from centic9's CommonCrawlDocumentDownload
        //probably saved me hours.  Thank you, Dominik!
        tmp = Files.createTempFile("cc-getter", "");
        try (InputStream is = new GZIPInputStream(httpResponse.getEntity().getContent())) {
            WARCRecord warcRecord = new WARCRecord(new FastBufferedInputStream(is), "", 0);
            ArchiveRecordHeader archiveRecordHeader = warcRecord.getHeader();
            if (archiveRecordHeader.getHeaderFields().containsKey(WARCConstants.HEADER_KEY_TRUNCATED)) {
                isTruncated = true;
            }
            headers = LaxHttpParser.parseHeaders(warcRecord, "UTF-8");

            Files.copy(warcRecord, tmp, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        writeStatus(r, null, headers, 0L, isTruncated, FETCH_STATUS.FETCHED_IO_EXCEPTION_READING_ENTITY,
                writer);
        deleteTmp(tmp);
        return;
    }

    String digest = null;
    long tmpLength = 0l;
    try (InputStream is = Files.newInputStream(tmp)) {
        digest = base32.encodeAsString(DigestUtils.sha1(is));
        tmpLength = Files.size(tmp);
    } catch (IOException e) {
        writeStatus(r, null, headers, tmpLength, isTruncated, FETCH_STATUS.FETCHED_IO_EXCEPTION_SHA1, writer);
        logger.warn("IOException during digesting: " + tmp.toAbsolutePath());
        deleteTmp(tmp);
        return;
    }

    if (Files.exists(targFile)) {
        writeStatus(r, digest, headers, tmpLength, isTruncated, FETCH_STATUS.ALREADY_IN_REPOSITORY, writer);
        deleteTmp(tmp);
        return;
    }
    try {
        Files.createDirectories(targFile.getParent());
        Files.copy(tmp, targFile);
    } catch (IOException e) {
        writeStatus(r, digest, headers, tmpLength, isTruncated,
                FETCH_STATUS.FETCHED_EXCEPTION_COPYING_TO_REPOSITORY, writer);
        deleteTmp(tmp);

    }
    writeStatus(r, digest, headers, tmpLength, isTruncated, FETCH_STATUS.ADDED_TO_REPOSITORY, writer);
    deleteTmp(tmp);
}

From source file:org.tallison.cc.warc.AbstractExtractor.java

String digest(byte[] bytes) {
    return base32.encodeToString(DigestUtils.sha1(bytes));
}

From source file:org.tsaap.lti.tp.ResourceLink.java

/**
 * Send a service request to the tool consumer.
 *
 * @param type Message type//from www.  jav  a  2s  .co  m
 * @param url  URL to send request to
 * @param xml  XML of message request
 * @return <code>true</code> if the request successfully obtained a response
 */
private boolean doLTI11Service(String type, String url, String xml) {

    this.extResponse = null;
    if ((url != null) && (url.length() > 0)) {
        String messageId = UUID.randomUUID().toString();
        StringBuilder xmlRequest = new StringBuilder();
        xmlRequest.append("<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n");
        xmlRequest.append(
                "<imsx_POXEnvelopeRequest xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n");
        xmlRequest.append("  <imsx_POXHeader>\n");
        xmlRequest.append("    <imsx_POXRequestHeaderInfo>\n");
        xmlRequest.append("      <imsx_version>V1.0</imsx_version>\n");
        xmlRequest.append("      <imsx_messageIdentifier>").append(messageId)
                .append("</imsx_messageIdentifier>\n");
        xmlRequest.append("    </imsx_POXRequestHeaderInfo>\n");
        xmlRequest.append("  </imsx_POXHeader>\n");
        xmlRequest.append("  <imsx_POXBody>\n");
        xmlRequest.append("    <").append(type).append("Request>\n");
        xmlRequest.append(xml);
        xmlRequest.append("    </").append(type).append("Request>\n");
        xmlRequest.append("  </imsx_POXBody>\n");
        xmlRequest.append("</imsx_POXEnvelopeRequest>\n");
        // Calculate body hash
        String hash = Base64.encodeBase64String(DigestUtils.sha1(xmlRequest.toString()));
        Map<String, String> params = new HashMap<String, String>();
        params.put("oauth_body_hash", hash);
        HashSet<Map.Entry<String, String>> httpParams = new HashSet<Map.Entry<String, String>>();
        httpParams.addAll(params.entrySet());
        // Check for query parameters which need to be included in the signature
        Map<String, String> queryParams = new HashMap<String, String>();
        String urlNoQuery = url;
        try {
            URI uri = new URI(url, false);
            String query = uri.getQuery();
            if (query != null) {
                urlNoQuery = urlNoQuery.substring(0, urlNoQuery.length() - query.length() - 1);
                String[] queryItems = query.split("&");
                for (int i = 0; i < queryItems.length; i++) {
                    String[] queryItem = queryItems[i].split("=", 2);
                    if (queryItem.length > 1) {
                        queryParams.put(queryItem[0], queryItem[1]);
                    } else {
                        queryParams.put(queryItem[0], "");
                    }
                }
                httpParams.addAll(queryParams.entrySet());
            }
        } catch (URIException e) {
        }
        // Add OAuth signature
        Map<String, String> header = new HashMap<String, String>();
        OAuthMessage oAuthMessage = new OAuthMessage("POST", urlNoQuery, httpParams);
        OAuthConsumer oAuthConsumer = new OAuthConsumer("about:blank", this.consumer.getKey(),
                this.consumer.getSecret(), null);
        OAuthAccessor oAuthAccessor = new OAuthAccessor(oAuthConsumer);
        try {
            oAuthMessage.addRequiredParameters(oAuthAccessor);
            header.put("Authorization", oAuthMessage.getAuthorizationHeader(null));
            header.put("Content-Type", "application/xml");
        } catch (OAuthException e) {
        } catch (URISyntaxException e) {
        } catch (IOException e) {
        }
        StringRequestEntity entity = new StringRequestEntity(xmlRequest.toString());
        // Connect to tool consumer
        this.extResponse = this.doPostRequest(url, Utils.getHTTPParams(params), header, entity);
        // Parse XML response
        if (this.extResponse != null) {
            this.extDoc = Utils.getXMLDoc(this.extResponse);
            boolean ok = this.extDoc != null;
            if (ok) {
                Element el = Utils.getXmlChild(this.extDoc.getRootElement(), "imsx_statusInfo");
                ok = el != null;
                if (ok) {
                    String responseCode = Utils.getXmlChildValue(el, "imsx_codeMajor");
                    ok = responseCode != null;
                    if (ok) {
                        ok = responseCode.equals("success");
                    }
                }
            }
            if (!ok) {
                this.extResponse = null;
            }
        }
    }

    return (this.extResponse != null);

}

From source file:org.xwiki.contrib.authentication.jdbc.internal.DefaultUserSynchronizer.java

@SuppressWarnings("unchecked")
private Map<String, String> getXWikiUserProperties(XWikiDocument userDocument)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    Map<String, String> userProperties = new HashMap<String, String>();
    userProperties.put("login", userDocument.getDocumentReference().getName());
    String password = getRequestPassword();
    if (password != null) {
        userProperties.put("password", password);
        userProperties.put("passwordsha1base64", Base64.encodeBase64String(DigestUtils.sha1(password)));
    }/*w  ww  .j ava2s .  co  m*/

    // object fields
    BaseObject userObject = userDocument.getXObject(USERCLASS_REFERENCE);

    for (BaseProperty<EntityReference> property : (Collection<BaseProperty<EntityReference>>) userObject
            .getFieldList()) {
        if (!property.getName().equals("password")) {
            userProperties.put(property.getName(), property.toText());
        }
    }

    // name
    String firstName = userProperties.get("first_name");
    String lastName = userProperties.get("last_name");
    if (StringUtils.isNotEmpty(firstName)) {
        if (StringUtils.isNotEmpty(lastName)) {
            userProperties.put("name", firstName + ' ' + lastName);
        } else {
            userProperties.put("name", firstName);
        }
    } else if (StringUtils.isNotEmpty(lastName)) {
        userProperties.put("name", lastName);
    }

    return userProperties;
}

From source file:org.xwiki.contrib.authentication.jdbc.internal.Sha1Base64PasswordHasher.java

@Override
public String create(String password) {
    return Base64.encodeBase64String(DigestUtils.sha1(password));
}

From source file:org.xwiki.contrib.authentication.jdbc.XWikiJDBCAuthenticator.java

private Map<String, Object> checkJDBCAuth(String login, String password, XWikiContext context)
        throws Exception {
    this.configuration.checkDriver();

    String selectQuery = this.configuration.getSelectQuery();

    if (selectQuery == null) {
        throw new Exception(
                "Select query should be provided in xwiki.authentication.jdbc.mapping.select.query");
    }//from  w w  w .j a  va 2  s  .c o m

    String[] selectQueryParameters = this.configuration.getSelectParameters();

    Connection connection = this.userSynchronizer.getConnection();

    PreparedStatement statement = null;
    try {
        statement = connection.prepareStatement(selectQuery);

        Map<String, String> fields = new HashMap<String, String>();
        fields.put("login", login);
        fields.put("password", password);
        // FIXME: crappy hack mostly here because MySQL 5 does not support it natively
        fields.put("passwordsha1base64", Base64.encodeBase64String(DigestUtils.sha1(password)));

        int index = 1;
        for (String field : selectQueryParameters) {
            statement.setString(index++, fields.get(field));
        }

        ResultSet resultSet = statement.executeQuery();

        if (!resultSet.next()) {
            LOG.debug("SELECT query did not return any rows");
            return null;
        }

        String passwordColumn = configuration.getPasswordColumn();
        if (passwordColumn != null) {
            // check password
            String dbPassword = resultSet.getString(passwordColumn);

            PasswordHasher passwordHasher = componentManager.getInstance(PasswordHasher.class,
                    configuration.getPasswordHasher());

            if (!passwordHasher.verify(dbPassword, password)) {
                LOG.debug("Incorrect password for user {}", login);
                return null;
            }
        }

        // Sync properties
        Map<String, Object> userProperties = new HashMap<String, Object>();

        String[] selectQueryMapping = this.configuration.getSelectMapping();

        int columnCount = resultSet.getMetaData().getColumnCount();
        for (int i = 0; i < columnCount && i < selectQueryMapping.length; ++i) {
            String mappingField = selectQueryMapping[i];
            if (StringUtils.isNotEmpty(mappingField)) {
                String value = resultSet.getString(i + 1);

                userProperties.put(mappingField, value);
            }
        }

        return userProperties;
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}