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.egov.collection.integration.pgi.AxisAdaptor.java

private String hashAllFields(final LinkedHashMap<String, String> fields) {

    final String axisSecureSecret = collectionApplicationProperties.axisSecureSecret();
    byte[] decodedKey;
    byte[] hashValue = null;
    // Sort list with field names ascending order
    final List<String> fieldNames = new ArrayList<>(fields.keySet());
    Collections.sort(fieldNames);

    // iterate through field name list and generate message for hashing. Format: fieldname1=fieldvale1?fieldname2=fieldvalue2
    final Iterator<String> itr = fieldNames.iterator();
    final StringBuilder hashingMessage = new StringBuilder();
    int i = 0;/*from   ww w . j  a va2 s .  c  o  m*/
    while (itr.hasNext()) {
        final String fieldName = itr.next();
        final String fieldValue = fields.get(fieldName);
        if (fieldValue != null && fieldValue.length() > 0) {
            if (i != 0)
                hashingMessage.append("&");
            hashingMessage.append(fieldName).append("=").append(fieldValue);
            i++;
        }
    }
    try {
        decodedKey = Hex.decodeHex(axisSecureSecret.toCharArray());
        SecretKeySpec keySpec = new SecretKeySpec(decodedKey, "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        byte[] hashingMessageBytes = hashingMessage.toString().getBytes(UTF8);
        hashValue = mac.doFinal(hashingMessageBytes);
    } catch (DecoderException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return DatatypeConverter.printHexBinary(hashValue);
}

From source file:com.portfolio.security.LTIv2Servlet.java

private int postData(String urlStr, String jsonData, String oauth_consumer_key, String oauth_consumer_secret)
        throws IOException {
    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);/*from  w w w  .jav a  2s . c  om*/
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/vnd.ims.lti.v2.toolproxy+json");
    connection.setRequestProperty("Content-Length", String.valueOf(jsonData.length()));

    Map<String, String> postProp = new HashMap<String, String>();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");

        md.update(jsonData.getBytes());
        byte[] output = Base64.encode(md.digest());
        String hash = new String(output);

        postProp.put("oauth_body_hash", hash);
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    OAuthMessage oam = new OAuthMessage(OAuthMessage.POST, urlStr, postProp.entrySet());

    OAuthConsumer cons = new OAuthConsumer("about:blank", oauth_consumer_key, oauth_consumer_secret, null);
    OAuthAccessor acc = new OAuthAccessor(cons);
    try {
        oam.addRequiredParameters(acc);
        connection.setRequestProperty("Authorization", oam.getAuthorizationHeader(null));
        oam.sign(acc);
    } catch (net.oauth.OAuthException e) {
        throw new Error(e);
    } catch (java.io.IOException e) {
        throw new Error(e);
    } catch (java.net.URISyntaxException e) {
        throw new Error(e);
    }

    // Write data
    OutputStream os = connection.getOutputStream();
    os.write(jsonData.getBytes());

    // Read response
    int responseCode = connection.getResponseCode();

    // Close streams
    os.close();

    return responseCode;

}

From source file:com.bytecode.core.ConManager.java

private String hash(String password) throws ProcessingException {
    try {// www  .  j  av  a2  s .  com
        MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
        byte[] passwordBytes = password.getBytes();
        byte[] digest = sha512.digest(passwordBytes);
        StringBuilder stringBuilder = new StringBuilder();
        String s;
        for (byte b : digest) {
            s = Integer.toHexString((int) b & 0xff).toUpperCase();
            if (s.length() == 1) {
                stringBuilder.append('0');
            }
            stringBuilder.append(s);
        }
        return stringBuilder.toString();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ConManager.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
        throw new ProcessingException("NoSuchAlgorithmException");
    }
}

From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java

/**
 * Encrypts a password./*  w w  w.ja  va2 s  .  co m*/
 * 
 * @param password
 *            String
 * @param serverInfo
 *            ServerInfo
 * @return String
 */
public String encrypt(String password, ServerInfo serverInfo) {
    try {
        Certificate publicKey = getCertificateForEncryption(serverInfo);
        PublicKey key = publicKey.getPublicKey();
        byte[] inpBytes;
        inpBytes = password.getBytes();
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptededByteAr = cipher.doFinal(inpBytes);
        byte[] base64EncodedByteAr = Base64.encodeBase64(encryptededByteAr);
        return new String(base64EncodedByteAr);
        // TODO: OW When new login proxy object with encryption handler is
        // implemented, handle exceptions
    } catch (NoSuchAlgorithmException e) {
        // nothing to do
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // nothing to do
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // nothing to do
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        // nothing to do
        e.printStackTrace();
    } catch (BadPaddingException e) {
        // nothing to do
        e.printStackTrace();
    } catch (CertificateStoreException e) {
        // Auto-generated catch block
        e.printStackTrace();
    }
    WorkspaceUtil.logException("Couldn't encrypt password.",
            new CertificateStoreException("Couldn't encrypt password."));
    return "";
}

From source file:de.madvertise.android.sdk.MadView.java

/**
 * Returns the MD5 hash for a string.//from  w  w  w.  j  ava 2  s.c o m
 * 
 * @param input
 * @return md5 hash
 */
private String getMD5Hash(String input) {
    MessageDigest messageDigest = null;

    try {
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        MadUtil.logMessage(null, Log.DEBUG, "Could not create hash value");
        return "";
    }
    messageDigest.update(input.getBytes());
    String temp = null;
    byte[] digest = messageDigest.digest();
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < digest.length; i++) {
        temp = Integer.toHexString(0xFF & digest[i]);
        if (temp.length() < 2) {
            temp = "0" + temp;
        }
        hexString.append(temp);
    }
    return hexString.toString();
}

From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java

