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.nubits.nubot.trading.wrappers.ExcoinWrapper.java

public Trade parseTrade(JSONObject in) {
    Trade out = new Trade();

    //get and set the pair
    String commodity = in.get("commodity").toString();
    String currency = in.get("currency").toString();
    CurrencyPair pair = CurrencyPair.getCurrencyPairFromString(commodity + "_" + currency, "_");
    out.setPair(pair);/*w  w  w .  j  a v a  2s  . c  om*/
    //get and set the type
    String type = in.get("type").toString();
    out.setType(type.equals("BUY") ? Constant.BUY : Constant.SELL);
    //get and set the price
    Amount price = new Amount(Double.parseDouble(in.get("price").toString()), pair.getPaymentCurrency());
    out.setPrice(price);
    //get and set the date
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss z");
    Date date = null;
    try {
        date = sdf.parse(in.get("timestamp").toString());
    } catch (java.text.ParseException pe) {
        //sometimes timestamp in this format are returned
        //2014-12-19T16:02:07.961Z
        sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
        try {
            date = sdf.parse(in.get("timestamp").toString());
        } catch (java.text.ParseException pe1) {
            LOG.error(pe1.toString());
        }
    }
    if (date != null) {
        long timeStamp = date.getTime();
        Date insertDate = new Date(timeStamp);
        out.setDate(insertDate);
    }
    //set the exchangeName
    out.setExchangeName(exchange.getName());
    //set the amount
    Amount amount;
    if (type.equals("BUY")) {
        amount = new Amount(Double.parseDouble(in.get("received").toString()), pair.getOrderCurrency());
    } else {
        amount = new Amount(Double.parseDouble(in.get("sent").toString()), pair.getOrderCurrency());
    }
    out.setAmount(amount);
    //set the fee
    Amount fee = new Amount(Double.parseDouble(in.get("fee").toString()), pair.getPaymentCurrency());
    out.setFee(fee);

    //generate the unique id - MD5 hash of datetime and pair concatenation
    String hash_data = in.get("timestamp").toString() + in.get("commodity").toString()
            + in.get("currency").toString();
    String id = null;
    try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(hash_data.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
        }
        id = sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
        LOG.error(e.toString());
    }
    //set the id
    out.setId(id);
    //set the order_id
    out.setOrder_id(id);

    return out;
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * Initialize the class.  Sets the encryption level for the instance
 * and generates the secret key factory.
 *
 * @param Strength/*w  w w  .  j  ava 2s.c o m*/
 */
private void initialize(int Strength) {
    switch (Strength) {
    case EncryptionMedium:
        algorithm = algorithmMedium;
        break;
    case EncryptionStrong:
        algorithm = algorithmStrong;
        break;
    }
    pbeParamSpec = new PBEParameterSpec(salt, count);
    try {
        keyFac = SecretKeyFactory.getInstance(algorithm, "BC");
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "CryptoHelper(): " + e.toString());
    } catch (NoSuchProviderException e) {
        Log.e(TAG, "CryptoHelper(): " + e.toString());
    }
}

From source file:com.ccserver.digital.service.LOSService.java

private ClientType getClientType() {
    ClientType clientType = new ClientType();
    UserDetail userDetail = new UserDetail();
    userDetail.setUserId(losConfig.getUserName());

    MessageDigest digester = null;
    try {/* ww w .j av  a  2  s  .c om*/
        digester = MessageDigest.getInstance("MD5");
        digester.update(losConfig.getPassword().getBytes());
    } catch (NoSuchAlgorithmException e) {
        logger.error(Utils.getErrorFormatLog("LOSService", "getClientType", "", e.toString()));
    }

    userDetail.setUserPassword(digester.digest());

    clientType.setUserDetail(userDetail);
    clientType.setSourceAppID(getConfiguration("LOS_SOURCE_ID", "CCApp"));

    TargetAppIDs targetAppIDs = new TargetAppIDs();
    targetAppIDs.getTargetAppID().add(getConfiguration("LOS_TARGET_ID", "ESB"));
    clientType.setTargetAppIDs(targetAppIDs);
    return clientType;
}

