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:eu.operando.operandoapp.database.DatabaseHelper.java

public void sendSettingsToServer(final String imei) {
    new Thread(new Runnable() {
        @Override//www. ja v  a 2s.c o  m
        public void run() {
            String xml_settings = exportAllPermissionsPerDomain();
            if (xml_settings != null) {
                try {
                    String urlParameters = "userxml=" + xml_settings + "&userID="
                            + Base64.encode(DigestUtils.sha1(imei), Base64.DEFAULT);
                    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
                    URL url = new URL(serverUrl + "/prefs");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(15000);
                    conn.setConnectTimeout(15000);
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                        wr.write(postData);
                    }
                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        //Do something on HTTP_OK ?????
                    } else {
                        throw new Exception();
                    }
                    Log.d("SENT", Integer.toString(responseCode));
                } catch (Exception e) {
                    //create a file as database to resend later
                    Writer writer = null;
                    try {
                        File file = new File(MainContext.INSTANCE.getContext().getFilesDir(), "resend.inf");
                        if (!file.exists()) {
                            writer = new BufferedWriter(new FileWriter(file));
                            writer.write("1"); //currently putting 1 for "true" to resend
                        }
                    } catch (Exception ex) {
                        ex.getMessage();
                    } finally {
                        try {
                            writer.close();
                        } catch (Exception ex) {
                            ex.getMessage();
                        }
                    }
                }
            }
        }
    }).start();
}

From source file:net.straylightlabs.tivolibre.TivoStreamChunk.java

public byte[] getKey(String mak) {
    byte[] makBytes = mak.getBytes();
    byte[] bytes = new byte[makBytes.length + dataSize];
    System.arraycopy(makBytes, 0, bytes, 0, makBytes.length);
    System.arraycopy(data, 0, bytes, makBytes.length, dataSize);
    return DigestUtils.sha1(bytes);
}

From source file:net.straylightlabs.tivolibre.TuringDecoder.java

private void prepareFrameHelper(TuringStream stream, int streamId, int blockId) {
    // Update our key for the current stream and block
    key[16] = (byte) streamId;
    key[17] = (byte) ((blockId & 0xFF0000) >> 16);
    key[18] = (byte) ((blockId & 0x00FF00) >> 8);
    key[19] = (byte) (blockId & 0x0000FF);

    byte[] shortenedKey = new byte[SHORTENED_KEY_LENGTH];
    System.arraycopy(key, 0, shortenedKey, 0, SHORTENED_KEY_LENGTH);
    byte[] turkey = DigestUtils.sha1(shortenedKey);
    //        TivoDecoder.logger.debug("prepareFrameHelper(): turkey={}", DigestUtils.sha1Hex(shortenedKey));
    byte[] turiv = DigestUtils.sha1(key);
    //        TivoDecoder.logger.debug("prepareFrameHelper(): turiv={}", DigestUtils.sha1Hex(key));

    stream.reset(streamId, blockId, turkey, turiv);
}

From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {//from w ww .  j a v  a2 s.  co  m
            X509Certificate caCert = (X509Certificate) sslKeyStore
                    .getCertificate(KeyToolUtils.getRootCAalias());
            if (caCert == null) {
                return new String[] { "Could not find certificate" };
            }
            return new String[] { caCert.getSubjectX500Principal().toString(),
                    "Fingerprint(SHA1): "
                            + JOrphanUtils.baToHexString(DigestUtils.sha1(caCert.getEncoded()), ' '),
                    "Created: " + caCert.getNotBefore().toString() };
        } catch (GeneralSecurityException e) {
            LOG.error("Problem reading root CA from keystore", e);
            return new String[] { "Problem with root certificate", e.getMessage() };
        }
    }
    return null; // should not happen
}

From source file:org.hawkular.openshift.auth.BasicAuthentication.java

private boolean verifySHA1Password(String storedPassword, String passedPassword) {
    //Remove the SHA_PREFIX from the password string
    storedPassword = storedPassword.substring(SHA_PREFIX.length());

    //Get the SHA digest and encode it in Base64
    byte[] digestedPasswordBytes = DigestUtils.sha1(passedPassword);
    String digestedPassword = Base64.getEncoder().encodeToString(digestedPasswordBytes);

    //Check if the stored password matches the passed one
    if (digestedPassword.equals(storedPassword)) {
        return true;
    } else {//w  w w . j  av a 2 s.c om
        return false;
    }
}

From source file:org.hawkular.openshift.auth.BasicAuthenticator.java

private boolean verifySHA1Password(String storedPassword, String passedPassword) {
    //Remove the SHA_PREFIX from the password string
    storedPassword = storedPassword.substring(SHA_PREFIX.length());

    //Get the SHA digest and encode it in Base64
    byte[] digestedPasswordBytes = DigestUtils.sha1(passedPassword);
    String digestedPassword = Base64.getEncoder().encodeToString(digestedPasswordBytes);

    //Check if the stored password matches the passed one
    return digestedPassword.equals(storedPassword);
}

From source file:org.imsglobal.lti.toolProvider.ResourceLink.java

