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:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * If there is a saved cert, checks the one given against it. If a signature was passed in
 * and no saved cert, then check that signature. Otherwise, presents the
 * given cert's signature to the user for approval.
 * //w  w w. ja v a 2  s  . co m
 * The saved data must always win over any passed-in URI data
 * 
 * @param cert the given cert.
 */
private void validateX509Cert(final X509Certificate cert) {

    boolean certMismatch = false;

    int hashAlg = connection.getIdHashAlgorithm();
    byte[] certData = null;
    boolean isSigEqual = false;
    try {
        certData = cert.getEncoded();
        isSigEqual = SecureTunnel.isSignatureEqual(hashAlg, connection.getIdHash(), certData);
    } catch (Exception ex) {
        ex.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
        return;
    }

    // If there is no saved cert, then if a signature was provided,
    // check the signature and save the cert if the signature matches.
    if (connection.getSshHostKey().equals("")) {
        if (!connection.getIdHash().equals("")) {
            if (isSigEqual) {
                Log.i(TAG, "Certificate validated from URI data.");
                saveAndAcceptCert(cert);
                return;
            } else {
                certMismatch = true;
            }
        }
        // If there is a saved cert, check against it.
    } else if (connection.getSshHostKey().equals(Base64.encodeToString(certData, Base64.DEFAULT))) {
        Log.i(TAG, "Certificate validated from saved key.");
        saveAndAcceptCert(cert);
        return;
    } else {
        certMismatch = true;
    }

    // Show a dialog with the key signature for approval.
    DialogInterface.OnClickListener signatureNo = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // We were told not to continue, so stop the activity
            Log.i(TAG, "Certificate rejected by user.");
            closeConnection();
            ((Activity) getContext()).finish();
        }
    };
    DialogInterface.OnClickListener signatureYes = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.i(TAG, "Certificate accepted by user.");
            saveAndAcceptCert(cert);
        }
    };

    // Display dialog to user with cert info and hash.
    try {
        // First build the message. If there was a mismatch, prepend a warning about it.
        String message = "";
        if (certMismatch) {
            message = getContext().getString(R.string.warning_cert_does_not_match) + "\n\n";
        }
        byte[] certBytes = cert.getEncoded();
        String certIdHash = SecureTunnel.computeSignatureByAlgorithm(hashAlg, certBytes);
        String certInfo = String.format(Locale.US, getContext().getString(R.string.info_cert_tunnel),
                certIdHash, cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName(),
                cert.getNotBefore(), cert.getNotAfter());
        certInfo = message + certInfo.replace(",", "\n");

        // Actually display the message
        Utils.showYesNoPrompt(getContext(),
                getContext().getString(R.string.info_continue_connecting) + connection.getAddress() + "?",
                certInfo, signatureYes, signatureNo);
    } catch (NoSuchAlgorithmException e2) {
        e2.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

public String updatePerson(String first_name, String last_name, String phone, String email, String password,
        String accountType, ResponseObject responseObject) {
    try {/*ww w. jav a2s  .co m*/
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss aa");
        String today = formatter.format(date);
        String encrypted_password = null;

        if (password != null)
            encrypted_password = encryptWithoutEncode(password);

        WordPressUserPojo wpuser = new WordPressUserPojo();
        WordPressAuthPojo wpauth = new WordPressAuthPojo();

        wpuser.setModified(today);
        wpuser.setFirstname(first_name);
        wpuser.setLastname(last_name);
        wpuser.setPhone(phone);
        ArrayList<String> emailArray = new ArrayList<String>();
        emailArray.add(email);
        wpuser.setEmail(emailArray);
        wpauth.setWPUserID(email);
        wpauth.setPassword(encrypted_password);
        wpauth.setAccountType(accountType);
        wpauth.setModified(today);

        return updatePerson(wpuser, wpauth, responseObject);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

public String registerPerson(String first_name, String last_name, String phone, String email, String password,
        String accountType, ResponseObject responseObject) {
    try {/*w w  w . j a v a  2s  .co m*/
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss aa");
        String today = formatter.format(date);
        String encrypted_password;

        encrypted_password = encryptWithoutEncode(password);

        WordPressUserPojo wpuser = new WordPressUserPojo();
        WordPressAuthPojo wpauth = new WordPressAuthPojo();

        wpuser.setCreated(today);
        wpuser.setModified(today);
        wpuser.setFirstname(first_name);
        wpuser.setLastname(last_name);
        wpuser.setPhone(phone);

        ArrayList<String> emailArray = new ArrayList<String>();
        emailArray.add(email);
        wpuser.setEmail(emailArray);

        //wpauth.setWPUserID(email);
        wpauth.setPassword(encrypted_password);
        wpauth.setAccountType(accountType);
        wpauth.setCreated(today);
        wpauth.setModified(today);

        WordPressSetupPojo wpSetup = new WordPressSetupPojo();
        wpSetup.setAuth(wpauth);
        wpSetup.setUser(wpuser);

        return registerPerson(wpSetup, responseObject);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:edu.stanford.muse.util.Util.java

/** SHA-256 hash */
public static String hash(String s) {
    MessageDigest digest = null;/*w  w w.j a  v a2 s.co m*/
    String hash = null;
    try {
        digest = MessageDigest.getInstance("SHA-256");
        digest.update(s.getBytes());
        hash = bytesToHexString(digest.digest());
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return hash;
}

From source file:edu.stanford.muse.util.Util.java

public static String hash(String s, Map<String, String> map) {
    MessageDigest digest = null;//from w ww .  ja  v  a2 s.c o m
    String hash = null;
    try {
        digest = MessageDigest.getInstance("SHA-256");
        digest.update(s.getBytes());
        hash = bytesToHexString(digest.digest());
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    if (map != null)
        map.put(hash, s);
    return hash;
}

From source file:org.dataconservancy.packaging.tool.model.ipm.FileInfo.java

/**
 * Default constructor that should be used in most cases. Will read the file at the path location and load the necessary file attributes.
 * @param path The path to the file.//from  ww  w .ja  v  a2s  . c o  m
 */
public FileInfo(Path path) {
    location = path.toUri();
    name = path.getFileName().toString();

    try {
        fileAttributes = new FileInfoAttributes(Files.readAttributes(path, BasicFileAttributes.class));
        if (fileAttributes.isRegularFile()) {
            checksums = new HashMap<>();
            formats = new ArrayList<>();

            MessageDigest md5 = null;
            MessageDigest sha1 = null;

            try {
                md5 = MessageDigest.getInstance("MD5");
                sha1 = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e.getMessage(), e);
            }

            try (ChecksumCalculatingInputStream in = new ChecksumCalculatingInputStream(
                    Files.newInputStream(path), Arrays.asList(md5, sha1))) {

                IOUtils.copy(in, new NullOutputStream());

                in.digests().forEach((md, digest) -> {
                    String encoded = Hex.encodeHexString(digest);
                    if (md.getAlgorithm().equals("MD5")) {
                        checksums.put(Algorithm.MD5, encoded);
                    }

                    if (md.getAlgorithm().equals("SHA-1")) {
                        checksums.put(Algorithm.SHA1, encoded);
                    }
                });
            }

            List<DetectedFormat> fileFormats = ContentDetectionService.getInstance()
                    .detectFormats(path.toFile());
            for (DetectedFormat format : fileFormats) {
                if (format.getId() != null && !format.getId().isEmpty()) {
                    formats.add(createFormatURIString(format));
                }

                if (format.getMimeType() != null && !format.getMimeType().isEmpty()) {
                    formats.add(format.getMimeType());
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:MyZone.Settings.java

private byte[] hashMessage(byte[] data, String mdAlgorithm) {
    try {/*ww w .j a va  2 s. c o  m*/
        MessageDigest md;
        Security.addProvider(new BouncyCastleProvider());
        md = MessageDigest.getInstance(mdAlgorithm, "BC");
        byte[] hash = null;
        md.update(data, 0, data.length);
        hash = md.digest();
        return hash;
    } catch (NoSuchAlgorithmException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    } catch (java.security.NoSuchProviderException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:MyZone.Settings.java

private byte[] encryptWithPriKey(byte[] plain, String keyAlgorithm, PrivateKey priKey) {
    try {//from   w  w  w . j  a  v a2 s .c  o m
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(keyAlgorithm, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, priKey);
        int msgLength = plain.length;
        int chunks = (int) (Math.ceil((double) msgLength / (double) globalProperties.plainBlockSize));
        byte[] encryptedMsg = new byte[(int) (globalProperties.certificateKeySize / 8) * chunks];
        byte[] encryptedChunk = new byte[globalProperties.plainBlockSize];
        byte[] plainChunk = new byte[globalProperties.plainBlockSize];
        int offset = 0;
        int i = 0;
        while (msgLength > plainChunk.length) {
            System.arraycopy(plain, offset, plainChunk, 0, plainChunk.length);
            offset += plainChunk.length;
            msgLength -= plainChunk.length;
            encryptedChunk = cipher.doFinal(plainChunk);
            System.arraycopy(encryptedChunk, 0, encryptedMsg, i * encryptedChunk.length, encryptedChunk.length);
            i++;
        }
        if (msgLength > 0) {
            plainChunk = new byte[msgLength];
            System.arraycopy(plain, offset, plainChunk, 0, msgLength);
            encryptedChunk = cipher.doFinal(plainChunk);
            System.arraycopy(encryptedChunk, 0, encryptedMsg, i * encryptedChunk.length, encryptedChunk.length);
        }
        return encryptedMsg;
    } catch (NoSuchAlgorithmException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    } catch (NoSuchPaddingException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    } catch (InvalidKeyException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    } catch (IllegalBlockSizeException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    } catch (BadPaddingException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    } catch (java.security.NoSuchProviderException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Initialize this servlet.//from   w w w .  j  ava2s. co  m
 *
 * @throws ServletException Description of the Exception
 */
public void init() throws ServletException {

    // Set our properties from the initialization parameters
    String value = null;
    try {
        value = getServletConfig().getInitParameter("debug");
        debug = Integer.parseInt(value);
    } catch (Throwable t) {
        ;
    }
    try {
        value = getServletConfig().getInitParameter("input");
        input = Integer.parseInt(value);
    } catch (Throwable t) {
        ;
    }
    try {
        value = getServletConfig().getInitParameter("listings");
        listings = (new Boolean(value)).booleanValue();
    } catch (Throwable t) {
        ;
    }
    try {
        value = getServletConfig().getInitParameter("readonly");
        if (value != null) {
            readOnly = (new Boolean(value)).booleanValue();
        }
    } catch (Throwable t) {
        ;
    }
    try {
        value = getServletConfig().getInitParameter("output");
        output = Integer.parseInt(value);
    } catch (Throwable t) {
        ;
    }

    globalXsltFile = getServletConfig().getInitParameter("globalXsltFile");
    localXsltFile = getServletConfig().getInitParameter("localXsltFile");
    readmeFile = getServletConfig().getInitParameter("readmeFile");

    // Sanity check on the specified buffer sizes
    if (input < 256) {
        input = 256;
    }
    if (output < 256) {
        output = 256;
    }

    if (debug > 0) {
        log("DefaultServlet.init:  input buffer size=" + input + ", output buffer size=" + output);
    }

    // Load the MD5 helper used to calculate signatures.
    try {
        md5Helper = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new IllegalStateException();
    }
}

From source file:cm.aptoide.pt.MainActivity.java

protected void addStore(String uri_str, String username, String password) {

    if (uri_str.contains("http//")) {
        uri_str = uri_str.replaceFirst("http//", "http://");
    }//  w ww.  ja v a  2s.c om

    if (uri_str.length() != 0 && uri_str.charAt(uri_str.length() - 1) != '/') {
        uri_str = uri_str + '/';
        Log.d("Aptoide-ManageRepo", "repo uri: " + uri_str);
    }
    if (!uri_str.startsWith("http://")) {
        uri_str = "http://" + uri_str;
        Log.d("Aptoide-ManageRepo", "repo uri: " + uri_str);
    }
    if (username != null && username.contains("@")) {
        try {
            password = Algorithms.computeSHA1sum(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    NetworkUtils utils = new NetworkUtils();
    final int response = utils.checkServerConnection(uri_str, username, password);
    final String uri = uri_str;
    switch (response) {
    case 0:
        service.addStore(db, uri, username, password);
        break;
    case 401:
        runOnUiThread(new Runnable() {

            @Override
            public void run() {

                showAddStoreCredentialsDialog(uri);
            }
        });

        break;
    case 404:
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast toast = Toast.makeText(mContext, mContext.getString(R.string.verify_store),
                        Toast.LENGTH_SHORT);
                toast.show();
                showAddStoreDialog();
            }
        });
        break;
    case -1:
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast toast = Toast.makeText(mContext, mContext.getString(R.string.an_error_check_net),
                        Toast.LENGTH_SHORT);
                toast.show();
                showAddStoreDialog();
            }
        });
        break;
    default:
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast toast = Toast.makeText(mContext,
                        mContext.getString(R.string.error_occured) + " " + response, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 30);
                toast.show();
                showAddStoreDialog();
            }
        });
        break;
    }

}