From source file:org.apache.hadoop.registry.client.impl.zk.RegistrySecurity.java

/**
 * Generate a base-64 encoded digest of the idPasswordPair pair
 * @param idPasswordPair id:password//from  w ww  . j av  a  2  s  .co  m
 * @return a string that can be used for authentication
 */
public String digest(String idPasswordPair) throws IOException {
    if (StringUtils.isEmpty(idPasswordPair) || !isValid(idPasswordPair)) {
        throw new IOException("Invalid id:password");
    }
    try {
        return DigestAuthenticationProvider.generateDigest(idPasswordPair);
    } catch (NoSuchAlgorithmException e) {
        // unlikely since it is standard to the JVM, but maybe JCE restrictions
        // could trigger it
        throw new IOException(e.toString(), e);
    }
}

From source file:de.andreas_rueckert.trade.site.mtgox.client.MtGoxClient.java

/**
 * Create authentication entries for a HTTP post header.
 *
 * @param postData The data to post via HTTP.
 * @param userAccount The account of the user on the exchange. Null, if the default account should be used.
 *
 * @return The header entries as a map or null if an error occured.
 */// ww  w . j  a  va2  s. c om
Map<String, String> getAuthenticationHeader(String postData, TradeSiteUserAccount userAccount) {
    HashMap<String, String> result = new HashMap<String, String>();
    Mac mac;
    String accountKey = null;
    String accountSecret = null;

    // Try to get user account and secret.
    if (userAccount != null) {

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

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

        accountKey = _key;
        accountSecret = _secret;
    }

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

    result.put("Rest-Key", accountKey);

    // Create a new secret key
    SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(accountSecret), "HmacSHA512");

    // 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;
    }

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

        result.put("Rest-Sign", Base64.encodeBase64String(mac.doFinal(postData.getBytes("UTF-8"))));

    } catch (UnsupportedEncodingException uee) {

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

        return null;
    }

    return result;
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * encrypt a string using a random session key
 *
 * @param plaintext/*from  w  w w.  java 2 s . c  o  m*/
 * @return encrypted String
 * @throws Exception
 * @author Peli
 */
public String encryptWithSessionKey(String plaintext) throws CryptoHelperException {
    if (debug) {
        Log.i(TAG, "Encrypt with session key");
    }
    status = false; // assume failure
    if (password == null) {
        String msg = "Must call setPassword before runing encrypt.";
        throw new CryptoHelperException(msg);
    }
    byte[] cipherSessionKey = {};
    byte[] ciphertext = {};

    // First create a session key
    SecretKey sessionKey = null;
    byte[] sessionKeyEncoded = null;
    String sessionKeyString = null;
    try {
        KeyGenerator keygen;
        keygen = KeyGenerator.getInstance("AES");
        keygen.init(256); // needs 96 bytes
        //keygen.init(128); // needs 64 bytes
        sessionKey = keygen.generateKey();
        sessionKeyEncoded = sessionKey.getEncoded();
        sessionKeyString = new String(sessionKeyEncoded);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "generateMasterKey(): " + e.toString());
    }

    // Convert this to a Pbe key
    PBEKeySpec sessionPbeKeySpec = new PBEKeySpec(sessionKeyString.toCharArray());
    SecretKey sessionPbeKey = null;
    try {
        sessionPbeKey = keyFac.generateSecret(sessionPbeKeySpec);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "setPassword(): " + e.toString());
    }

    // Encrypt the session key using the master key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
        cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded);
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey(): " + e.toString());
    }

    // Now encrypt the text using the session key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, sessionPbeKey, pbeParamSpec);
        ciphertext = pbeCipher.doFinal(plaintext.getBytes());
        status = true;
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey2(): " + e.toString());
    }

    String stringCipherVersion = "A";
    String stringCipherSessionKey = toHexString(cipherSessionKey);
    String stringCiphertext = toHexString(ciphertext);
    if (debug) {
        Log.i(TAG, "Length: " + stringCipherSessionKey.length() + ", " + stringCipherSessionKey);
    }

    StringBuilder sb = new StringBuilder(
            stringCipherVersion.length() + stringCipherSessionKey.length() + stringCiphertext.length());
    sb.append(stringCipherVersion);
    sb.append(stringCipherSessionKey);
    sb.append(stringCiphertext);
    return sb.toString();
}

