Example usage for java.security InvalidKeyException toString

List of usage examples for java.security InvalidKeyException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:de.niklasmerz.cordova.fingerprint.Fingerprint.java

/**
 * Initialize the {@link Cipher} instance with the created key in the {@link #createKey()}
 * method./*w  w  w  . j  a va 2  s .co  m*/
 *
 * @return {@code true} if initialization is successful, {@code false} if the lock screen has
 * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
 * the key was generated.
 */
private static boolean initCipher() {
    boolean initCipher = false;
    String errorMessage = "";
    String initCipherExceptionErrorPrefix = "Failed to init Cipher: ";
    try {
        SecretKey key = getSecretKey();
        mCipher.init(Cipher.ENCRYPT_MODE, key);
        initCipher = true;
    } catch (InvalidKeyException e) {
        errorMessage = initCipherExceptionErrorPrefix + "InvalidKeyException: " + e.toString();
    }
    if (!initCipher) {
        Log.e(TAG, errorMessage);
    }
    return initCipher;
}

From source file:com.QuarkLabs.BTCeClientJavaFX.networking.AuthRequest.java

public JSONObject makeRequest(String method, Map<String, String> arguments)
        throws UnsupportedEncodingException {
    if (method == null) {
        return null;
    }/*from w w w .  j a  v a2 s .c  o  m*/
    if (arguments == null) {
        arguments = new HashMap<>();
    }
    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }
    StringBuilder out = new StringBuilder();
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("Key", key);
        String sign = byteArrayToHexString(mac.doFinal(postData.getBytes("UTF-8")));
        urlConnection.setRequestProperty("Sign", sign);
        urlConnection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                out.append(line);
            }
            rd.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new JSONObject(out.toString());
}

From source file:net.fenyo.mail4hotspot.web.GMailOAuthStep1Servlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {// w  ww.  j a va 2  s. c o  m
        if (request.getPathInfo().equals("/step1")) {
            //            final String uuid = request.getParameter("uuid");
            final String nonce = nonce();
            final String now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);
            final String base_string = "GET&"
                    + urlEncode("https://www.google.com/accounts/OAuthGetRequestToken") + "&"
                    + urlEncode("oauth_callback=" + urlEncode(base + "oauth/step2")
                            + "&oauth_consumer_key=www.vpnoverdns.com&oauth_nonce=" + nonce
                            + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now
                            + "&oauth_version=1.0&scope=" + urlEncode("https://mail.google.com/"));
            log.debug("digestencoded=" + urlEncode(hmac(consumer_secret + "&", base_string)));
            final String url = "https://www.google.com/accounts/OAuthGetRequestToken?oauth_consumer_key=www.vpnoverdns.com&oauth_nonce="
                    + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now
                    + "&oauth_version=1.0&oauth_callback=" + urlEncode(base + "oauth/step2") + "&scope="
                    + urlEncode("https://mail.google.com/") + "&oauth_signature="
                    + urlEncode(hmac(consumer_secret + "&", base_string));
            final String reply = Browser.getHtml(url, null);
            // request_token est URL encoded
            final String request_token = parseReply("oauth_token", reply);
            // request_token_secret est URL encoded
            final String request_token_secret = parseReply("oauth_token_secret", reply);
            log.debug("oauthtoken=" + request_token);
            log.debug("oauthtokensecret=" + request_token_secret);
            if (request_token == null || request_token_secret == null) {
                log.error("token error: token=" + request_token + " - token_secret=" + request_token_secret);
                return;
            }
            map_request_token.put(urlDecode(request_token), urlDecode(request_token_secret));

            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location",
                    "https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=" + request_token);
            final PrintWriter out = response.getWriter();
            out.println(
                    "<html><body>click <a href='https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token="
                            + request_token + "'>here</a></body></html>");
        }

        if (request.getPathInfo().equals("/step2")) {
            final String verifier = request.getParameter("oauth_verifier");
            // request_token n'est pas URL encoded
            final String request_token = request.getParameter("oauth_token");
            // request_token_secret n'est pas URL encoded
            final String request_token_secret = map_request_token.get(request_token);

            log.debug("oauthtoken=" + request_token);
            log.debug("oauthtokensecret=" + request_token_secret);
            log.debug("verifier=" + verifier);

            String nonce = nonce();
            String now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);

            String base_string = "GET&" + urlEncode("https://www.google.com/accounts/OAuthGetAccessToken") + "&"
                    + urlEncode("oauth_consumer_key=www.vpnoverdns.com&oauth_nonce=" + nonce
                            + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now + "&oauth_token="
                            + urlEncode(request_token) + "&oauth_verifier=" + urlEncode(verifier)
                            + "&oauth_version=1.0");

            log.debug("digestencoded="
                    + urlEncode(hmac(consumer_secret + "&" + request_token_secret, base_string)));

            String url = "https://www.google.com/accounts/OAuthGetAccessToken?oauth_consumer_key=www.vpnoverdns.com&oauth_nonce="
                    + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now + "&oauth_token="
                    + urlEncode(request_token) + "&oauth_verifier=" + urlEncode(verifier)
                    + "&oauth_version=1.0&oauth_signature="
                    + urlEncode(hmac(consumer_secret + "&" + request_token_secret, base_string));

            final String reply = Browser.getHtml(url, null);
            // access token est URL encoded
            final String access_token = parseReply("oauth_token", reply);
            // access_token_secret est URL encoded
            final String access_token_secret = parseReply("oauth_token_secret", reply);
            log.debug("oauthaccesstoken=" + access_token);
            log.debug("oauthaccesstokensecret=" + access_token_secret);

            nonce = nonce();
            now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);

            base_string = "GET&" + urlEncode("https://mail.google.com/mail/b/alexandre.fenyo2@gmail.com/imap/")
                    + "&"
                    + urlEncode("oauth_consumer_key=www.vpnoverdns.com&oauth_nonce=" + nonce
                            + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now + "&oauth_token="
                            + access_token + "&oauth_version=1.0");

            // oauth_token=\"$oauthaccesstoken\",oauth_version=\"1.0\",oauth_signature=\"$digestencoded\"" | read URL

            log.debug("digestencoded="
                    + urlEncode(hmac(consumer_secret + "&" + urlDecode(access_token_secret), base_string)));

            url = "GET https://mail.google.com/mail/b/alexandre.fenyo2@gmail.com/imap/ oauth_consumer_key=\"www.vpnoverdns.com\",oauth_nonce=\""
                    + nonce + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + now
                    + "\",oauth_token=\"" + access_token + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + urlEncode(hmac(consumer_secret + "&" + urlDecode(access_token_secret), base_string))
                    + "\"";
            log.debug(org.apache.commons.codec.binary.Base64.encodeBase64String(url.getBytes("UTF-8")));

        }

    } catch (InvalidKeyException ex) {
        log.error(ex.toString());
    } catch (NoSuchAlgorithmException ex) {
        log.error(ex.toString());
    }
}

