C#C
C#4y ago
BrunORC

❔ X509 Certificate from base64 string

I am trying to transform a base64 string I receive from a previous webrequest into a x509 certificate btu all I get is a
CryptographicException: Unable to decode certificate.
. The public key I got in base64 is this one:
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALOexE7WXZM/aq8S0umcDGptu7BHSF5KNq/O5PA1jP54HzNQuSDjyd/3Fp3SOWUr6RC8nQKfYqPRXkOVce73h50CAwEAAQ==
and I intend to later use it in an RSACryptoServiceProvider to encrypt some data. I have the same code in Java working properly and can't understand what might be wrong in the C# version.

Java code from public key string into X509 cert.
final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString.getBytes()));


C# version 1 from public key string into X509 cert with error:
byte[] publicKeyBytes = Convert.FromBase64String(base64publicKey);
X509Certificate2 cert = new X509Certificate2(publicKeyBytes);
return cert;


C# version 2 from public key string into X509 cert with error:
byte[] publicKeyBytes = Convert.FromBase64String(base64publicKey);
X509Certificate2 cert = null;
string certFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
try {
    File.WriteAllBytes(certFile, publicKeyBytes);
    string certText = File.ReadAllText(certFile);
    cert = new X509Certificate2(certFile);
} finally {
    File.Delete(certFile);
}
return cert;


I have tried other options, all of which failed so far.
Was this page helpful?