2011-07-13 42 views
3

我在Java中執行以下操作時遇到問題。以下是我正在使用的工具的文檔中的Fantom代碼。Java相當於使用SHA1的Fantom HMAC

// compute salted hmac 
hmac := Buf().print("$username:$userSalt").hmac("SHA-1", password.toBuf).toBase64 

// now compute login digest using nonce 
digest := "${hmac}:${nonce}".toBuf.toDigest("SHA-1").toBase64 

// our example variables 
username: "jack" 
password: "pass" 
userSalt: "6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU=" 
nonce: "3da210bdb1163d0d41d3c516314cbd6e" 
hmac:  "IjJOApgvDoVDk9J6NiyWdktItl0=" 
digest: "t/nzXF3n0zzH4JhXtihT8FC1N3s=" 

我一直在通過Google搜索各種示例,但沒有一個產生結果文檔聲明應該返回。

Fantom知識的人可以驗證文檔中的示例是否正確?

至於Java方面,這是我最近嘗試

public static String hmacSha1(String value, String key) { 
    try { 
     // Get an hmac_sha1 key from the raw key bytes 
     byte[] keyBytes = key.getBytes("UTF-8");   
     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("UTF-8")); 

     // Convert raw bytes to Hex 
     byte[] hexBytes = new Hex().encode(rawHmac); 

     // Covert array of Hex bytes to a String 
     return new String(hexBytes, "UTF-8"); 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

然而,當我調用該方法具有以下參數

jack:6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU= 
pass 

我得到

22324e02982f0e854393d27a362c96764b48b65d 

回答

1

原來這只是我自己的知識的缺乏,並有足夠的試驗和錯誤,我能夠做弄明白如下:

//username: "jack" 
//password: "pass" 
//userSalt: "6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU=" 
//nonce: "3da210bdb1163d0d41d3c516314cbd6e" 
//hmac:  "IjJOApgvDoVDk9J6NiyWdktItl0=" 
//digest: "t/nzXF3n0zzH4JhXtihT8FC1N3s=" 

... 
// initialize a Mac instance using a signing key from the password 
SecretKeySpec signingKey = new SecretKeySpec(password.getBytes(), "HmacSHA1"); 
Mac mac = Mac.getInstance("HmacSHA1"); 
mac.init(signingKey); 

// compute salted hmac 
byte[] hmacByteArray = mac.doFinal((username + ':' + userSalt).getBytes()); 
String hmacString = new String(Base64.encodeBase64(hmacByteArray)); 
// hmacString == hmac 

// now compute login digest using nonce 
MessageDigest md = MessageDigest.getInstance("SHA-1"); 
md.update((hmacString + ':' + nonce).getBytes()); 
byte[] digestByteArray = md.digest(); 
String digestString = new String(Base64.encodeBase64(digestByteArray)); 
// digestString == digest 

使用org.apache.commons.codec.binary。 Base64來編碼字節數組。

2

不知道文檔來自哪裏 - 但它們可能已過時 - 或錯誤。我會實際運行魅影代碼中使用作爲您的參考,以確保您正在測試正確的東西;)

你可以看看Java源代碼的SYS :: Buf.hmac:MemBuf.java

我也建議分離出3個轉換。確保您的原始字節數組在Fantom和Java中都匹配,然後驗證摘要匹配,最後進行Base64編碼。更容易驗證代碼中的每個階段。