问题
I have an object of System.Security.Cryptography.X509Certificates.X509Certificate2. I want to construct an instance of Pkcs12Store (Org.BouncyCastle.Pkcs) using this object.
I tried:
Approach 1:
public Pkcs12Store GetPkcs12Store(X509Certificate2 cert, string password)
{
byte[] rawdata = cert.RawData;
MemoryStream memStream = new MemoryStream(rawdata);
Pkcs12Store pk12;
pk12 = new Pkcs12Store(memStream, password.ToCharArray());
return pk12;
}
In this approach, I am getting the exception:
Unable to cast object of type 'Org.BouncyCastle.Asn1.DerSequence' to type 'Org.BouncyCastle.Asn1.DerInteger'.
Approach 2:
I tried:
public static Pkcs12Store GetPkcs12Store(X509Certificate2 cert, string password)
{
Org.BouncyCastle.X509.X509Certificate bcCert;
bcCert = DotNetUtilities.FromX509Certificate(cert);
pk12 = new Pkcs12StoreBuilder().Build();
X509CertificateEntry certEntry = new X509CertificateEntry(bcCert);
pk12.SetCertificateEntry(bcCert.SubjectDN.ToString(), certEntry);
AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(bcCert.GetPublicKey());
return pk12;
}
In this approach, I do not get the exception I was getting earlier, but then the Pkcs12Store returns false for IsKeyEntry.
string alias = null;
foreach (object a in pk12.Aliases)
{
alias = ((string)a);
if (pk12.IsKeyEntry(alias))
{
break;
}
}
ICipherParameters pk = pk12.GetKey(alias).Key;
So the code fails at the line ICipherParameters pk = pk12.GetKey(alias).Key;
Approach 3:
public static Pkcs12Store GetPkcs12Store(X509Certificate2 cert, string password)
{
Pkcs12Store pk12;
byte[] rawdata;
Org.BouncyCastle.X509.X509Certificate bcCert;
rawdata = cert.Export(X509ContentType.Pfx, password);
MemoryStream memStream = new MemoryStream(rawdata);
pk12 = new Pkcs12Store(memStream, password.ToCharArray());
return pk12;
}
In this approach, I get the error:
Key not valid for use in specified state.
at the statement cert.Export...
来源:https://stackoverflow.com/questions/60918431/how-to-construct-pkcs12store-from-x509certificate2