From source file:de.andreas_rueckert.trade.site.cryptsy.client.CryptsyClient.java

/**
 * Execute a authenticated query on cryptsy.
 *
 * @param method      The method to execute.
 * @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.
 *//*from   w ww .  j  a v  a2 s  .co m*/
private final JSON 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 = null; // The used key of the account.
    String accountSecret = null; // 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 if (_defaultUserAccount != null) { // Use the default values from the API implementation.

        accountKey = _defaultUserAccount.getAPIkey();
        accountSecret = _defaultUserAccount.getSecret();
    }

    // Check, if account key and account secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Public key not available for authenticated request to " + _name);
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException(
                "Private key not available for authenticated request to " + _name);
    }

    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(_url, 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(_name + " trade API request failed: " + errorMessage);

                return null;

            } else { // Request succeeded!

                // Try to figure, what the return actually is: json object or json array?

                // Test, if the return value is an JSONArray.
                JSONArray arrayReturn = jsonResult.optJSONArray("return");

                if (arrayReturn != null) { // Converting the result into a JSON array worked, so return it.

                    return arrayReturn;
                }

                // Now test, if the return value is a JSONObject.
                JSONObject objectReturn = jsonResult.optJSONObject("return");

                if (objectReturn != null) { // Converting the result into a JSON object worked, so return it.

                    return objectReturn;
                }

                if (!jsonResult.has("return")) { // Has this object no return value?

                    LogUtils.getInstance().getLogger()
                            .error(_name + " trade API request '" + method + "' has no return value.");

                    return null; // No reasonable return value possible.

                } else { // There is a return value, but it's neither an array or a object, so we cannot convert it.

                    LogUtils.getInstance().getLogger().error(_name + " trade API request '" + method
                            + "' has a return value, that is neither a JSONObject or a JSONArray. Don't know, what to do with it.");

                    return null; // Not much we can do here...
                }
            }

        } 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:com.stimulus.archiva.store.MessageStore.java

public void init() throws MessageStoreException {
    tempfiles = Config.getFileSystem().getTempFiles();
    byte[] salt = Config.getConfig().getSalt();
    String passPhrase = getPassPhrase();
    if (!isDefaultPassPhraseModified())
        logger.warn("archiving is disabled. encryption password is not set.");
    int iterationCount = 17;
    String algorithm = Config.getConfig().getPBEAlgorithm(); // "PBEWithMD5AndDES")
    // Create the key
    try {//from  www .  j a  v a  2s.co  m
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
        key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec);

        paramSpec = new PBEParameterSpec(salt, iterationCount);

    } catch (java.security.NoSuchAlgorithmException e) {
        throw new MessageStoreException(
                "failed to locate desired encryption algorithm {algorithm='" + algorithm + "'", logger);
    } catch (Exception e) {
        throw new MessageStoreException(e.toString(), e, logger);
    }
}

From source file:de.andreas_rueckert.trade.site.anx.client.ANXClient.java

/**
 * Create authentication entries for a HTTP post header.
 *
 * @param postData The data to post via HTTP.
 * @param userAccount The account of the user on the exchange. Null, if the default account should be used.
 *
 * @return The header entries as a map or null if an error occured.
 *///from   w w  w.ja va 2  s . c  om
Map<String, String> getAuthenticationHeader(String postData, TradeSiteUserAccount userAccount) {

    HashMap<String, String> result = new HashMap<String, String>();
    Mac mac;
    String accountKey = null;
    String accountSecret = null;

    // Try to get user account and secret.
    if (userAccount != null) {

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

    } else { // Throw an error.

        throw new MissingAccountDataException("No user account given for " + _name + " request");
    }

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

    result.put("Rest-Key", accountKey);

    // Create a new secret key
    SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(accountSecret), "HmacSHA512");

    // 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;
    }

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

        result.put("Rest-Sign", Base64.encodeBase64String(mac.doFinal(postData.getBytes("UTF-8"))));

    } catch (UnsupportedEncodingException uee) {

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

        return null;
    }

    return result;
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * encrypt a file using a random session key
 *
 * @param contentResolver is used to be able to read the stream
 * @param fileUri         is the stream or file to read from
 * @return Uri to the created plaintext file
 * @throws Exception/*from  w w  w  . jav a2s.c  o m*/
 * @author Peli
 */
