I wrote a .net program to generate .jks file and import root.crt in .jks file, I am using .net and bouncy castle library to do this. Below is my code:
`public void GenerateTrustStore(string rootCertificateFilePath, string trustStoreFilePath, string trustStorePassword, string alias) { try {
X509Certificate2 rootCertificateX509Certificate2 = new X509Certificate2(rootCertificateFilePath, trustStorePassword);
Org.BouncyCastle.X509.X509Certificate rootBouncyCastleCertificateX509 = DotNetUtilities.FromX509Certificate(rootCertificateX509Certificate2);
Pkcs12Store trustStore = new Pkcs12StoreBuilder().Build(); ;
trustStore.SetCertificateEntry(alias, new X509CertificateEntry(rootBouncyCastleCertificateX509));
using (FileStream trustStoreStream = File.Create(trustStoreFilePath))
{
trustStore.Save(trustStoreStream, trustStorePassword.ToCharArray(), new SecureRandom());
}
Console.WriteLine($"Root certificate imported successfully with alias '{alias}' into the truststore.");
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred while importing the root certificate: {ex.Message}");
}
}
`
However upon running keytool command: keytool -list -keystore truststore.jks -storepass abcdefghij, it says that it has 0 certificate entries:
But when I read truststore.jks file using .net program it does show that alias: 'caroot' is present in .jks file:
Program I wrote to read the .jks file and print its content:
`public void ReadTrustStore(string trustStoreFilePath, string trustStorePassword) { try { using (var trustStoreStream = File.OpenRead(trustStoreFilePath)) { Pkcs12Store trustStore = new Pkcs12Store(trustStoreStream, trustStorePassword.ToCharArray());
foreach (string alias in trustStore.Aliases)
{
if (trustStore.IsCertificateEntry(alias))
{
X509CertificateEntry certEntry = trustStore.GetCertificate(alias);
X509Certificate2 certificate = new X509Certificate2(certEntry.Certificate.GetEncoded());
Console.WriteLine($"Alias: {alias}");
Console.WriteLine($"Subject: {certificate.Subject}");
Console.WriteLine($"Issuer: {certificate.Issuer}");
Console.WriteLine($"Serial Number: {certificate.SerialNumber}");
Console.WriteLine($"Thumbprint: {certificate.Thumbprint}");
Console.WriteLine();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred while reading trust store: {ex.Message}");
}
}`
I need help to understand what is wrong I am doing and how can I fix it.
Note: I root.crt and root.key file is also generated through program and using them I can generate proper self signed certificates and .jks files if I execute keytool and openssl commands. But I want to prepare .jks and selfsigned certificates using C# and libraries(ex: bouncy castle).
I tried writing the program to generate .jks file and import root certificate in it. My program was able to create .jks file but upon running the keytool command to verify the certificate entry it says that it has 0 entries.

