2014-04-11 27 views
1

我需要使用C#& C++ Metro(WinRT)應用程序中的PBKDF2加密來從密碼中派生密鑰。在Metro上我應該使用什麼來派生使用PBKDF2的密鑰(如OpenSSL的PKCS5_PBKDF2_HMAC_SHA1調用)?是否有基於WinRT的OpenSSL版本? (我讀過它只能在桌面平臺的Windows上構建)。或者是否有其他解決方案我應該使用?在Metro(WinRT)應用程序中使用PBKDF2加密

順便說一句我可以從C#或C++調用該函數,所以任何一個都可以。任何意見將不勝感激!

編輯: 我剛剛發現一個名爲「Rfc2898DeriveBytes」的.NET函數 - 詳細信息here。如果我正確讀取它,它將執行與OpenSSL的PKCS5_PBKDF2_HMAC_SHA1調用相同的操作 - 是否正確?

編輯#2: 不幸的是,它看起來像我不能因爲儘管什麼Microsoft documentation for Rfc2898DeriveBytes說,在我的Windows 8.1 Metro應用使用Rfc2898DeriveBytes畢竟,該API方法不會在「Windows.Security.Cryptography存在'構建Windows 8.1應用程序時的命名空間。還有什麼我可以使用的?

+0

是的,它是正確的,但是因爲它還有一點點我也寫了一個答案。 –

回答

3

經過多次挖掘,我終於找到了this link。下面是我在Metro應用程序中做的事情:

private static bool GetPBKDFDerivedKey(string password, 
    byte[] salt,     // length = 32 bytes (256 bits) 
    out byte[] encryptionKeyOut) // length = 32 bytes (256 bits) 
{    
    IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(salt); 
    KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); // 10000 iterations 

    // Get a KDF provider for PBKDF2 and hash the source password to a Cryptographic Key using the SHA256 algorithm. 
    // The generated key for the SHA256 algorithm is 256 bits (32 bytes) in length. 
    KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256); 
    IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); 
    CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer); 

    // Generate key material from the source password, salt, and iteration count 
    const int keySize = 256/8; // 256 bits = 32 bytes 
    IBuffer key = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, keySize); 

    // send the generated key back to the caller 
    CryptographicBuffer.CopyToByteArray(key, out encryptionKeyOut); 

    return true; // success 
} 
1

您可以使用Rfc2898DeriveBytes作爲RFC actually defines PBKDF2。請注意,您需要確保您使用相同的字符編碼,鹽的大小和輪數來兼容。通常SHA1被用作底層哈希函數(這很好),但要注意PBKDF2也可以使用其他哈希函數。 Rfc2898DeriveBytes利用SHA1來實現HMAC功能。

請注意Rfc2898DeriveBytes利用UTF-8; Mickeysoft沒有記錄(甚至在多次請求後)。如果您不確定兩種平臺上的編碼,則可以使用字節數組。如果您允許字符超出US ASCII範圍,您應該特別注意這一點。

+0

感謝你們,特別是UTF-8信息!我將在我的應用程序中使用[Rfc2898DeriveBytes](http://msdn.microsoft.com/zh-cn/library/system.security.cryptography.rfc2898derivebytes.aspx)。 – dbeachy1

+0

我在這裏遇到了一個問題 - 雖然Microsoft爲Rfc2898DeriveBytes提供的文檔說,「平臺:Windows Phone 8.1,Windows Phone 8,Windows 8.1 ...」,Visual Studio在編譯期間失敗,錯誤爲\t 1類型或名稱空間名稱'Rfc2898DeriveBytes'在命名空間'Windows.Security.Cryptography'中不存在。還有什麼我可以使用? – dbeachy1

+1

我想你可以使用同一類的單聲道源代碼,因爲它似乎是麻省理工學院許可的。不過,您可能需要放入不同的HMAC實施。應該有其他代碼來實現它。請注意,一旦獲得HMAC或SHA功能,就不會「非常」難以實現。 –

相關問題