I was sent some code as an example of how to work with their system.
Unfortunately, they don't have an example in C# but was able to send me
code in java.

It looks like this:

synchronized private static final X509Certificate genCert(
        String pCerPath) throws Exception {
        Security
            .addProvider(new
org.bouncycastle.jce.provider.BouncyCastleProvider());
        CertificateFactory certificatefactory;

        X509Certificate cert;

        certificatefactory = CertificateFactory.getInstance("X.509", "BC");

        InputStream bais = new FileInputStream(pCerPath);

        cert =
            (X509Certificate) certificatefactory.generateCertificate(bais);

        return cert;
    }


Unfortunately, it isn't 1:1, so I came out with something like this:

static X509Certificate GenerateCertificate(string certificatePath)
{
    X509Certificate certificate;
    X509CertificateParser certificateParser = new X509CertificateParser();
    ISignatureFactory signatureFactory;
    using (var fileStream = new FileStream(certificatePath, FileMode.Open))
    {
        certificate = certificateParser.ReadCertificate(fileStream);
        var keyPair = GenerateRsaKeyPair(2048);
        signatureFactory = new Asn1SignatureFactory(
            PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(),
            keyPair.Private
        );
    }

    var certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.SetIssuerDN(certificate.IssuerDN);
    certificateGenerator.SetSubjectDN(certificate.SubjectDN);
    var diff = Convert.ToInt64((DateTime.Now - new DateTime(2022, 01,
26, 22, 25, 0)).TotalSeconds);
    
certificateGenerator.SetSerialNumber(certificate.SerialNumber.Add(BigInteger.ValueOf(diff)));
    certificateGenerator.SetNotAfter(DateTime.UtcNow.AddYears(2));
    certificateGenerator.SetNotBefore(DateTime.UtcNow);
    certificateGenerator.SetPublicKey(certificate.GetPublicKey());
    return certificateGenerator.Generate(signatureFactory);
}


The Asn1SignatureFactory takes in a privateKey, which I generate.  I get
a cert fine, however, when I look at other people's code with self certs,
they tend to use their self certs subject here.  I was kind of wondering,
what is the proper way to do this?  Also, serialNumber, I just tacked on
the difference between when I started to now, since I don't have a
persistent incrementor, I think a lot of the examples use random number.

Best regards,
Talon

Reply via email to