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

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

Introduction

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

Prototype

@Deprecated
    public static byte[] sha(String data) 

Source Link

Usage

From source file:org.apache.ace.authentication.processor.password.PasswordAuthenticationProcessor.java

/**
 * Hashes a given password using the current set hash method.
 * /*from  ww w  .j  a v  a  2 s .  co  m*/
 * @param password the password to hash, should not be <code>null</code>.
 * @return the hashed password, never <code>null</code>.
 */
private Object hashPassword(Object password) {
    if ("none".equalsIgnoreCase(m_passwordHashMethod)) {
        // Very special ROT26 hashing method...
        return password;
    }

    if ("md5".equalsIgnoreCase(m_passwordHashMethod)) {
        if (password instanceof byte[]) {
            return DigestUtils.md5((byte[]) password);
        }
        return DigestUtils.md5((String) password);
    }
    if ("sha1".equalsIgnoreCase(m_passwordHashMethod)) {
        if (password instanceof byte[]) {
            return DigestUtils.sha((byte[]) password);
        }
        return DigestUtils.sha((String) password);
    }
    if ("sha256".equalsIgnoreCase(m_passwordHashMethod)) {
        if (password instanceof byte[]) {
            return DigestUtils.sha256((byte[]) password);
        }
        return DigestUtils.sha256((String) password);
    }
    if ("sha384".equalsIgnoreCase(m_passwordHashMethod)) {
        if (password instanceof byte[]) {
            return DigestUtils.sha384((byte[]) password);
        }
        return DigestUtils.sha384((String) password);
    }
    if ("sha512".equalsIgnoreCase(m_passwordHashMethod)) {
        if (password instanceof byte[]) {
            return DigestUtils.sha512((byte[]) password);
        }
        return DigestUtils.sha512((String) password);
    }
    return password;
}

From source file:org.apache.ace.authentication.processor.password.PasswordAuthenticationProcessorTest.java

/**
 * Tests that updated does not throw an exception for a correct configuration.
 *//*from  w w w .  j a v a 2  s  .co m*/
@Test(groups = { UNIT })
public void testUpdatedDoesAcceptCorrectProperties() throws ConfigurationException {
    final String keyUsername = "foo";
    final String keyPassword = "bar";

    Dictionary<String, Object> props = new Hashtable<>();

    props.put(PROPERTY_KEY_USERNAME, keyUsername);
    props.put(PROPERTY_KEY_PASSWORD, keyPassword);
    props.put(PROPERTY_PASSWORD_HASHMETHOD, "sha1");

    PasswordAuthenticationProcessor processor = new PasswordAuthenticationProcessor();

    processor.updated(props);

    byte[] hashedPw = DigestUtils.sha("secret");

    // Test whether we can use the new properties...
    User user = mock(User.class);
    when(user.getName()).thenReturn("bob");
    when(user.hasCredential(eq(keyPassword), eq(hashedPw))).thenReturn(Boolean.TRUE);

    when(m_userAdmin.getUser(eq(keyUsername), eq("bob"))).thenReturn(user);

    User result = processor.authenticate(m_userAdmin, "bob", "secret");
    assert result != null : "Expected a valid user to be returned!";

    assert "bob".equals(user.getName()) : "Expected bob to be returned!";
}

From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java

/**
 * Sets the input for this composite. /*from   w  w w  . j av  a2 s  . c  o  m*/
 *
 * @param certificateChain certificate chain input
 */
