Example usage for java.security NoSuchAlgorithmException toString

List of usage examples for java.security NoSuchAlgorithmException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.basho.riak.pbc.RiakClient.java

/**
 * helper method to use a reasonable default client id
 * beware, it caches the client id. If you call it multiple times on the same client
 * you get the *same* id (not good for reusing a client with different ids)
 * //from w  ww  .ja  v  a2s  . c o  m
 * @throws IOException
 */
public void prepareClientID() throws IOException {
    Preferences prefs = Preferences.userNodeForPackage(RiakClient.class);

    String clid = prefs.get("client_id", null);
    if (clid == null) {
        SecureRandom sr;
        try {
            sr = SecureRandom.getInstance("SHA1PRNG");
            // Not totally secure, but doesn't need to be
            // and 100% less prone to 30 second hangs on linux jdk5
            sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] data = new byte[6];
        sr.nextBytes(data);
        clid = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
        prefs.put("client_id", clid);
        try {
            prefs.flush();
        } catch (BackingStoreException e) {
            throw new IOException(e.toString());
        }
    }

    setClientID(clid);
}

From source file:com.netscape.kra.StorageKeyUnit.java

/**
 * Protectes the share with the given password.
 *///from   www.  j  a va2 s . co m
public String encryptShare(CryptoToken token, byte share[], String pwd) throws EBaseException {
    try {
        CMS.debug("StorageKeyUnit.encryptShare");
        Cipher cipher = token.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
        SymmetricKey sk = StorageKeyUnit.buildSymmetricKey(token, pwd);

        cipher.initEncrypt(sk, IV);
        byte prev[] = preVerify(share);
        byte enc[] = cipher.doFinal(prev);

        return Utils.base64encode(enc, true).trim();
    } catch (NoSuchAlgorithmException e) {
        throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
    } catch (TokenException e) {
        throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
    } catch (InvalidKeyException e) {
        throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
    } catch (InvalidAlgorithmParameterException e) {
        throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
    } catch (BadPaddingException e) {
        throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
    } catch (IllegalBlockSizeException e) {
        throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
    }
}

From source file:com.goliathonline.android.kegbot.util.BitmapUtils.java

/**
 * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback
 * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}.
 *
 * @param cookie An arbitrary object that will be passed to the callback.
 *///from  w w w  .  ja  v  a2  s  .com
public static void fetchImage(final Context context, final String url,
        final BitmapFactory.Options decodeOptions, final Object cookie,
        final OnFetchCompleteListener callback) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            final String url = params[0];
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            // First compute the cache key and cache file path for this URL
            File cacheFile = null;
            try {
                MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
                mDigest.update(url.getBytes());
                final String cacheKey = bytesToHexString(mDigest.digest());
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                            + File.separator + "data" + File.separator + context.getPackageName()
                            + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
                }
            } catch (NoSuchAlgorithmException e) {
                // Oh well, SHA-1 not available (weird), don't cache bitmaps.
            }

            if (cacheFile != null && cacheFile.exists()) {
                Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions);
                if (cachedBitmap != null) {
                    return cachedBitmap;
                }
            }

            try {
                // TODO: check for HTTP caching headers
                final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext());
                final HttpResponse resp = httpClient.execute(new HttpGet(url));
                final HttpEntity entity = resp.getEntity();

                final int statusCode = resp.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return null;
                }

                final byte[] respBytes = EntityUtils.toByteArray(entity);

                // Write response bytes to cache.
                if (cacheFile != null) {
                    try {
                        cacheFile.getParentFile().mkdirs();
                        cacheFile.createNewFile();
                        FileOutputStream fos = new FileOutputStream(cacheFile);
                        fos.write(respBytes);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    } catch (IOException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    }
                }

                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
            } catch (Exception e) {
                Log.w(TAG, "Problem while loading image: " + e.toString(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            callback.onFetchComplete(cookie, result);
        }
    }.execute(url);
}

From source file:tw.idv.gasolin.pycontw2012.util.BitmapUtils.java

