我需要從將傳遞給支付服務的字串在 C# 中創建一個 SHA-256 哈希。我有一些用 PHP 提供的舊示例代碼,并撰寫了它的 C# 版本 - 不幸的是,生成的哈希沒有被需要它的服務所接受,所以看起來好像我在我的 C# 代碼中的某個地方犯了一個錯誤.
支付服務創建哈希所需的步驟是:
- 收集選定的引數并加入一個字串
- 將創建的字串轉換為其 ascii 十六進制表示
- 將 ascii 十六進制表示傳遞給 SHA-256 演算法。
這是示例 PHP 代碼:
$stringToHash = $storeName.$chargetotal.$currency.$sharedsecret; // These are just supplied variables
$ascii = bin2hex($stringToHash);
return hash("sha256", $ascii);
這是我的 C# 代碼:
var hashString = new StringBuilder();
// Append the supplied variables
hashString.Append(storeName);
hashString.Append(chargeTotal.ToString("f2"));
hashString.Append(currency);
hashString.Append(sharedSecret);
var bytes = Encoding.ASCII.GetBytes(hashString.ToString());
using (SHA256 shaM = new SHA256Managed())
{
var hash = shaM.ComputeHash(bytes);
return BitConverter.ToString(hash).Replace("-", "");
}
具體來說,我不確定我用來獲取 ascii 位元組的方法是否與 PHP bin2hex 方法中所做的相同。
編輯 - 問題解決了!
使用多項式的解決方案解決了問題。
對于某些背景資訊,使用的一般程序是將支付資訊發布到支付網關,其中一部分是散列與其他變數的純文本版本(共享秘密除外)一起發送。還有更多的變數,包括時間戳,可以避免重復哈希的問題。
然后網關服務器重新計算哈希以驗證請求。出于這個原因,散列必須匹配,我無法更改散列演算法或字符集等。有關更多資訊,此服務來自一家主要的全球銀行...
不幸的是,我對 PHP 代碼沒有任何控制權;它不是我的。該片段是作為一些“示例”代碼的一部分發送的,我不得不使用 C# 重新創建它。對于任何為此苦苦掙扎的用戶,關鍵部分是使用字串構建器而不是 BitConverter。
uj5u.com熱心網友回復:
不,那不一樣。
PHP 代碼獲取字串,將其轉換為十六進制表示,然后對該字串進行哈希處理。這還涉及一些轉換為位元組的中間內部步驟:
- 構造字串。
- 使用配置為默認值的任何文本編碼(例如 UTF-8、Windows-1252)將該字串轉換為位元組序列。
- 將該字串轉換為這些位元組的十六進制表示形式,作為字串。PHP 檔案說“一個 ASCII 字串”,但這僅指使用基本
0-9和a-f字符這一事實。字串的編碼仍然是 PHP 的默認編碼。 - 使用默認文本編碼將該字串轉換回位元組。
- 使用 SHA256 散列這些位元組并將它們作為十六進制字串回傳。
您所做的是使用 ASCII 編碼將輸入字串轉換為位元組序列,對其進行哈希處理,然后將其轉換回十六進制字串。這會跳過首先將字串轉換為十六進制的步驟,并且與字串編碼不匹配,如果輸入包含非 ASCII 字符(例如 Unicode),則會產生不同的哈希值。
PHP 代碼本身很脆弱,因為它的行為取決于系統配置。由于底層字符表示的固有差異,具有不同語言環境配置的兩個系統可能會產生不同的哈希值。例如,字串“áéíóú€”c3a1c3a9c3adc3b3c3bae282ac在 UTF-8 中編碼為,但e1e9edf3fa3f在 ISO-8859-1 和e1e9edf3fa80Windows-1252 中。
如果您可以控制 PHP 代碼,我強烈建議將其更改為使用單一規范編碼,例如 UTF-8。例如:
$token = $storeName . $chargetotal . $currency . $sharedsecret;
$utf8token = mb_convert_encoding($token, 'UTF-8');
$hextoken = bin2hex($utf8token);
return hash("sha256", $hextoken);
這消除了編碼歧義。請注意,在這里使用 ASCII 是一個糟糕的主意 - 如果輸入中包含的商店名稱或任何其他欄位可能包含重音符號、西里爾字母或 CJK 字符(您應該支持國際化!)那么您生成的哈希將不能正確代表名稱,并且可能會以意想不到的方式斷裂或碰撞。
另一個錯誤是您的數字轉換。您告訴 C# 將貨幣格式化為兩位小數,但 PHP 端只是將數字與默認轉換為字串連接起來。您應該確保 PHP 端的貨幣值被編碼為帶有兩位小數的數字,例如15.0015。
您還應該使用decimalC# 來存盤貨幣值,而不是float. 由于浮點數在內部表示數字的方式,因此不能保證它們能準確地存盤貨幣值。Decimal 保證數字的整數部分將被正確表示。小數部分的存盤精度也足以表示貨幣。
我推薦的另一件事是使用SHA256.Create()而不是顯式構造一個SHA256Managed物件。這將確保您在平臺上使用可用的本機加密實作,而不是每次都使用較慢的托管實作。
在 C# 方面,等效的則是:
// build the string
var tokenString = new StringBuilder();
tokenString.Append(storeName);
tokenString.Append(chargeTotal.ToString("0.00"));
tokenString.Append(currency);
tokenString.Append(sharedSecret);
// convert to bytes using UTF-8 encoding
var tokenBytes = Encoding.UTF8.GetBytes(tokenString);
// convert those bytes to a hexadecimal string
var tokenBytesHex = BitConverter.ToString(tokenBytes).Replace("-", "");
// convert that string back to bytes (UTF-8 used here since that is the default on PHP, but ASCII will work too)
var tokenBytesHexBytes = Encoding.UTF8.GetBytes(tokenString);
// hash those bytes
using (SHA256 sha256 = SHA256.Create())
{
var hash = sha256.ComputeHash(tokenBytesHexBytes);
return BitConverter.ToString(hash).Replace("-", "");
}
然而,這仍然是壞的。當您使用BitConverter.ToString從位元組中獲取十六進制字串時,輸出使用大寫字母(例如 FF 表示 255)。在 PHP 中,bin2hex使用小寫字母。這很重要,因為它會為散列函式生成不同的輸入。
更好的解決方案是將這些BitConverter呼叫替換為更直接的十六進制轉換,以便您可以直接控制格式:
var sb = new StringBuilder();
foreach (byte b in bytes)
sb.AppendFormat("{0:x2}", b);
var hex = sb.ToString();
這應該在 PHP 和 C# 端都匹配。
順便說一句,我強烈建議從安全的角度重新考慮這個散列方案。
The first obvious vulnerability is that a store with the same name but with a numeric suffix can produce transaction hash collisions, e.g. a store called Shoe making a $54.00 transaction has the same hash as a store called Shoe5 making a $4.00 transaction, since both will produce Shoe54.00usd. You need to separate the fields using a character that cannot be present in the input strings in order to avoid this. Ideally this involves encoding the fields in a canonical structured format such as BSON or Bencode, but a crude approach here could just be to separate fields with a tab character.
Additionally, building message authentication codes by concatenating secret and non-secret information together is problematic for Merkle-Damg?rd construction hash functions like MD5, SHA1, and SHA256. The security properties of these hash functions are not tuned for this use-case, and you may fall victim to length extension attacks. Instead, you should consider using a HMAC, which is specifically designed for this use case. You can think of a HMAC like a keyed hash. The only difference is that the shared secret is used as a key, rather than concatenated to the data being hashed.
In PHP you can use hash_hmac for this. In C# you can use HMACSHA256.
Putting that all together, you get:
$token = $storeName . "\t" . $chargetotal . "\t" . $currency;
$utf8token = mb_convert_encoding($token, 'UTF-8');
$hextoken = bin2hex($utf8token);
return hash_hmac("sha256", $hextoken, $sharedsecret);
and
// build the string
var tokenString = new StringBuilder();
tokenString.Append(storeName);
tokenString.Append("\t");
tokenString.Append(chargeTotal.ToString("0.00"));
tokenString.Append("\t");
tokenString.Append(currency);
// convert to bytes using UTF-8 encoding
var tokenBytes = Encoding.UTF8.GetBytes(tokenString);
// convert those bytes to a hexadecimal string
var sb = new StringBuilder();
for (byte b in tokenBytes)
sb.AppendFormat("{0:x2}", b);
var tokenBytesHex = sb.ToString();
// convert that string back to bytes (UTF-8 used here since that is the default on PHP, but ASCII will work too)
var tokenBytesHexBytes = Encoding.UTF8.GetBytes(tokenString);
// hash those bytes using HMAC-SHA256
byte[] sharedSecretBytes = Encoding.UTF8.GetBytes(sharedsecret);
using (HMACSHA256 hmac_sha256 = new HMACSHA256(sharedSecretBytes))
{
var hashBytes = hmac_sha256.ComputeHash(tokenBytesHexBytes);
sb = new StringBuilder();
for (byte b in hashBytes)
sb.AppendFormat("{0:x2}", b);
var hashString = sb.ToString();
return hashString;
}
從安全角度來看,這仍然不是 100% 理想,因為在不同時間進行的相同金額的兩次交易將具有相同的哈希值,但是您說這些欄位是示例,因此我不會在那里進一步演示。可以說你應該在那里有一些唯一的交易識別符號。另一個潛在問題是,您將在 C# 端的堆上留下包含哈希的字串,這些字串是敏感的,但如果不SecureString非常小心地使用,您就無能為力,這是一個非常復雜的話題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/363145.html
上一篇:DocumentationFile和GenerateDocumentationFile可以在.Net專案檔案中一起使用嗎?
