Example usage for java.security NoSuchAlgorithmException printStackTrace

List of usage examples for java.security NoSuchAlgorithmException printStackTrace

Introduction

In this page you can find the example usage for java.security NoSuchAlgorithmException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.dasein.cloud.gogrid.GoGridMethod.java

private @Nonnull String stupidPHPMD5(@Nonnull String toSign) throws InternalException, CloudException {
    try {/*from w  w w  .  java 2  s .co  m*/
        MessageDigest digest = MessageDigest.getInstance("MD5");

        return hex(digest.digest(toSign.getBytes("CP1252")));
    } catch (NoSuchAlgorithmException e) {
        logger.error("No support for MD5: " + e.getMessage());
        e.printStackTrace();
        throw new InternalException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error("No support for CP1252: " + e.getMessage());
        e.printStackTrace();
        throw new InternalException(e);
    }
}

From source file:org.fedoraproject.mobile.activities.NavigationDrawerActivity.java

@Nullable
private String getLibravatarImage(@NonNull String email) {
    StringBuilder hexString = null;
    final String MD5 = "MD5";
    try {//  w w  w .  j a  va 2 s .c om
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance(MD5);
        digest.update(email.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        hexString = new StringBuilder("https://seccdn.libravatar.org/avatar/");
        for (byte aMessageDigest : messageDigest) {
            String hash = Integer.toHexString(0xFF & aMessageDigest);
            while (hash.length() < 2)
                hash = "0" + hash;
            hexString.append(hash);
        }
        hexString.append("?s=");
        hexString.append(mPortrait.getMeasuredWidth());
        hexString.append("&d=http://cdn.libravatar.org/avatar/40f8d096a3777232204cb3f796c577b7?s=80&d=retro");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null != hexString ? hexString.toString() : null;
}

From source file:com.ichi2.libanki.Utils.java

/**
 * SHA1 checksum./*from w  w  w .  j  a v a 2  s  .  co  m*/
 * Equivalent to python sha1.hexdigest()
 *
 * @param data the string to generate hash from
 * @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data.
 */
public static String checksum(String data) {
    String result = "";
    if (data != null) {
        MessageDigest md = null;
        byte[] digest = null;
        try {
            md = MessageDigest.getInstance("SHA1");
            digest = md.digest(data.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            Timber.e(e, "Utils.checksum: No such algorithm.");
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            Timber.e(e, "Utils.checksum :: UnsupportedEncodingException");
            e.printStackTrace();
        }
        BigInteger biginteger = new BigInteger(1, digest);
        result = biginteger.toString(16);

        // pad with zeros to length of 40 This method used to pad
        // to the length of 32. As it turns out, sha1 has a digest
        // size of 160 bits, leading to a hex digest size of 40,
        // not 32.
        if (result.length() < 40) {
            String zeroes = "0000000000000000000000000000000000000000";
            result = zeroes.substring(0, zeroes.length() - result.length()) + result;
        }
    }
    return result;
}

From source file:org.apache.catalina.authenticator.DigestAuthenticator.java

public DigestAuthenticator() {
    super();/*w ww  .  ja v a 2 s. c o m*/
    try {
        if (md5Helper == null)
            md5Helper = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new IllegalStateException();
    }
}

From source file:cm.aptoide.pt.webservices.login.Login.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case CreateUser.REQUEST_CODE:
        switch (resultCode) {
        case RESULT_OK:
            if (!Login.isLoggedIn(context)) {
                try {
                    username_box.setText(data.getStringExtra("username"));
                    password_box.setText(data.getStringExtra("password"));
                    new CheckUserCredentials().execute(data.getStringExtra("username"),
                            Algorithms.computeSHA1sum(data.getStringExtra("password")), "true");
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }//from   www  .j  a v  a 2s.c o  m
            }
            break;

        default:
            break;
        }
        break;

    default:
        break;
    }
}

From source file:info.ajaxplorer.synchro.SyncJob.java

public static String computeMD5(File f) {
    MessageDigest digest;/*from www .jav  a  2 s  . c  o  m*/
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
        return "";
    }
    InputStream is;
    try {
        is = new FileInputStream(f);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return "";
    }
    byte[] buffer = new byte[8192];
    int read = 0;
    try {
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] md5sum = digest.digest();
        BigInteger bigInt = new BigInteger(1, md5sum);
        String output = bigInt.toString(16);
        if (output.length() < 32) {
            // PAD WITH 0
            while (output.length() < 32)
                output = "0" + output;
        }
        return output;
    } catch (IOException e) {
        //throw new RuntimeException("Unable to process file for MD5", e);
        return "";
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            //throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
            return "";
        }
    }
}

