如何在Android上使用SHA-256

时间:2014-09-12 07:27:23

标签: java android http hex sha

我需要加密我的Android API调用。我需要使用SHA-256。

我试过jokecamp.com这个例子,但它似乎不适用于Android我也从commons.apache.org导入了Jar文件

这是我的代码:

package com.example.api_tester;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    public static final String TAG = MainActivity.class.getSimpleName();
    APICall api;
    ApiSecurity hash_security;

    TextView url;
    TextView api_result;
    TextView url_call;
    private String hardCodedUrl = " MY API URL";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Hide Action Bar min target apit set to 11
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getActionBar().hide();
        setContentView(R.layout.activity_main);
        Log.i(TAG, "onCreate");

        ...

        test();

    }//end - onCreate




        private void test(){           
            try {
                String secret = "acbdef";
                String message = "api_key=abcd123&access_token=123abc";

                Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
                SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
                sha256_HMAC.init(secret_key);            

                String hash = Hex.encodeHexString(sha256_HMAC.doFinal(message.getBytes()));
                Log.e(TAG, "Result=> " + hash);
            }
            catch (Exception e) {
                Log.e(TAG, "Error=> " + e);
            }
        }//end test

    ...

这是我得到的恐怖:

09-12 13:39:42.676: E/AndroidRuntime(13531): java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Hex.encodeHexString

谢谢你们。

2 个答案:

答案 0 :(得分:1)

您正在使用Apache Commons Codec

String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);

对于java,请执行此操作

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes("UTF-8"));

答案 1 :(得分:0)

好像你错过了" encodeHexString"方法 - 而不是包括整个jar,使用任何简单的实现...例如:

private final static char[] hexArray = "0123456789abcdef".toCharArray();

private static String encodeHexString(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}