/**
 * Send a service request to the tool consumer.
 *
 * @param string type Message type value
 * @param string url  URL to send request to
 * @param string xml  XML of message request
 *
 * @return boolean True if the request successfully obtained a response
 *///  www  .ja  va 2 s  .c  o m
private boolean doLTI11Service(String type, String url, String xml) {

    boolean ok = false;
    this.extRequest = null;
    this.extRequestHeaders = null;
    this.extResponse = null;
    this.extResponseHeaders = null;
    if (StringUtils.isNotEmpty(url)) {
        String messageId = UUID.randomUUID().toString();
        String xmlRequest = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n"
                + "<imsx_POXEnvelopeRequest xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n"
                + "  <imsx_POXHeader>\n" + "    <imsx_POXRequestHeaderInfo>\n"
                + "      <imsx_version>V1.0</imsx_version>\n" + "      <imsx_messageIdentifier>" + id
                + "</imsx_messageIdentifier>\n" + "    </imsx_POXRequestHeaderInfo>\n" + "  </imsx_POXHeader>\n"
                + "  <imsx_POXBody>\n" + "    <" + type + "Request>\n" + xml + "    </" + type + "Request>\n"
                + "  </imsx_POXBody>\n" + "</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 {
            URL uri = new URL(url);
            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 (Exception e) {
            e.printStackTrace();
        }
        // 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) {
        }
        try {
            StringEntity entity = new StringEntity(xmlRequest);

            // Connect to tool consumer
            this.extResponse = doPostRequest(url, LTIUtil.getHTTPParams(params), header, entity);
            // Parse XML response
            if (this.extResponse != null) {
                this.extDoc = LTIUtil.getXMLDoc(extResponse);
                ok = this.extDoc != null;
                if (ok) {
                    Element el = LTIUtil.getXmlChild(this.extDoc.getRootElement(), "imsx_statusInfo");
                    ok = el != null;
                    if (ok) {
                        String responseCode = LTIUtil.getXmlChildValue(el, "imsx_codeMajor");
                        ok = responseCode != null;
                        if (ok) {
                            ok = responseCode.equals("success");
                        }
                    }
                }
                if (!ok) {
                    this.extResponse = null;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return (this.extResponse != null);

}

From source file:org.jenkinsci.plugins.htpasswd.HtPasswdFile.java

private static boolean validateShaPassword(String hashed, String plain) {
    String result = Base64.encodeBase64String(DigestUtils.sha1(plain));
    String hashOnly = hashed.substring(5); // skip "{SHA1}"
    return hashOnly.equals(result);
}

From source file:org.jnrain.mobile.ui.URLImageGetter.java

public Drawable getDrawable(String source) {
    Log.v(TAG, "Image request: " + source);

    // Transform source
    String actualSource = transformSource(source);
    Log.v(TAG, "Transformed => " + actualSource);

    // set image to loading state
    URLDrawable urlDrawable = new URLDrawable(_activity.getResources().getDrawable(R.drawable.loading_pic));

    // get the actual source
    String absoluteURL;/*from  w ww .java 2 s  . c  om*/

    if (actualSource.startsWith("http://") || actualSource.startsWith("https://")) {
        absoluteURL = actualSource;
    } else {
        absoluteURL = _baseURL + actualSource;
    }

    // make the request
    // hash the url
    // NOTE: we cannot directly use DigestUtils.sha1Hex, because of the
    // Android-specific quirk described in
    // stackoverflow.com/questions/9126567/method-not-found-using-digestutils-in-android
    String absURLHash = new String(Hex.encodeHex(DigestUtils.sha1(absoluteURL)));

    File cacheFile = new File(_activity.getApplication().getCacheDir(), absURLHash);
    BigBinaryRequest req = new BigBinaryRequest(absoluteURL, cacheFile);

    _listener.makeSpiceRequest(req, absURLHash, DurationInMillis.ONE_DAY,
            new URLImageRequestListener((TextView) _container, urlDrawable, absoluteURL, _activity));

    // return reference to URLDrawable where I will change with actual
    // image
    // from
    // the src tag
    return urlDrawable;
}

From source file:org.khannex.action.MakeSign.java

@Override
public Response execute(Context context) {
    Response retval = null;//from  ww  w.  j av a  2s .co m

    final Optional<String> param = getNextParam();
    if (param.isPresent()) {
        final CardIO cardio = new CardIO();
        try {
            final byte[] digest = DigestUtils.sha1(param.get());
            final byte[] pin = readPin().getBytes();

            cardio.connect();
            cardio.transmitReset().assertSuccessful();
            cardio.transmitSelectDf(new byte[] { 0x50, 0x11 }).assertSuccessful();
            cardio.transmitSelectDf(new byte[] { (byte) 0x90, 0x02 }).assertSuccessful();
            cardio.transmitVerify(pin).assertSuccessful();
            cardio.transmitSelectPrivateKey().assertSuccessful();
            final byte[] signature = cardio.transmitSign(digest).assertSuccessful().getData();

            final String result = Base64.getEncoder().encodeToString(getBerEncodedResult(digest, signature));
            retval = response().withResult(result).build();
        } catch (Exception ex) {
            context.setException(ex);

            retval = response().build();
        } finally {
            cardio.disconnect();
        }
    }

    return retval;
}