public void setInput(X509Certificate[] certificateChain) {
    X509Certificate certificate = certificateChain[0];

    X500Principal issuedToPrincipal = certificate.getSubjectX500Principal();
    Map<String, String> issuedToAttributes = getAttributeMap(issuedToPrincipal);
    issuedToCN.setText(issuedToAttributes.get("CN")); //$NON-NLS-1$
    issuedToO.setText(issuedToAttributes.get("O")); //$NON-NLS-1$
    issuedToOU.setText(issuedToAttributes.get("OU")); //$NON-NLS-1$
    serialNumber.setText(certificate.getSerialNumber().toString(16));

    X500Principal issuedFromPrincipal = certificate.getIssuerX500Principal();
    Map<String, String> issuedFromAttributes = getAttributeMap(issuedFromPrincipal);
    issuedByCN.setText(issuedFromAttributes.get("CN")); //$NON-NLS-1$
    issuedByO.setText(issuedFromAttributes.get("O")); //$NON-NLS-1$
    issuedByOU.setText(issuedFromAttributes.get("OU")); //$NON-NLS-1$

    issuesOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotBefore()));
    expiresOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotAfter()));

    byte[] encoded2 = null;

    try {
        encoded2 = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
    }

    byte[] md5 = DigestUtils.md5(encoded2);
    String md5HexString = getHexString(md5);
    fingerprintMD5.setText(md5HexString);
    byte[] sha = DigestUtils.sha(encoded2);
    String shaHexString = getHexString(sha);
    fingerprintSHA1.setText(shaHexString);

    // Details: certificate chain
    CertificateChainItem parentItem = null;
    CertificateChainItem certificateItem = null;

    for (X509Certificate cert : certificateChain) {
        CertificateChainItem item = new CertificateChainItem(cert);

        if (parentItem != null) {
            item.child = parentItem;
            parentItem.parent = item;
        }

        if (certificateItem == null) {
            certificateItem = item;
        }

        parentItem = item;
    }

    hierarchyTreeViewer.setInput(new CertificateChainItem[] { parentItem });
    hierarchyTreeViewer.expandAll();
    hierarchyTreeViewer.setSelection(new StructuredSelection(certificateItem), true);

    // Details: 
    certificateTree.removeAll();
    populateCertificateTree();
    valueText.setText(StringUtils.EMPTY);
}

From source file:org.apache.shindig.common.crypto.BasicBlobCrypter.java

/**
 * Generates unique keys from a master key.
 *
 * @param label type of key to derive//from  w  ww .  j a va 2s  .c  o m
 * @param masterKey master key
 * @param len length of key needed, less than 20 bytes.  20 bytes are
 * returned if len is 0.
 *
 * @return a derived key of the specified length
 */
private byte[] deriveKey(byte label, byte[] masterKey, int len) {
    byte[] base = Crypto.concat(new byte[] { label }, masterKey);
    byte[] hash = DigestUtils.sha(base);
    if (len == 0) {
        return hash;
    }
    byte[] out = new byte[len];
    System.arraycopy(hash, 0, out, 0, out.length);
    return out;
}

From source file:org.apache.shindig.gadgets.HashLockedDomainService.java

private String getLockedDomain(Gadget gadget, String container) {
    String suffix = lockedSuffixes.get(container);
    if (suffix == null) {
        return null;
    }/*  w  ww.j av a 2  s  .  com*/
    byte[] sha1 = DigestUtils.sha(gadget.getSpec().getUrl().toString());
    String hash = new String(Base32.encodeBase32(sha1));
    return hash + suffix;
}

From source file:org.apache.shindig.gadgets.oauth.OAuthCommandLine.java

public static void main(String[] argv) throws Exception {
    Map<String, String> params = Maps.newHashMap();
    for (int i = 0; i < argv.length; i += 2) {
        params.put(argv[i], argv[i + 1]);
    }/* ww  w .  ja  v a  2s. com*/
    final String httpProxy = params.get("--httpProxy");
    final String consumerKey = params.get("--consumerKey");
    final String consumerSecret = params.get("--consumerSecret");
    final String xOauthRequestor = params.get("--requestorId");
    final String accessToken = params.get("--accessToken");
    final String tokenSecret = params.get("--tokenSecret");
    final String method = params.get("--method") == null ? "GET" : params.get("--method");
    String url = params.get("--url");
    String contentType = params.get("--contentType");
    String postBody = params.get("--postBody");
    String postFile = params.get("--postFile");
    String paramLocation = params.get("--paramLocation");
    String bodySigning = params.get("--bodySigning");

    HttpRequest request = new HttpRequest(Uri.parse(url));
    if (contentType != null) {
        request.setHeader("Content-Type", contentType);
    } else {
        request.setHeader("Content-Type", OAuth.FORM_ENCODED);
    }
    if (postBody != null) {
        request.setPostBody(postBody.getBytes());
    }
    if (postFile != null) {
        request.setPostBody(IOUtils.toByteArray(new FileInputStream(postFile)));
    }

    OAuthParamLocation paramLocationEnum = OAuthParamLocation.URI_QUERY;
    if (paramLocation != null) {
        paramLocationEnum = OAuthParamLocation.valueOf(paramLocation);
    }

    BodySigning bodySigningEnum = BodySigning.none;
    if (bodySigning != null) {
        bodySigningEnum = BodySigning.valueOf(bodySigning);
    }

    List<OAuth.Parameter> oauthParams = Lists.newArrayList();
    UriBuilder target = new UriBuilder(Uri.parse(url));
    String query = target.getQuery();
    target.setQuery(null);
    oauthParams.addAll(OAuth.decodeForm(query));
    if (OAuth.isFormEncoded(contentType) && request.getPostBodyAsString() != null) {
        oauthParams.addAll(OAuth.decodeForm(request.getPostBodyAsString()));
    } else if (bodySigningEnum == BodySigning.legacy) {
        oauthParams.add(new OAuth.Parameter(request.getPostBodyAsString(), ""));
    } else if (bodySigningEnum == BodySigning.hash) {
        oauthParams.add(new OAuth.Parameter(OAuthConstants.OAUTH_BODY_HASH, new String(
                Base64.encodeBase64(DigestUtils.sha(request.getPostBodyAsString().getBytes())), "UTF-8")));
    }

    if (consumerKey != null) {
        oauthParams.add(new OAuth.Parameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey));
    }
    if (xOauthRequestor != null) {
        oauthParams.add(new OAuth.Parameter("xoauth_requestor_id", xOauthRequestor));
    }

    OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, null);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.accessToken = accessToken;
    accessor.tokenSecret = tokenSecret;
    OAuthMessage message = accessor.newRequestMessage(method, target.toString(), oauthParams);

    List<Map.Entry<String, String>> entryList = OAuthRequest.selectOAuthParams(message);

    switch (paramLocationEnum) {
    case AUTH_HEADER:
        request.addHeader("Authorization", OAuthRequest.getAuthorizationHeader(entryList));
        break;

    case POST_BODY:
        if (!OAuth.isFormEncoded(contentType)) {
            throw new RuntimeException("OAuth param location can only be post_body if post body if of "
                    + "type x-www-form-urlencoded");
        }
        String oauthData = OAuthUtil.formEncode(message.getParameters());
        request.setPostBody(CharsetUtil.getUtf8Bytes(oauthData));
        break;

    case URI_QUERY:
        request.setUri(Uri.parse(OAuthUtil.addParameters(request.getUri().toString(), entryList)));
        break;
    }
    request.setMethod(method);

    HttpFetcher fetcher = new BasicHttpFetcher(httpProxy);
    HttpResponse response = fetcher.fetch(request);

    System.out.println("Request ------------------------------");
    System.out.println(request.toString());
    System.out.println("Response -----------------------------");
    System.out.println(response.toString());
}

From source file:org.apache.shindig.gadgets.oauth.OAuthRequest.java

/**
 * Start with an HttpRequest.//from ww  w. ja  v a  2  s.  c  o m
 * Throw if there are any attacks in the query.
 * Throw if there are any attacks in the post body.
 * Build up OAuth parameter list.
 * Sign it.
 * Add OAuth parameters to new request.
 * Send it.
 */