/**
 * Encrypts a password.//www  .  j  a v a2s. com
 * 
 * @param password
 *            the password to be encrypted
 * @param server
 *            the server from which to fetch the public key that is used for encryption
 * @return the encrypted password
 */
public String encrypt(String password, ServerInfo server) {
    try {
        final Certificate publicKey = getCertificateForEncryption(server);
        final PublicKey key = publicKey.getPublicKey();
        final byte[] inpBytes = password.getBytes();
        final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        final byte[] encryptededByteAr = cipher.doFinal(inpBytes);
        final byte[] base64EncodedByteAr = Base64.encodeBase64(encryptededByteAr);
        return new String(base64EncodedByteAr);
        // TODO: OW When new login proxy object with encryption handler is
        // implemented, handle exceptions
    } catch (final NoSuchAlgorithmException e) {
        // nothing to do
        e.printStackTrace();
    } catch (final NoSuchPaddingException e) {
        // nothing to do
        e.printStackTrace();
    } catch (final InvalidKeyException e) {
        // nothing to do
        e.printStackTrace();
    } catch (final IllegalBlockSizeException e) {
        // nothing to do
        e.printStackTrace();
    } catch (final BadPaddingException e) {
        // nothing to do
        e.printStackTrace();
    } catch (final ESCertificateException e) {
        // Auto-generated catch block
        e.printStackTrace();
    }
    WorkspaceUtil.logException(Messages.KeyStoreManager_Could_Not_Encrypt_Password,
            new ESCertificateException(Messages.KeyStoreManager_34));
    return ""; //$NON-NLS-1$
}

From source file:org.ormma.controller.OrmmaAssetController.java

/**
 * Write a stream to disk.// w w  w. ja  v a  2 s  . c  o  m
 * 
 * @param in
 *            the input stream
 * @param file
 *            the file to store it in
 * @param storeInHashedDirectory
 *            use a hashed directory name
 * @return the path where it was stired
 * @throws IllegalStateException
 *             the illegal state exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public String writeToDisk(InputStream in, String file, boolean storeInHashedDirectory)
        throws IllegalStateException, IOException
/**
 * writes a HTTP entity to the specified filename and location on disk
 */
{
    int i = 0;
    byte buff[] = new byte[1024];

    MessageDigest digest = null;
    if (storeInHashedDirectory) {
        try {
            digest = java.security.MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    FileOutputStream out = null;
    try {
        out = getAssetOutputString(file);
        do {
            int numread = in.read(buff);
            if (numread <= 0)
                break;

            if (storeInHashedDirectory && digest != null) {
                digest.update(buff);
            }
            out.write(buff, 0, numread);

            // System.out.println("numread" + numread);
            i++;
        } while (true);
        out.flush();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            out = null;
        }
    }
    // out.close();
    // in.close();
    String filesDir = getFilesDir();

    if (storeInHashedDirectory && digest != null) {
        filesDir = moveToAdDirectory(file, filesDir, asHex(digest));
    }
    return filesDir + file;

}

From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java

/**
 * Build a new HTTP Client for the given parameters
 *
 * @param params/* w w w .  jav a2  s  .  c  o m*/
 * @return
 */
public DefaultHttpClient buildNewHttpClient(HttpParams params) {
    PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    cxMgr.setMaxTotal(100);
    cxMgr.setDefaultMaxPerRoute(20);

    DefaultHttpClient httpClient = new DefaultHttpClient(cxMgr, params);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");
    // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
    // CookiePolicy.BROWSER_COMPATIBILITY);
    if (this.useNtlm) {
        httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register("BASIC", new BasicSchemeFactory());
        httpClient.getAuthSchemes().register("DIGEST", new DigestSchemeFactory());
        httpClient.getAuthSchemes().register("SPNEGO", new SPNegoSchemeFactory());
        httpClient.getAuthSchemes().register("KERBEROS", new KerberosSchemeFactory());
    }

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    if (this.useProxy) {
        if (this.proxySocks) {

            log.info("Using proxy socks " + this.socksHost + ":" + this.socksPort);

            System.setProperty("socksProxyHost", this.socksHost);
            System.setProperty("socksProxyPort", String.valueOf(this.socksPort));

        } else {
            HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (this.authProxy) {

                List<String> authPreferences = new ArrayList<>();

                if (this.ntlmProxy) {

                    NTCredentials creds = new NTCredentials(this.proxyUser, this.proxyPassword,
                            this.proxyWorkstation, this.proxyDomain);
                    httpClient.getCredentialsProvider()
                            .setCredentials(new AuthScope(this.proxyHost, this.proxyPort), creds);
                    // httpClient.getCredentialsProvider().setCredentials(
                    // AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.NTLM);
                } else {
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.proxyUser,
                            this.proxyPassword);
                    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.BASIC);
                }

                httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPreferences);
            }
        }

    }

    return httpClient;
}

From source file:com.neusou.bioroid.image.ImageLoader.java

private String computeDigest(String uri) {
    String s = uri;//from  w w  w . ja  va 2 s .c  om
    MessageDigest m;
    try {
        m = MessageDigest.getInstance("MD5");
        m.update(s.getBytes(), 0, s.length());
        BigInteger bi = new BigInteger(1, m.digest());
        String bigInt = bi.toString(16);
        return bigInt;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.zsxj.pda.ui.client.LoginActivity.java

private String getMd5(String input, String charset) {
    try {/*from  w w  w . j  a v a2s .c  o  m*/
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytesOfMessage = input.getBytes(charset);
        byte[] theDigest = md.digest(bytesOfMessage);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < theDigest.length; i++) {
            String hex = Integer.toHexString(0xff & theDigest[i]);
            if (hex.length() == 1) {
                sb.append("0");
            }
            sb.append(hex);
        }
        return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}