/**
 * Only call this method from the main (UI) thread. The
 * {@link OnFetchCompleteListener} callback be invoked on the UI thread, but
 * image fetching will be done in an {@link AsyncTask}.
 * //  w ww . jav a 2 s . c o  m
 * @param cookie
 *            An arbitrary object that will be passed to the callback.
 */
public static void fetchImage(final Context context, final String url,
        final BitmapFactory.Options decodeOptions, final Object cookie,
        final OnFetchCompleteListener callback) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            final String url = params[0];
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            // First compute the cache key and cache file path for this URL
            File cacheFile = null;
            try {
                MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
                mDigest.update(url.getBytes());
                final String cacheKey = bytesToHexString(mDigest.digest());
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                            + File.separator + "data" + File.separator + context.getPackageName()
                            + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
                }
            } catch (NoSuchAlgorithmException e) {
                // Oh well, SHA-1 not available (weird), don't cache
                // bitmaps.
            }

            if (cacheFile != null && cacheFile.exists()) {
                Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions);
                if (cachedBitmap != null) {
                    return cachedBitmap;
                }
            }

            try {
                // TODO: check for HTTP caching headers
                final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext());
                final HttpResponse resp = httpClient.execute(new HttpGet(url));
                final HttpEntity entity = resp.getEntity();

                final int statusCode = resp.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return null;
                }

                final byte[] respBytes = EntityUtils.toByteArray(entity);

                // Write response bytes to cache.
                if (cacheFile != null) {
                    try {
                        cacheFile.getParentFile().mkdirs();
                        cacheFile.createNewFile();
                        FileOutputStream fos = new FileOutputStream(cacheFile);
                        fos.write(respBytes);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    } catch (IOException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    }
                }

                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
            } catch (Exception e) {
                Log.w(TAG, "Problem while loading image: " + e.toString(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            callback.onFetchComplete(cookie, result);
        }
    }.execute(url);
}

From source file:org.opennms.netmgt.config.UserManager.java

/**
 * <p>encryptedPassword</p>// w ww  .j av  a 2 s  . co m
 *
 * @param aPassword a {@link java.lang.String} object.
 * @param useSalt TODO
 * @return a {@link java.lang.String} object.
 */
public String encryptedPassword(final String aPassword, final boolean useSalt) {
    String encryptedPassword = null;

    if (useSalt) {
        encryptedPassword = m_passwordEncryptor.encryptPassword(aPassword);
    } else {
        // old crappy algorithm
        try {
            final MessageDigest digest = MessageDigest.getInstance("MD5");

            // build the digest, get the bytes, convert to hexadecimal string
            // and return
            encryptedPassword = hexToString(digest.digest(aPassword.getBytes()));
        } catch (final NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.toString());
        }
    }

    return encryptedPassword;
}

From source file:de.andreas_rueckert.trade.site.btc_e.client.BtcEClient.java

/**
 * Execute a authenticated query on btc-e.
 *
 * @param method The method to execute./*from ww  w .  j a  v a2s  .c o m*/
 * @param arguments The arguments to pass to the server.
 * @param userAccount The user account on the exchange, or null if the default account should be used.
 *
 * @return The returned data as JSON or null, if the request failed.
 *
 * @see http://pastebin.com/K25Nk2Sv
 */
