在android中有没有创建Hmac256字符串的功能?

Bik*_*h M 15 android hmac hmacsha1

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

请帮我.

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);
}
Run Code Online (Sandbox Code Playgroud)

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


Chi*_*vda 9

试试下面的代码

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")));
}
Run Code Online (Sandbox Code Playgroud)

Hex.encodeHexString()使用此方法,将以下依赖项添加到您的应用程序gradle.

compile 'org.apache.directory.studio:org.apache.commons.codec:1.8'
Run Code Online (Sandbox Code Playgroud)

这会将结果字符串转换为十六进制字符串,与您的php hash_hmac()函数生成相同.