繁体   English   中英

在Metro(WinRT)应用程序中使用PBKDF2加密

[英]Using PBKDF2 encryption in a Metro (WinRT) application

我需要在C#和C ++ Metro(WinRT)应用程序中使用PBKDF2加密从加盐密码派生密钥。 如何在Metro上使用PBKDF2(如OpenSSL的PKCS5_PBKDF2_HMAC_SHA1调用)来派生密钥? 是否有基于WinRT构建的OpenSSL版本? (我读过它仅在Windows桌面平台上构建。)还是我应该使用其他解决方案?

顺便说一句,我可以从C#或C ++调用该函数,所以也可以。 任何建议将不胜感激!

编辑:我刚刚找到一个名为“ Rfc2898DeriveBytes”的.NET函数- 此处有详细信息。 如果我正确地阅读了该文档,它将执行与OpenSSL的PKCS5_PBKDF2_HMAC_SHA1调用相同的操作-正确吗?

编辑#2:不幸的是,看起来我最终无法在Windows 8.1 Metro应用程序中使用Rfc2898DeriveBytes,因为尽管Microsoft Rfc2898DeriveBytes文档说了什么,但构建时该API方法并不存在于Windows.Security.Cryptography名称空间中Windows 8.1应用程序。 还有什么我可以用的吗?

经过大量挖掘之后,我终于找到了这个链接 这是我最终在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
}

您可以使用Rfc2898DeriveBytes因为RFC实际上定义了PBKDF2 请注意,您需要确保使用相同的字符编码,盐大小和轮数以兼容。 通常,SHA1用作基础哈希函数(很好),但是请注意PBKDF2也可以使用其他哈希函数。 Rfc2898DeriveBytes SHA1用于HMAC功能。

请注意, Rfc2898DeriveBytes使用UTF-8。 Mickeysoft并未对此进行记录(即使在多次请求之后)。 如果不确定两种平台上的编码,都可以改用字节数组。 如果允许字符超出美国ASCII范围,则应特别注意这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM