[英]How to use SHA-256 with Android
I need to encrypt my Android API Call. 我需要加密我的Android API调用。 I need to use the SHA-256. 我需要使用SHA-256。
I have tried to you this example from jokecamp.com but it does not seem to work with Android I also imported the Jar file from commons.apache.org 我已经从jokecamp.com向您尝试了此示例,但它似乎不适用于Android,我也从commons.apache.org导入了Jar文件
Here is my code: 这是我的代码:
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
...
And here is the Eror I am getting: 这是我得到的错误:
09-12 13:39:42.676: E/AndroidRuntime(13531): java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Hex.encodeHexString
Thanks guys. 多谢你们。
You are using Apache Commons Codec 您正在使用Apache Commons Codec
String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);
For java do this 对于Java,执行此操作
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes("UTF-8"));
Seems you are missing the "encodeHexString" method - instead of including the whole jar, use any easy implementation around... for example: 似乎您缺少“ 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.