【问题标题】:Create openssl dhparam in C# with BouncyCastle. How?使用 BouncyCastle 在 C# 中创建 openssl dhparam。如何?
【发布时间】:2021-12-24 15:50:19
【问题描述】:

在 C# 中找到 BouncyCastle 的文档非常困难。

这个link points to a solution 是用 Java 编写的。我似乎无法将其转换为 C#。它可以工作,但不能在 C# 中使用。

谁能帮我把代码转换成 C# BouncyCastle?

Java 代码:

import java.math.BigInteger;
import java.security.SecureRandom;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.crypto.generators.DHParametersGenerator;
import org.bouncycastle.crypto.params.DHParameters;
import org.bouncycastle.util.encoders.Base64;

public class OpenSSLDHParamClone
{

    public static void main(String[] args) throws Exception
    {
        DHParametersGenerator generator = new DHParametersGenerator();
        generator.init(1024, 80, new SecureRandom());
        DHParameters params = generator.generateParameters();
        // Generator G is set as random in params, but it has to be 2 to conform to openssl
        DHParameters realParams = new DHParameters(params.getP(), BigInteger.valueOf(2));
        ASN1EncodableVector seq = new ASN1EncodableVector();
        seq.add(new DERInteger(realParams.getP()));
        seq.add(new DERInteger(realParams.getG()));
        byte [] derEncoded = new DERSequence(seq).getDEREncoded();
        System.out.println("-----BEGIN DH PARAMETERS-----");
        String b64Encoded = new String(Base64.encode(derEncoded), "US-ASCII");
        while (b64Encoded.length() > 0) {
            int subStringLength = Math.min(64, b64Encoded.length());
            System.out.println(b64Encoded.substring(0, subStringLength));
            b64Encoded = b64Encoded.substring(subStringLength);
        }
        System.out.println("-----END DH PARAMETERS-----");
    }
}

本质上它需要和 OpenSSL 命令做同样的事情:

openssl dhparam -out dhparam.pem 2048

【问题讨论】:

  • 您几乎可以 1:1 移植代码。 BC/C# 命名与 BC/Java 命名基本相同,区别主要在于大小写或使用 IntelliSense 可以轻松识别。

标签: java c# bouncycastle


【解决方案1】:

下面是 C# .NET Core 中使用 BouncyCastle DLL 库的工作示例。

只需创建一个 .NET Core 控制台项目,添加 BouncyCastle DLL 引用并运行。

// .NET Imports
using System.Text.RegularExpressions;

// BouncyCastle for .NET Imports
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;

class Program
{
    static void Main(string[] args)
    {
        GeneratePkcs3(RootLenght.RootLength1024);

    }

    /// <summary>
    ///     Generates dhparam in PKCS#3 format defined by RFC 2631.
    ///     
    ///     OpenSSL equivalent command:
    ///     $ openssl dhparam -out dhparam.pem 1024
    ///     
    ///     The minimum root length recommended for NGINX dhparam is 2048bit
    ///     
    ///     *******************************************
    ///     Notes / Handy references:
    ///     http://www.keylength.com/en/compare/
    ///     
    /// </summary>
    static void GeneratePkcs3(RootLenght rootLength)
    {
        string dhparam = null;

        try
        {

            Console.WriteLine("Please wait. Generating DH parameter...");
            Console.WriteLine("Choosing Root Length beyond 1024bit, may considerably increase the wait...");
            Console.WriteLine("");

            const int DefaultPrimeProbability = 30;

            DHParametersGenerator generator = new DHParametersGenerator();
            generator.Init((int)rootLength, DefaultPrimeProbability, new SecureRandom());
            DHParameters parameters = generator.GenerateParameters();

            DHParameters realParams = new DHParameters(parameters.P, BigInteger.ValueOf(2));

            Asn1EncodableVector seq = new Asn1EncodableVector();
            seq.Add(new DerInteger(realParams.P));
            seq.Add(new DerInteger(realParams.G));
            byte[] derEncoded = new DerSequence(seq).GetDerEncoded();
            dhparam = Convert.ToBase64String(derEncoded);

            Console.WriteLine("-----BEGIN DH PARAMETERS-----");
            Console.WriteLine(SpliceText(dhparam, 64));
            Console.WriteLine("-----END DH PARAMETERS-----");

            Console.WriteLine("");
            Console.WriteLine("");

            Console.WriteLine($"{(int)rootLength}bit DH parameter succesfully generated.");

            Console.ReadKey();

        }
        catch (Exception ex)
        {
            // Note: handles errors on the page. Redirect to error page.
            //ErrorHandler(ex);
            Console.WriteLine(ex.Message);
        }
    }

    private enum RootLenght
    {
        RootLength1024 = 1024, // Test ONLY!
        RootLength2048 = 2048,
        RootLength3072 = 3072,
        RootLength4096 = 4096,
    }

    public static string SpliceText(string text, int lineLength)
    {
        return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
    }

}

【讨论】:

    猜你喜欢
    • 2019-10-08
    • 2021-06-06
    • 2021-09-19
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    相关资源
    最近更新 更多