private final JSONObject authenticatedHTTPRequest(String method, Map<String, String> arguments,
        TradeSiteUserAccount userAccount) {
    HashMap<String, String> headerLines = new HashMap<String, String>(); // Create a new map for the header lines.
    Mac mac;
    SecretKeySpec key = null;
    String accountKey; // The used key of the account.
    String accountSecret; // The used secret of the account.

    // Try to get an account key and secret for the request.
    if (userAccount != null) {

        accountKey = userAccount.getAPIkey();
        accountSecret = userAccount.getSecret();

    } else { // Use the default values from the API implementation.

        accountKey = _key;
        accountSecret = _secret;
    }

    // Check, if account key and account secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Key not available for authenticated request to btc-e");
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException("Secret not available for authenticated request to btc-e");
    }

    if (arguments == null) { // If the user provided no arguments, just create an empty argument array.
        arguments = new HashMap<String, String>();
    }

    arguments.put("method", method); // Add the method to the post data.
    arguments.put("nonce", "" + ++_nonce); // Add the dummy nonce.

    // Convert the arguments into a string to post them.
    String postData = "";

    for (Iterator argumentIterator = arguments.entrySet().iterator(); argumentIterator.hasNext();) {
        Map.Entry argument = (Map.Entry) argumentIterator.next();

        if (postData.length() > 0) {
            postData += "&";
        }
        postData += argument.getKey() + "=" + argument.getValue();
    }

    // Create a new secret key
    try {

        key = new SecretKeySpec(accountSecret.getBytes("UTF-8"), "HmacSHA512");

    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Create a new mac
    try {

        mac = Mac.getInstance("HmacSHA512");

    } catch (NoSuchAlgorithmException nsae) {

        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    // Init mac with key.
    try {
        mac.init(key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }

    // Add the key to the header lines.
    headerLines.put("Key", accountKey);

    // Encode the post data by the secret and encode the result as base64.
    try {

        headerLines.put("Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8"))));
    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Now do the actual request
    String requestResult = HttpUtils.httpPost("https://" + DOMAIN + "/tapi", headerLines, postData);

    if (requestResult != null) { // The request worked

        try {
            // Convert the HTTP request return value to JSON to parse further.
            JSONObject jsonResult = JSONObject.fromObject(requestResult);

            // Check, if the request was successful
            int success = jsonResult.getInt("success");

            if (success == 0) { // The request failed.
                String errorMessage = jsonResult.getString("error");

                LogUtils.getInstance().getLogger().error("btc-e.com trade API request failed: " + errorMessage);

                return null;

            } else { // Request succeeded!

                return jsonResult.getJSONObject("return");
            }

        } catch (JSONException je) {
            System.err.println("Cannot parse json request result: " + je.toString());

            return null; // An error occured...
        }
    }

    return null; // The request failed.
}

From source file:it.cnr.isti.thematrix.scripting.modules.MatrixFileInput.java

/**
 * Download CSV data from the DBMS in case a valid CSV file is not found but we have a DB mapping for that
 * filename. //from www . ja  va2s.c o  m
 * 
 * TODO Maybe a file that is not downloadable should not reach here at all.
 * 
 * @param fileMapper class providing mapping information for DM-downloadable files
 * 
 * @return true if the file was successfully downloaded.
 */
private boolean openFileDownloadFromDB(MappingManager fileMapper) {

    //      If we get here, we know the CSV file is not found or invalid
    boolean fileOK = false; // true if we were able to download the CSV, it becomes the return value
    Collection<String> mappedFileNames = null; // the list of names defined in the mapping.xml config
    boolean workDone = false; // true only after successful creation

    /************** new code -- interaction with the Database ******************/

    try { // check if the file belongs in those defined by our mapping
        mappedFileNames = MappingSingleton.getInstance().mapping.getDatasetNames();
    } catch (Exception e1) {
        LogST.logP(0, "MatrixFileInput.openFile() - ERROR - exception while reading the mapping file "
                + e1.toString());
        e1.printStackTrace();
    }

    if (mappedFileNames == null || !mappedFileNames.contains(baseName)) {
        LogST.logP(0,
                "MatrixFileInput.openFileDownLoadFromDB() - ERROR - file " + baseName + " has no mapping");
        throw new Error("MatrixFileInput.openFileDownLoadFromDB() No mapping for file");
        //         System.exit(0); // FIXME we should throw exception
    }

    // if it is there, start routine to retrieve it
    try {
        // when retrieving, encode the values with the recoding tables // NOT YET
        // and dump to the CSV
        fileMapper.createDataset(new ArrayList<String>(Arrays.asList(baseName)));
        workDone = true;
    }
    /*************** Real work ends here *******************/
    catch (NoSuchAlgorithmException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - MD5 encoding algorithm not found");
        e.printStackTrace();
    } catch (JAXBException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - JAXB error");
        e.printStackTrace();
    } catch (IOException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - file not found");
        e.printStackTrace();
    } catch (SyntaxErrorInMappingException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - malformed file mapping");
        e.printStackTrace();
    } catch (SQLException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - SQL error");
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - JDBC driver not found");
        e.printStackTrace();
    } catch (JDBCConnectionException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - can't open JDBC connection");
        e.printStackTrace();
    } catch (UnsupportedDatabaseDriverException e) {
        LogST.logP(0, "MatrixFileInput.openFile() - JDB driver needed is not supported");
        e.printStackTrace();
    }

    if (workDone) { // only if we did not get any exception check for the CSV

        /**
         * TODO refactor, the Mapping Manager should return this information; for now we check again
         */
        try {
            fileOK = fileMapper.checkCSVFileExistence(baseName);
        } catch (Exception e) {
            LogST.logP(0, "MatrixFileInput, exception " + e.toString() + " for file " + baseName
                    + " in setup() not dowloaded");
        }
        ;

        LogST.logP(0, "MatrixFileInput.openFile() - DBMS download done for file" + baseName + " at time "
                + new java.util.Date().toString());

        /**************
         * END of interaction with the Database ***********************
         * 
         * now if we really got the data, we are fine; but if a query for manual execution was produced instead, no
         * file to open --> the script execution cannot continue; we should gracefully generate any more required
         * data and exit;
         * 
         * in the future, this can be implemented by launching an internal exception, caught in the interpreter, or
         * floated to the outermost eval(), whose catch will scan all the modules in the script, triggering the
         * openFile() of all FileInput modules
         */
    }

    // 3 possible cases: a) csv downloaded from DB b) csv not downloaded, query generated c) error occurred
    // let the user know in case b) he has to run the query manually
    if (!fileOK && Dynamic.ignoreDBConnection) {
        LogST.logP(0, "MatrixFileInput - no DBMS connection - query dumped to text file\n"
                + "Please execute the query, place the result in the directory of IAD files, validate the files.");
    }
    // case a) returns true, b) c) return false.
    return fileOK;
}

