简体   繁体   中英

How to Get Certificate Modulus Using PowerShell?

Given a *.cer file, how can I retrieve the modulus of the certificate's public key, in byte format, using only PowerShell?

I was able to perform the following actions in PowerShell to retrieve the public key modulus of a signing certificate.

# Load the cert into an object.
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\Users\JaneDoe\Desktop\myCertificate.cer");

This gives us a certificate object that we can extract a lot of data from, such as the expiration date NotAfter , the thumbprint, and other info.

# Calculate the public key modulus, and convert to hex format.
$modulus = ($cert.PublicKey.Key.ExportParameters($false)).Modulus | %{ ("{0:x}" -f $_).PadLeft(2, "0") };

This will retrieve the modulus from the public key, and pipe the results into a hex formatter. You'll notice it also guarantees that each item in the collection will be padded with a leading zero if smaller than 0x10 16.

# Format display to look nice.
[Regex]::Replace(("0x00, 0x" + [string]::Join(", 0x", $modulus)), "(?<=^(.{102})+)", [Environment]::NewLine);

For my specific use case, I wanted each item in the collection to have a leading 0x for copy/paste purposes, and to have a newline after every 102 characters also for copy/paste purposes. You could ignore this last command if you don't need it.

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