Rya*_*ral 14
使用Android平台中的散列算法HMAC-SHA256计算消息摘要:
private void generateHashWithHmac256(String message, String key) {
    try {
        final String hashingAlgorithm = "HmacSHA256"; //or "HmacSHA1", "HmacSHA512"
        byte[] bytes = hmac(hashingAlgorithm, key.getBytes(), message.getBytes());
        final String messageDigest = bytesToHex(bytes);
        Log.i(TAG, "message digest: " + messageDigest);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static byte[] hmac(String algorithm, byte[] key, byte[] message) throws NoSuchAlgorithmException, InvalidKeyException {
    Mac mac = Mac.getInstance(algorithm);
    mac.init(new SecretKeySpec(key, algorithm));
    return mac.doFinal(message);
}
public static String bytesToHex(byte[] bytes) {
    final char[] hexArray = "0123456789abcdef".toCharArray();
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0, v; 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);
}
这种方法不需要任何外部依赖.
试试下面的代码
public static String encode(String key, String data) throws Exception {
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    sha256_HMAC.init(secret_key);
    return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
Hex.encodeHexString()使用此方法,将以下依赖项添加到您的应用程序gradle.
compile 'org.apache.directory.studio:org.apache.commons.codec:1.8'
这会将结果字符串转换为十六进制字符串,与您的php hash_hmac()函数生成相同.
| 归档时间: | 
 | 
| 查看次数: | 7315 次 | 
| 最近记录: |