Nagendra Ghimire
Nagendra Ghimire

Reputation: 86

Can I Convert X509 Certificate to string/byte to use later?

I have a situation where I need X509 certificate and have easy way to pass strings to it. Can I somehow convert the certificate to string and back to certificate?

I tried the following and everything works good except the certificate thumbprint is changed.

var originalCert = new X509Certificate2("C:\\cert.pfx", "password");
var byteCert = originalCert.GetRawCertData();
var stringCert = Encoding.Unicode.GetString(byteCert);
var convertedBytes = Encoding.Unicode.GetBytes(stringCert);
var convertedCert = new X509Certificate2(convertedBytes);

var equalThumbprints = originalCert.Thumbprint == convertedCert.Thumbprint; //this returns false

How can I get exact same certificate in this case?

shouldn't the certificate thumbprint be unique and be generated by certificate authority?

Upvotes: 1

Views: 8315

Answers (2)

Crypt32
Crypt32

Reputation: 13944

As suggested in comments, when you need to transfer byte array over text transport and to retain its integrity, you should use Base64 encoding:

String b64 = Convert.ToBase64String(originalCert.RawData);

and then when you need to restore byte array from string:

Byte[] rawData = Convert.FromBase64String(b64);

Base64 uses only ASCII table (in fact, only 7 bits) and is resistant to control characters, such as CR/LF/CRLF, spaces, tabs and other characters.

Upvotes: 3

MBB
MBB

Reputation: 1685

To answer the doubt on thumbprint here is the answer:

The thumbprint is dynamically generated using the SHA1 algorithm and does not physically exist in the certificate. Since the thumbprint is a unique value for the certificate, it is commonly used to find a particular certificate in a certificate store.

More here ...

To check whether you have the same certificate then use the Equals method.

 var equalcerts = originalCert.Equals(convertedCert);

UPDATE

The Equals method should not be used when comparing certificates for security purposes. Instead, use a hash of the RawData property, or the Thumbprint property.

So create your new certificate with RawData something like:

    var originalCert = new X509Certificate2("C:\\cert.pfx", "password");
    var byteCert = Convert.ToBase64String(originalCert.RawData);            
    var convertedCert = new X509Certificate2(Convert.FromBase64String(byteCert));            
    var equalThumbprints = originalCert.Thumbprint == convertedCert.Thumbprint; //true
    var equalcerts = originalCert.Equals(convertedCert); //true

Upvotes: 1

Related Questions