public Uri encryptFileWithSessionKey(ContentResolver contentResolver, Uri fileUri)
        throws CryptoHelperException {
    if (debug) {
        Log.d(TAG, "Encrypt with session key");
    }
    status = false; // assume failure
    if (password == null) {
        String msg = "Must call setPassword before runing encrypt.";
        throw new CryptoHelperException(msg);
    }

    String outputPath = "";
    try {
        InputStream is;
        if (fileUri.getScheme().equals("file")) {
            is = new java.io.FileInputStream(fileUri.getPath());
            outputPath = fileUri.getPath() + OISAFE_EXTENSION;
        } else {
            is = contentResolver.openInputStream(fileUri);
            outputPath = getTemporaryFileName();
        }

        FileOutputStream os = new FileOutputStream(outputPath);

        byte[] cipherSessionKey = {};
        //         byte[] ciphertext = {};

        // First create a session key
        SecretKey sessionKey = null;
        byte[] sessionKeyEncoded = null;
        //         String sessionKeyString = null;
        try {
            KeyGenerator keygen;
            keygen = KeyGenerator.getInstance("AES");
            keygen.init(256); // needs 96 bytes
            //keygen.init(128); // needs 64 bytes
            sessionKey = keygen.generateKey();
            sessionKeyEncoded = sessionKey.getEncoded();
            //            sessionKeyString = new String(sessionKeyEncoded);
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "generateMasterKey(): " + e.toString());
            return null;
        }

        // Encrypt the session key using the master key
        try {
            pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
            cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded);
            status = true;
        } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
                | InvalidKeyException e) {
            Log.e(TAG, "encryptWithSessionKey(): " + e.toString());
        }
        if (!status) {
            return null;
        }
        status = false;

        String stringCipherVersion = "A";
        byte[] bytesCipherVersion = stringCipherVersion.getBytes();
        os.write(bytesCipherVersion, 0, bytesCipherVersion.length);

        os.write(cipherSessionKey, 0, cipherSessionKey.length);

        if (debug) {
            Log.d(TAG, "bytesCipherVersion.length: " + bytesCipherVersion.length);
        }
        if (debug) {
            Log.d(TAG, "cipherSessionKey.length: " + cipherSessionKey.length);
        }

        Trivium tri = new Trivium();
        try {
            tri.setupKey(Trivium.MODE_ENCRYPT, sessionKeyEncoded, 0);
            tri.setupNonce(sessionKeyEncoded, 10);

            // Create the byte array to hold the data
            final int bytesLen = 4096; // buffer length
            byte[] bytesIn = new byte[bytesLen];
            byte[] bytesOut = new byte[bytesLen];

            int offset = 0;
            int numRead = 0;
            while ((numRead = is.read(bytesIn, 0, bytesLen)) >= 0) {
                tri.process(bytesIn, 0, bytesOut, 0, numRead);

                os.write(bytesOut, 0, numRead);
                offset += numRead;
            }

            // Ensure all the bytes have been read in
            if (offset < is.available()) {
                throw new IOException("Could not completely read file ");
            }

            // Close the input stream and return bytes
            is.close();
            os.close();

            // Securely delete the original file:
            SecureDelete.delete(new File(fileUri.getPath()));
            status = true;

        } catch (ESJException e) {
            Log.e(TAG, "Error encrypting file", e);
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found", e);
    } catch (IOException e) {
        Log.e(TAG, "IO Exception", e);
    }

    if (status == false) {
        return null;
    }
    return Uri.fromFile(new File(outputPath)); //Uri.parse("file://" + outputPath); // TODO: UUEncode
}