【问题标题】:How do I import an RSA Public Key from .NET into OpenSSL如何将 .NET 中的 RSA 公钥导入 OpenSSL
【发布时间】:2010-10-04 14:08:11
【问题描述】:

我有一个 .NET 程序和一个 Borland Win32 程序,它们需要传递一些加密安全信息。现在的计划是让 .NET 应用程序创建一个公钥/私钥对,将公钥存储在磁盘上,并在 .NET 程序运行期间将私钥保存在内存中。

然后 Borland 应用程序将从磁盘读取公钥并使用 OpenSSL 库使用公钥加密数据并将结果写入磁盘。

最后,.NET 应用程序将读取加密数据并使用私钥对其进行解密。

从 .NET 导出密钥然后将其导入 OpenSSL 库的最佳方法是什么?

【问题讨论】:

    标签: c# c++ openssl rsa


    【解决方案1】:

    在 .NET 程序中创建一个新的RSACryptoServiceProvider。将公钥导出为RSAParameters,并将ModulusExponent 值写入磁盘。像这样:

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096); //4096 bit key
    RSAParameters par = rsa.ExportParameters(false); // export the public key
    
    File.WriteAllBytes(@"C:\modulus.bin", par.Modulus); // write the modulus and the exponent to disk
    File.WriteAllBytes(@"C:\exponent.bin", par.Exponent);
    

    在 C++ 端,您需要从磁盘读取模数和指数值,将它们转换为 BIGNUM 值。这些值将被加载到 RSA 密钥中,然后您可以加密纯文本并将密文写入磁盘。像这样:

    RSA * key;
    
    unsigned char *modulus; 
    unsigned char *exp; 
    
    FILE * fp = fopen("c:\\modulus.bin", "rb"); // Read the modulus from disk
    modulus = new unsigned char[512];
    memset(modulus, 0, 512);
    fread(modulus, 512, 1, fp);
    fclose(fp);
    
    fp = fopen("c:\\exponent.bin", "rb"); // Read the exponent from disk
    exp = new unsigned char[3];
    memset(exp, 0, 3);
    fread(exp, 3, 1, fp);
    fclose(fp);
    
    BIGNUM * bn_mod = NULL;
    BIGNUM * bn_exp = NULL;
    
    bn_mod = BN_bin2bn(modulus, 512, NULL); // Convert both values to BIGNUM
    bn_exp = BN_bin2bn(exp, 3, NULL);
    
    key = RSA_new(); // Create a new RSA key
    key->n = bn_mod; // Assign in the values
    key->e = bn_exp;
    key->d = NULL;
    key->p = NULL;
    key->q = NULL;
    
    int maxSize = RSA_size(key); // Find the length of the cipher text
    
    cipher = new char[valid];
    memset(cipher, 0, valid);
    RSA_public_encrypt(strlen(plain), plain, cipher, key, RSA_PKCS1_PADDING); // Encrypt plaintext
    
    fp = fopen("C:\\cipher.bin", "wb"); // write ciphertext to disk
    fwrite(cipher, 512, 1, fp);
    fclose(fp);
    

    最后你可以毫无困难地获取密文并用 C# 解密它。

    byte[] cipher = File.ReadAllBytes(@"c:\cipher.bin"); // Read ciphertext from file
    byte[] plain = rsa.Decrypt(cipher, false); // Decrypt ciphertext
    
    Console.WriteLine(ASCIIEncoding.ASCII.GetString(plain)); // Decode and display plain text
    

    【讨论】:

    • 嗨,如何使用私钥在 C++ 中解密这个?谢谢
    【解决方案2】:

    您可以通过 OpenSSL.NET 包装器直接在 C# 中使用 OpenSSL!

    【讨论】:

    • 这是一个很棒的项目,我已经在一两个项目中使用过它。我很高兴看到开发人员已将其更新到 v1.0.0d,因为我上次检查 :)。
    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2021-10-08
    • 2012-12-11
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多