我正在尝试使用以下函数生成SHA256: -
func generateHMAC(key: String, data: String) -> String {
let keyData = key.dataFromHexadecimalString()! as NSData
let dataIn = data.dataUsingEncoding(NSUTF16StringEncoding)
var result: [CUnsignedChar]
result = Array(count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyData.bytes, keyData.length, dataIn!.bytes, dataIn!.length, &result)
let hash = NSMutableString()
for val in result {
hash.appendFormat("%02hhx", val)
}
return hash as String
}
输入
AccountNumber: 100195
Amount: 10
BillerID: 59
ChannelID: 2
Context: 11|test
CountryID: 1
CustomerID: 34
EmailID: ankur.arya@me.com
ReturnURL: https://uat.myfatoora.com/ReceiptPOC.aspx
SECURITYTOKEN: 6B4A47A6-40A0-4C9D-A925-5CECA2910881
TxnRefNum: 991107844408242
UserName: USP
,输出
4cd1acc736a9702c8cdb1a546d1c274a67cb285dbdbb972aab39ee51c2a226c8
但是,这与使用以下算法的后端输出不匹配
private string CreateSHA256POC(bool useRequest)
{
// Hex Decode the Secure Secret for use in using the HMACSHA256 hasher
// hex decoding eliminates this source of error as it is independent of the character encoding
// hex decoding is precise in converting to a byte array and is the preferred form for representing binary values as hex strings.
secureHash = "";
byte[] convertedHash = new byte[_secureSecret.Length / 2];
for (int i = 0; i < _secureSecret.Length / 2; i++)
{
convertedHash[i] = (byte)Int32.Parse(_secureSecret.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}
// Build string from collection in preperation to be hashed
StringBuilder sb = new StringBuilder();
SortedList<String, String> list = (useRequest ? requestFields : responseFields);
foreach (KeyValuePair<string, string> kvp in list)
{
// if (kvp.Key.StartsWith("vpc_") || kvp.Key.StartsWith("user_"))
sb.Append(kvp.Key + "=" + kvp.Value + "&");
}
// remove trailing & from string
if (sb.Length > 0)
sb.Remove(sb.Length - 1, 1);
// Create secureHash on string
string hexHash = "";
using (HMACSHA256 hasher = new HMACSHA256(convertedHash))
{
byte[] hashValue = hasher.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()));
foreach (byte b in hashValue)
{
hexHash += b.ToString("X2");
secureHash = hexHash;
}
}
return hexHash;
}
并且他们的输出是
41D8E81C128100A76185F24CE00BC6A4FEA30839E6DE3DFFBC3B5814E4FD0C4E
密钥是
71DD0F73AFFBB47825FF9864DDE95F3B
你能不能请我帮助我在Swift中更新我的方法以获得与后端相同的结果。
感谢。