繁体   English   中英

如何将.NET中的RSA公钥导入OpenSSL

[英]How do I import an RSA Public Key from .NET into OpenSSL

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

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

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

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

在.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

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

暂无
暂无

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

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