From source file:SandBox.testing.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SSLContext sslContext = null;
    try {/*from w w w.ja v a2s.c o m*/
        sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}

From source file:de.lsvn.dao.UserDao.java

public int validateToken(String token) {
    connection = DbUtil.getConnection();
    try {//from   w  w  w .j  av  a2  s  . c o  m

        Date date = new Date();
        long timestamp = date.getTime();

        PreparedStatement cleanupStatement = connection
                .prepareStatement("DELETE FROM password_change_requests WHERE Time < ?; ");
        cleanupStatement.setString(1, String.valueOf(timestamp - 3600000L));
        cleanupStatement.executeUpdate();
        DbUtil.closePreparedStatement(cleanupStatement);

        PreparedStatement preparedStatement = connection
                .prepareStatement("SELECT Token, Time, UserID FROM password_change_requests");
        ResultSet rs = preparedStatement.executeQuery();

        while (rs.next()) {
            try {
                String storedToken = rs.getString("Token");
                long storedTimestamp = rs.getLong("Time");
                int usr = rs.getInt("UserID");
                if (PasswordHash.validatePassword(token, storedToken)
                        && timestamp < storedTimestamp + 3600000) {
                    return usr;
                }
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvalidKeySpecException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        DbUtil.closeResultSet(rs);
        DbUtil.closePreparedStatement(preparedStatement);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtil.closeConnection(connection);
    }

    return -1;
}

From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java

/**
 * Key derivation method from the given password
 * @param password password to derive/*from   w w w .  j a  v a 2s  .c  o m*/
 */
private void derivateKey(char[] password) {
    //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption
    SecretKeyFactory factory;
    try {
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        //1000 iteration should be enough since the attack has to be done online and
        //salt changes for each group
        KeySpec spec = new PBEKeySpec(password, this.salt, 1000, 256);
        SecretKey tmp = factory.generateSecret(spec);
        secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
        this.isReady = true;
    } catch (NoSuchAlgorithmException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
    }

}

From source file:at.asitplus.regkassen.core.DemoCashBox.java

/**
 * calculate cryptographic chain value/*from ww  w. j  a  v  a  2s. c o  m*/
 *
 * @param previousReceiptJWSRepresentation previous receipt for chain value calculation, if null, the cashboxID is used
 * @param rkSuite                          rksuite that contains information of the to-be-used HASH-algorithm
 * @return
 */
protected String calculateChainValue(String previousReceiptJWSRepresentation, RKSuite rkSuite) {
    try {
        String inputForChainCalculation;

        //Detailspezifikation Abs 4 "Sig-Voriger-Beleg"
        //if the first receipt is stored, then the cashbox-identifier is hashed and is used as chaining value
        //otherwise the complete last receipt is hased and the result is used as chaining value
        if (previousReceiptJWSRepresentation == null) {
            inputForChainCalculation = cashBoxParameters.getCashBoxId();
        } else {
            inputForChainCalculation = previousReceiptJWSRepresentation;
        }

        //set hash algorithm from RK suite, in this case SHA-256
        MessageDigest md = MessageDigest.getInstance(rkSuite.getHashAlgorithmForPreviousSignatureValue());

        //calculate hash value
        md.update(inputForChainCalculation.getBytes());
        byte[] digest = md.digest();

        //extract number of bytes (N, defined in RKsuite) from hash value
        int bytesToExtract = rkSuite.getNumberOfBytesExtractedFromPrevSigHash();
        byte[] conDigest = new byte[bytesToExtract];
        System.arraycopy(digest, 0, conDigest, 0, bytesToExtract);

        //encode value as BASE64 String ==> chainValue
        return CashBoxUtils.base64Encode(conDigest, false);

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}