簡體   English   中英

php 和 java hmac_sha1 散列不一樣

[英]php and java hmac_sha1 hashing are not the same

我正在嘗試將消息散列到用 php 編寫並由 HMAC_SHA1 算法編碼的服務器端(我無法更改他的代碼)。 我正在用Java編寫代碼。 php代碼如下:

$utf8Str = mb_convert_encoding($strToSign, "UTF-8");
$hmac_sha1_str = base64_encode(hash_hmac("sha1", $utf8Str, KEY));
$signature = urlencode($hmac_sha1_str);

我的Java代碼是:

private static String HashStringSign(String toHash){
try {
    String afterUTF = new String(toHash.getBytes(), "UTF-8");
    String res = hmac_sha1(afterUTF, SecretAccessKey);
    String signature = new String(Base64.encode(res.getBytes()));
    String result = URLEncoder.encode(signature);
        return result;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

private static String hmac_sha1(String value, String key) {
    try {
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();           
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

我遵循了 php 代碼中使用的每個散列方法,並按照您所看到的順序。 也許java中有一個函數在php中的工作方式不同?

我正在使用 - com.sun.org.apache.xml.internal.security.utils.Base64 java.net.URLEncoder、javax.crypto 和 org.apache.commons.codec.binary

謝謝!

在您的hash_hmac函數中,您需要將第 4 個參數設置為 true。

PHP 代碼不負責,僅 Java:

所以現在你說你不能改變PHP端,你可以對你的Java代碼做以下操作。

在 Java 代碼的最后一步中,您將原始字節數組轉換為十六進制。 但是,PHP 生成 base64 編碼的十六進制,而不僅僅是十六進制。

因此,在您的 Java 步驟結束時,只需對您的十六進制進行 base64 編碼,您將獲得相同的值。 https://stackoverflow.com/questions/9845767/base64-encoder-java#

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM