代码之家  ›  专栏  ›  技术社区  ›  Mykroft

如何从导入RSA公钥。NET转换为OpenSSL

  •  3
  • Mykroft  · 技术社区  · 17 年前

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

    最后是。NET应用程序将读取加密数据并用私钥解密。

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

    2 回复  |  直到 15 年前
        1
  •  5
  •   Mykroft    17 年前

    在。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);
    

    BIGNUM

    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);
    

    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
    
        2
  •  0
  •   fried    16 年前