From source file:com.netscape.ca.CertificateAuthority.java

/**
 * Signs the given certificate info using specified signing algorithm
 * If no algorithm is specified the CA's default algorithm is used.
 * <P>/* w w w. j a v a 2 s.  c o  m*/
 *
 * @param certInfo the certificate info to be signed.
 * @param algname the signing algorithm to use. These are names defined
 *            in JCA, such as MD5withRSA, etc. If null the CA's default
 *            signing algorithm will be used.
 * @return signed certificate
 */
public X509CertImpl sign(X509CertInfo certInfo, String algname) throws EBaseException {
    ensureReady();

    X509CertImpl signedcert = null;

    IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
    if (statsSub != null) {
        statsSub.startTiming("signing");
    }

    try (DerOutputStream out = new DerOutputStream(); DerOutputStream tmp = new DerOutputStream()) {

        if (certInfo == null) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_CERTINFO"));
            return null;
        }

        if (algname == null) {
            algname = mSigningUnit.getDefaultAlgorithm();
        }

        logger.debug("sign cert get algorithm");
        AlgorithmId alg = AlgorithmId.get(algname);

        // encode certificate info
        logger.debug("sign cert encoding cert");
        certInfo.encode(tmp);
        byte[] rawCert = tmp.toByteArray();

        // encode algorithm identifier
        logger.debug("sign cert encoding algorithm");
        alg.encode(tmp);

        logger.debug("CA cert signing: signing cert");
        byte[] signature = mSigningUnit.sign(rawCert, algname);

        tmp.putBitString(signature);

        // Wrap the signed data in a SEQUENCE { data, algorithm, sig }
        out.write(DerValue.tag_Sequence, tmp);
        //log(ILogger.LL_INFO, "CertificateAuthority: done signing");

        switch (mFastSigning) {
        case FASTSIGNING_DISABLED:
            signedcert = new X509CertImpl(out.toByteArray());
            break;

        case FASTSIGNING_ENABLED:
            signedcert = new X509CertImpl(out.toByteArray(), certInfo);
            break;

        default:
            break;
        }
    } catch (NoSuchAlgorithmException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CERT", e.toString(), e.getMessage()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
    } catch (IOException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CERT", e.toString(), e.getMessage()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
    } catch (CertificateException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CERT", e.toString(), e.getMessage()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
    } finally {
        if (statsSub != null) {
            statsSub.endTiming("signing");
        }
    }
    return signedcert;
}