public HttpRequest sanitizeAndSign(HttpRequest base, List<Parameter> params, boolean tokenEndpoint)
        throws OAuthRequestException {
    if (params == null) {
        params = Lists.newArrayList();
    }
    UriBuilder target = new UriBuilder(base.getUri());
    String query = target.getQuery();
    target.setQuery(null);
    params.addAll(sanitize(OAuth.decodeForm(query)));

    switch (OAuthUtil.getSignatureType(tokenEndpoint, base.getHeader("Content-Type"))) {
    case URL_ONLY:
        break;
    case URL_AND_FORM_PARAMS:
        try {
            params.addAll(sanitize(OAuth.decodeForm(base.getPostBodyAsString())));
        } catch (IllegalArgumentException e) {
            // Occurs if OAuth.decodeForm finds an invalid URL to decode.
            throw new OAuthRequestException(OAuthError.INVALID_REQUEST, "Could not decode body", e);
        }
        break;
    case URL_AND_BODY_HASH:
        try {
            byte[] body = IOUtils.toByteArray(base.getPostBody());
            byte[] hash = DigestUtils.sha(body);
            String b64 = new String(Base64.encodeBase64(hash), Charsets.UTF_8.name());
            params.add(new Parameter(OAuthConstants.OAUTH_BODY_HASH, b64));
        } catch (IOException e) {
            throw new OAuthRequestException(OAuthError.UNKNOWN_PROBLEM, "Error taking body hash", e);
        }
        break;
    }

    // authParams are parameters prefixed with 'xoauth' 'oauth' or 'opensocial',
    // trusted parameters have ability to override these parameters.
    List<Parameter> authParams = Lists.newArrayList();

    addIdentityParams(authParams);

    addSignatureParams(authParams);

    overrideParameters(authParams);

    params.addAll(authParams);

    try {
        OAuthMessage signed = OAuthUtil.newRequestMessage(accessorInfo.getAccessor(), base.getMethod(),
                target.toString(), params);
        HttpRequest oauthHttpRequest = createHttpRequest(base, selectOAuthParams(signed));
        // Following 302s on OAuth responses is unlikely to be productive.
        oauthHttpRequest.setFollowRedirects(false);
        return oauthHttpRequest;
    } catch (OAuthException e) {
        throw new OAuthRequestException(OAuthError.UNKNOWN_PROBLEM, "Error signing message", e);
    }
}

From source file:org.apache.shindig.gadgets.oauth.testing.FakeOAuthServiceProvider.java

private void validateMessage(OAuthAccessor accessor, MessageInfo info, boolean tokenEndpoint)
        throws OAuthException, IOException, URISyntaxException {
    OAuthValidator validator = new FakeTimeOAuthValidator();
    validator.validateMessage(info.message, accessor);

    String bodyHash = info.message.getParameter("oauth_body_hash");
    if (tokenEndpoint && bodyHash != null) {
        throw new RuntimeException("Can't have body hash on token endpoints");
    }/*from www .  j  a  va  2s .c  o m*/
    SignatureType sigType = OAuthUtil.getSignatureType(tokenEndpoint, info.request.getHeader("Content-Type"));
    switch (sigType) {
    case URL_ONLY:
        break;
    case URL_AND_FORM_PARAMS:
        if (bodyHash != null) {
            throw new RuntimeException("Can't have body hash in form-encoded request");
        }
        break;
    case URL_AND_BODY_HASH:
        if (bodyHash == null) {
            throw new RuntimeException("Requiring oauth_body_hash parameter");
        }
        byte[] received = Base64.decodeBase64(CharsetUtil.getUtf8Bytes(bodyHash));
        byte[] expected = DigestUtils.sha(info.rawBody);
        if (!Arrays.equals(received, expected)) {
            throw new RuntimeException("oauth_body_hash mismatch");
        }
    }

    // Most OAuth service providers are much laxer than this about checking nonces (rapidly
    // changing server-side state scales badly), but we are very strict in test cases.
    String nonceKey = info.message.getConsumerKey() + ',' + info.message.getParameter("oauth_nonce");

    CachedObject<OAuthMessage> previousMessage = nonceCache.getElement(nonceKey);
    if (previousMessage != null) {
        throw new RuntimeException(
                "Reused nonce, old message = " + previousMessage.obj + ", new message " + info.message);
    }
    nonceCache.addElement(nonceKey, info.message, TimeUnit.SECONDS.toMillis(10 * 60));
}

