كيف يمكنني استيراد المفتاح العمومي RSA من. NET في بينسل

StackOverflow https://stackoverflow.com/questions/497428

  •  20-08-2019
  •  | 
  •  

سؤال

ولدي برنامج NET و برنامج بورلاند Win32 والتي تحتاج إلى تمرير بعض المعلومات آمنة بشكل مشفر. خطة في الوقت الراهن هو أن يكون التطبيق. NET إنشاء زوج المفاتيح العام / الخاص، وتخزين المفتاح العمومي على القرص والحفاظ على مفتاح خاص في الذاكرة لطالما برنامج. NET قيد التشغيل.

والتطبيق بورلاند سيتم بعد قراءة المفتاح العمومي من القرص واستخدام مكتبة OpenSSL لتشفير البيانات مع المفتاح العمومي وكتابة تلك النتيجة إلى القرص.

وأخيرا فإن التطبيق. NET قراءة البيانات المشفرة وفك تشفير مع المفتاح الخاص.

ما هو أفضل وسيلة لتصدير المفتاح من .NET وفي المقابل استيراده إلى مكتبة OpenSSL؟

هل كانت مفيدة؟

المحلول

في البرنامج. NET إنشاء RSACryptoServiceProvider جديدة. تصدير المفتاح العمومي كما RSAParameters وكتابة القيم Modulus وExponent إلى القرص. مثل هذا:

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 مباشرة في C # مع OpenSSL.NET المجمع!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top