简体   繁体   中英

Converting base64 string to X509 certifcate

I use PowerShell and thus far I have figured out how to take a X509 certificate flat file eg Cert.cer and concert it to a Base64 string for storage (eg in a database as a string etc.) and then convert it back again into a System.Security.Cryptography.X509Certificates.X509Certificate2 object

See my code below so far:

$CertifcateFileFullPath = "C:\temp\cert.cer"
$Cert = new-object security.cryptography.x509certificates.x509certificate2 -ArgumentList $CertifcateFileFullPath

$Obj2 = [System.Convert]::ToBase64String($Cert.RawData)

$Obj3 = [System.Security.Cryptography.X509Certificates.X509Certificate2]([System.Convert]::FromBase64String($Obj2))

Now the thing is I want to write the object $obj3 back to the file system as a flat file (eg Cert.cer) which is readable/usable as the original certificate.

If I use | out-file C:\\Temp2\\Cert.cer etc... I get a file which is much bigger than the original file and not readable (eg does not open as a normal cert file). I assume the encoding is the issue when writing out the object to the file system (I believe cert files are ASN 1 encode binary files)

The problem is that PewrShell is Unicode by default, while CryptoAPI decoder expects an ASCII encoding (where each character is encoded by using one byte). To achieve this, add -Encoding ASCII paramter to Out-File cmdlet.

BTW, there is no need to store certificate file in binary format. CryptoAPI supports certificate files in Base64 format. Since .NET relies on CryptoAPI, then there will not be comatibility problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM