有什么功能可以在android中创建Hmac256字符串吗? [英] Is there any function for creating Hmac256 string in android?

查看:81
本文介绍了有什么功能可以在android中创建Hmac256字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android中是否有用于创建Hmac256字符串的功能? 我使用php作为我的android应用程序的后端,在php中,我们可以使用php函数hash_hmac()[

Is there any function for creating Hmac256 string in android ? I am using php as my back end for my android application, in php we can create hmac256 string using the php function hash_hmac () [ ref ] is there any function like this in Android

请帮助我.

推荐答案

在Android平台中使用哈希算法 HMAC-SHA256 计算消息摘要:

Calculate the message digest with the hashing algorithm HMAC-SHA256 in the Android platform:

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

这种方法不需要任何外部依赖.

This approach does not require any external dependency.

这篇关于有什么功能可以在android中创建Hmac256字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