在不使用CLR的情况下等效于C ++中的Rfc2898DeriveBytes

时间:2019-03-06 05:10:17

标签: c++ cryptography pbkdf2

在不使用CLR的情况下,C ++中Rfc2898DeriveBytes的替代方案是什么。 C#示例在下面共享。

string clearText="text to sign";
string EncryptionKey = "secret";
byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x48, 0x71, 0x21, 0x6d, 0x21, 0x4c, 0x61, 0x62, 0x72, 0x62, 0x61, 0x62, 0x72 });
    encryptor.Key = pdb.GetBytes(32);
    encryptor.IV = pdb.GetBytes(16);
    using (MemoryStream ms = new MemoryStream())
    {
        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
        {
            cs.Write(clearBytes, 0, clearBytes.Length);
            cs.Close();
        }
        clearText = Convert.ToBase64String(ms.ToArray());
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在OpenSSL中使用PKCS5_PBKDF2_HMAC

这两个函数都是PBKDF2函数,可以互换使用。

更新

这是为您提供的示例代码,用于在C#OpenSSL中生成相似的密钥。

C#一侧:

public static void Main()
{
    string EncryptionKey = "secret";
    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x48, 0x71, 0x21, 0x6d, 0x21, 0x4c, 0x61, 0x62, 0x72, 0x62, 0x61, 0x62, 0x72 }, 1000);
    Console.WriteLine("[{0}]", string.Join(", ", pdb.GetBytes(32)));
    Console.WriteLine("[{0}]", string.Join(", ", pdb.GetBytes(16)));
}

OpenSSL一侧:

#include <openssl/evp.h>
#include <string.h>
#include <stdlib.h>

int main(){
        char secret[] = "secret";
        unsigned char buf[48] = {0,};
        int size = 48;
        unsigned char salt[] = { 0x48, 0x71, 0x21, 0x6d, 0x21, 0x4c, 0x61, 0x62, 0x72, 0x62, 0x61, 0x62, 0x72 };
        PKCS5_PBKDF2_HMAC(secret, strlen(secret), salt, sizeof(salt), 1000, EVP_sha1(), size, buf);
        for (int i = 0; i < size; i++)
                printf("%d ", buf[i]);
        return 0;
}

请记住,在这些代码中,迭代只有1,000次,至少要使用100,000甚至1,000,000。