From source file:com.QuarkLabs.BTCeClient.exchangeApi.AuthRequest.java

/**
 * Makes any request, which require authentication
 *
 * @param method    Method of Trade API/*from   w ww  . ja  v  a  2s  .  co  m*/
 * @param arguments Additional arguments, which can exist for this method
 * @return Response of type JSONObject
 * @throws JSONException
 */
@Nullable
public JSONObject makeRequest(@NotNull String method, Map<String, String> arguments) throws JSONException {

    if (key.length() == 0 || secret.length() == 0) {
        return new JSONObject("{success:0,error:'No key/secret provided'}");
    }

    if (arguments == null) {
        arguments = new HashMap<>();
    }

    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator<Map.Entry<String, String>> it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

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

    HttpURLConnection connection = null;
    BufferedReader bufferedReader = null;
    DataOutputStream wr = null;
    try {
        connection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Key", key);
        byte[] array = mac.doFinal(postData.getBytes("UTF-8"));
        connection.setRequestProperty("Sign", byteArrayToHexString(array));
        wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        InputStream response = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(response));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return new JSONObject(sb.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:net.fenyo.mail4hotspot.web.YahooOAuthStep1Servlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//w ww  . ja va2s  .  c  o  m
        if (request.getPathInfo().equals("/step1")) {
            //            final String uuid = request.getParameter("uuid");
            final String nonce = nonce();
            final String now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);
            final String base_string = "GET&"
                    + urlEncode("https://api.login.yahoo.com/oauth/v2/get_request_token") + "&"
                    + urlEncode("oauth_callback=" + urlEncode(base + "yoauth/step2") + "&oauth_consumer_key="
                            + urlEncode(
                                    "dj0yJmk9UmZhMmthTU1EcVExJmQ9WVdrOWIxZEZaMWRGTldNbWNHbzlNVGMyTmprME5qSS0mcz1jb25zdW1lcnNlY3JldCZ4PTc2")
                            + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp="
                            + now + "&oauth_version=1.0");
            log.debug("digestencoded=" + urlEncode(hmac(consumer_secret + "&", base_string)));
            final String url = "https://api.login.yahoo.com/oauth/v2/get_request_token?oauth_consumer_key="
                    + urlEncode(
                            "dj0yJmk9UmZhMmthTU1EcVExJmQ9WVdrOWIxZEZaMWRGTldNbWNHbzlNVGMyTmprME5qSS0mcz1jb25zdW1lcnNlY3JldCZ4PTc2")
                    + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now
                    + "&oauth_version=1.0&oauth_callback=" + urlEncode(base + "yoauth/step2")
                    + "&oauth_signature=" + urlEncode(hmac(consumer_secret + "&", base_string));
            final String reply = Browser.getHtml(url, null);
            // request_token est URL encoded
            final String request_token = parseReply("oauth_token", reply);
            // request_token_secret est URL encoded
            final String request_token_secret = parseReply("oauth_token_secret", reply);
            log.debug("oauthtoken=" + request_token);
            log.debug("oauthtokensecret=" + request_token_secret);
            if (request_token == null || request_token_secret == null) {
                log.error("token error: token=" + request_token + " - token_secret=" + request_token_secret);
                return;
            }
            map_request_token.put(urlDecode(request_token), urlDecode(request_token_secret));

            final String xoauth_request_auth_url = parseReply("xoauth_request_auth_url", reply);
            log.debug("xoauth_request_auth_url=" + xoauth_request_auth_url);

            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", urlDecode(xoauth_request_auth_url));
            final PrintWriter out = response.getWriter();
            out.println("<html><body>click <a href='" + urlDecode(xoauth_request_auth_url)
                    + "'>here</a></body></html>");
        }

        if (request.getPathInfo().equals("/step2")) {
            final String verifier = request.getParameter("oauth_verifier");
            // request_token n'est pas URL encoded
            final String request_token = request.getParameter("oauth_token");
            // request_token_secret n'est pas URL encoded
            final String request_token_secret = map_request_token.get(request_token);

            log.debug("oauthtoken=" + request_token);
            log.debug("oauthtokensecret=" + request_token_secret);
            log.debug("verifier=" + verifier);

            String nonce = nonce();
            String now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);

            String base_string = "GET&" + urlEncode("https://api.login.yahoo.com/oauth/v2/get_token") + "&"
                    + urlEncode("oauth_consumer_key=" + urlEncode(
                            "dj0yJmk9UmZhMmthTU1EcVExJmQ9WVdrOWIxZEZaMWRGTldNbWNHbzlNVGMyTmprME5qSS0mcz1jb25zdW1lcnNlY3JldCZ4PTc2")
                            + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp="
                            + now + "&oauth_token=" + urlEncode(request_token) + "&oauth_verifier="
                            + urlEncode(verifier) + "&oauth_version=1.0");

            log.debug("digestencoded="
                    + urlEncode(hmac(consumer_secret + "&" + request_token_secret, base_string)));

            String url = "https://api.login.yahoo.com/oauth/v2/get_token?oauth_consumer_key=" + urlEncode(
                    "dj0yJmk9UmZhMmthTU1EcVExJmQ9WVdrOWIxZEZaMWRGTldNbWNHbzlNVGMyTmprME5qSS0mcz1jb25zdW1lcnNlY3JldCZ4PTc2")
                    + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now
                    + "&oauth_token=" + urlEncode(request_token) + "&oauth_verifier=" + urlEncode(verifier)
                    + "&oauth_version=1.0&oauth_signature="
                    + urlEncode(hmac(consumer_secret + "&" + request_token_secret, base_string));

            final String reply = Browser.getHtml(url, null);
            // access token est URL encoded
            final String access_token = parseReply("oauth_token", reply);
            // access_token_secret est URL encoded
            final String access_token_secret = parseReply("oauth_token_secret", reply);
            log.debug("oauthaccesstoken=" + access_token);
            log.debug("oauthaccesstokensecret=" + access_token_secret);

            final String xoauth_yahoo_guid = parseReply("xoauth_yahoo_guid", reply);
            log.debug("xoauth_yahoo_guid=" + xoauth_yahoo_guid);

            nonce = nonce();
            now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);

            base_string = "GET&" + urlEncode("https://mail.google.com/mail/b/alexandre.fenyo2@gmail.com/imap/")
                    + "&"
                    + urlEncode("oauth_consumer_key=www.vpnoverdns.com&oauth_nonce=" + nonce
                            + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now + "&oauth_token="
                            + access_token + "&oauth_version=1.0");

            // oauth_token=\"$oauthaccesstoken\",oauth_version=\"1.0\",oauth_signature=\"$digestencoded\"" | read URL

            log.debug("digestencoded="
                    + urlEncode(hmac(consumer_secret + "&" + urlDecode(access_token_secret), base_string)));

            url = "GET https://mail.google.com/mail/b/alexandre.fenyo2@gmail.com/imap/ oauth_consumer_key=\"www.vpnoverdns.com\",oauth_nonce=\""
                    + nonce + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + now
                    + "\",oauth_token=\"" + access_token + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + urlEncode(hmac(consumer_secret + "&" + urlDecode(access_token_secret), base_string))
                    + "\"";
            log.debug(org.apache.commons.codec.binary.Base64.encodeBase64String(url.getBytes("UTF-8")));

            //               String url2 =
            //                     "GET https://mail.google.com/mail/b/alexandre.fenyo2@gmail.com/imap/ oauth_consumer_key=\"www.vpnoverdns.com\",oauth_nonce=\"" +
            //                     nonce +
            //                     "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" +
            //                     now +
            //                     "\",oauth_token=\"" +
            //                     access_token +
            //                     "\",oauth_version=\"1.0\",oauth_signature=\"" +
            //                     urlEncode(hmac(consumer_secret + "&" + urlDecode(access_token_secret), base_string)) +"\"";
            //               log.debug(org.apache.commons.codec.binary.Base64.encodeBase64String(url.getBytes("UTF-8")));

        }

    } catch (InvalidKeyException ex) {
        log.error(ex.toString());
    } catch (NoSuchAlgorithmException ex) {
        log.error(ex.toString());
    }
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

private X509Certificate generateV3Certificate(KeyPair pair, String certSubjectDN, Calendar before,
        Calendar expiry) throws CryptoException {
    X509V3CertificateGenerator cert = new X509V3CertificateGenerator();

    /* Set the certificate serial number to a random number */
    Random rand = new Random();
    rand.setSeed(System.currentTimeMillis());

    /* Generates a number between 0 and 2^32 as the serial */
    BigInteger serial = BigInteger.valueOf(rand.nextInt(Integer.MAX_VALUE));
    logger.info("Setting X509 Cert Serial to: " + serial);

    cert.setSerialNumber(serial);/*from  ww  w  .  j  a  v a 2  s  .c o  m*/

    /* Set the certificate issuer */
    cert.setIssuerDN(new X500Principal(this.certIssuerDN));

    /* Set the start of valid period. */
    cert.setNotBefore(before.getTime());

    /* Set the certificate expiry date. */
    cert.setNotAfter(expiry.getTime());

    /* Set the subject */
    cert.setSubjectDN(new X500Principal(certSubjectDN));

    cert.setPublicKey(pair.getPublic());

    /* Signature algorithm, this may need to be changed if not all hosts have SHA256 and RSA implementations */
    cert.setSignatureAlgorithm("SHA512withRSA");

    cert.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    /* Only for signing */
    cert.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
    cert.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    /* Set a contact email address for the issuer */
    cert.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, this.certIssuerEmail)));

    logger.debug("Generating X509Certificate for key pair: " + pair);

    try {
        /* Use the BouncyCastle provider to actually generate the X509Certificate now */
        return cert.generateX509Certificate(pair.getPrivate(), "BC");
    } catch (InvalidKeyException e) {
        this.logger.error("InvalidKeyException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchProviderException e) {
        this.logger.error("NoSuchProviderException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (SecurityException e) {
        this.logger.error("SecurityException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (SignatureException e) {
        this.logger.error("SignatureException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), 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.
 *//*from   w w  w.jav  a 2 s .co  m*/
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: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  ww  w  . ja v  a2 s  . c o 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: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  ww  . ja v a  2s. c  o m
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:de.andreas_rueckert.trade.site.btc_e.client.BtcEClient.java

/**
 * Execute a authenticated query on btc-e.
 *
 * @param method The method to execute.//  w  w w . j  av a2  s. c om
 * @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.
}