From source file:org.apache.shindig.gadgets.uri.HashShaLockedDomainPrefixGenerator.java

public String getLockedDomainPrefix(Uri gadgetUri) {
    byte[] sha1 = DigestUtils.sha(gadgetUri.toString());
    return new String(Base32.encodeBase32(sha1)); // a hash
}

From source file:org.apache.shindig.social.core.oauth.FakeOAuthRequest.java

public FakeHttpServletRequest sign(String consumerKey, String consumerSecret, String requestor, String token,
        String tokenSecret, OAuthParamLocation paramLocationEnum, BodySigning bodySigning) throws Exception {
    FakeHttpServletRequest request = new FakeHttpServletRequest(url);

    List<OAuth.Parameter> oauthParams = Lists.newArrayList();
    UriBuilder target = new UriBuilder(Uri.parse(url));
    String query = target.getQuery();
    target.setQuery(null);//from  ww w . ja  v  a2 s.com
    oauthParams.addAll(OAuth.decodeForm(query));

    if (body != null) {
        if (OAuth.isFormEncoded(contentType)) {
            oauthParams.addAll(OAuth.decodeForm(body));
        } else if (bodySigning == BodySigning.LEGACY) {
            oauthParams.add(new OAuth.Parameter(body, ""));
        } else if (bodySigning == BodySigning.HASH) {
            oauthParams.add(new OAuth.Parameter(OAuthConstants.OAUTH_BODY_HASH,
                    new String(Base64.encodeBase64(DigestUtils.sha(body.getBytes())), "UTF-8")));
        }
    }

    oauthParams.add(new OAuth.Parameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey));
    oauthParams.add(new OAuth.Parameter("xoauth_requestor_id", requestor));

    OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, null);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    if (!StringUtils.isEmpty(token)) {
        accessor.accessToken = token;
        accessor.tokenSecret = tokenSecret;
    }
    OAuthMessage message = accessor.newRequestMessage(method, target.toString(), oauthParams);

    List<Map.Entry<String, String>> entryList = selectOAuthParams(message);

    switch (paramLocationEnum) {
    case AUTH_HEADER:
        request.setHeader("Authorization", getAuthorizationHeader(entryList));
        break;
    case POST_BODY:
        if (!OAuth.isFormEncoded(contentType)) {
            throw new RuntimeException("OAuth param location can only be post_body if post body is of "
                    + "type x-www-form-urlencoded");
        }
        // All message params should be added if oauth params are added to body
        for (Map.Entry<String, String> param : message.getParameters()) {
            request.setParameter(param.getKey(), true, param.getValue());
        }
        String oauthData = OAuth.formEncode(message.getParameters());
        request.setPostData(CharsetUtil.getUtf8Bytes(oauthData));
        break;
    case URI_QUERY:
        request.setQueryString(Uri.parse(OAuth.addParameters(url, entryList)).getQuery());
        break;
    }

    if (body != null && paramLocationEnum != OAuthParamLocation.POST_BODY) {
        request.setContentType(contentType);
        request.setPostData(body, "UTF-8");
        if (contentType.contains(OAuth.FORM_ENCODED)) {
            List<OAuth.Parameter> bodyParams = OAuth.decodeForm(body);
            for (OAuth.Parameter bodyParam : bodyParams) {
                request.setParameter(bodyParam.getKey(), bodyParam.getValue());
            }
        }
    }
    request.setMethod(method);

    return request;
}