[Certificate Fundamentals Part 3] Trying It with openssl and PowerShell: Keys, Encryption, Hashes, Signatures, and Self-Signed Certificates

Certificate Fundamentals Part 3 Trying It with openssl and PowerShell: Keys, Encryption, Hashes, Signatures, and Self-Signed Certificates Certificates and PKI

“When I type openssl genrsa, I get some kind of warning…”
“Windows doesn’t have openssl. How can I try this?”

You typed an openssl command exactly as shown in a guide you found online, and an unfamiliar warning appeared. Has that happened to you? OpenSSL changed its syntax significantly in 3.0, and if you follow an old guide, you may get warnings or the command may not work at all.

In Part 2, we looked at the cryptographic building blocks: symmetric encryption, public key encryption, key exchange, hashes, and signatures. Part 3 is a hands-on part. On Linux and Mac we use OpenSSL 3, and on Windows we use the built-in PowerShell and certutil, to go from creating keys all the way to creating a self-signed certificate.

▶ This part is also available as a YouTube video (about 18 min) (it is also embedded at the end of this article).

Diagram showing the overall flow of this part: genpkey creates the private key rsa.key, pkey -pubout extracts the public key rsa.pub, and for test.txt you encrypt with the public key, decrypt with the private key, sign with the private key, and verify with the public key

The figure above shows how the files created in this part relate to the commands used. The private key is used for “decrypt” and “sign,” and the public key is used for “encrypt” and “verify.” Keep this in mind as you read.


OpenSSL 3 basics

First, check the version of OpenSSL you have.

$ openssl version
OpenSSL 3.5.5 27 Jan 2026 (Library: OpenSSL 3.5.5 27 Jan 2026)
$ openssl version -d          # Location of the configuration file (openssl.cnf)
OPENSSLDIR: "/usr/lib/ssl"

OpenSSL 3 changed the syntax of several commands. When you read an old guide, keep this mapping in mind to avoid confusion.

PurposeOld syntaxOpenSSL 3 syntaxNotes
Creating keysgenrsa, ecparam -genkeygenpkeyThe same syntax for every algorithm. genrsa still works, but its output changed to PKCS#8 format
Displaying and converting keysrsa, ecpkeyIf you need the old format, use rsa -traditional
Encrypting and signing with a public keyrsautlpkeyutlrsautl was deprecated in 3.0. Running it prints a warning
Leaving a key unencrypted-nodes-noenc-nodes is deprecated (it still works)
Old algorithmsUsable as is (MD4, RC4, and so on)Needs -provider legacyTo read an old PFX, use pkcs12 -legacy
Adding featuresEngines (-engine)Providers (-provider)Engines were removed in 4.0

As of September 2026, the versions still supported are 3.5 (LTS, until April 2030), 3.6, 4.0, and others. Support for 1.1.1 ended in September 2023, and support for 3.0 ended in September 2026. Some commands are not available in the openssl of older operating systems.

Windows does not include openssl by default, so this article also gives the equivalent methods with PowerShell and certutil.


Creating keys (genpkey)

In OpenSSL 3, you create keys with genpkey. You choose the algorithm with -algorithm, and the syntax is common to all of them.

$ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa.key
....+.....+++++(Progress display of key generation; omitted)
$ openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out ec.key
$ openssl genpkey -algorithm ED25519 -out ed.key
$ openssl pkey -in rsa.key -pubout -out rsa.pub     # Extract the public key (the same for ec and ed)

$ openssl pkey -in ec.key -text -noout
Private-Key: (256 bit)
priv:
    0b:8c:d7:5c:22:5b:8c:c5:72:c9:2b:cd:24:b3:98:(omitted)
pub:
    04:80:6a:f4:c5:c6:94:0b:ba:02:0f:a6:95:b4:ee:(omitted)
ASN1 OID: prime256v1
NIST CURVE: P-256
  • For RSA, rsa_keygen_bits sets the key length (the default is 2048); for EC, ec_paramgen_curve sets the curve. As we saw in Part 2, for new keys use RSA 3072 or larger, or P-256 or larger
  • Keys are saved in PEM format (text that starts with -----BEGIN PRIVATE KEY-----) (formats are covered in detail in Part 4)
  • To protect a key with a passphrase, add -aes256. A key that a server reads automatically often has no passphrase, and is instead protected by file permissions (600) (with OpenSSL 3.5, the file was created with 600)
  • You may hand out a public key freely, but the rule is do not make copies of the private key

Windows has no standard command that creates a file containing only a key. Keys are created inside the certificate store, together with a certificate (with New-SelfSignedCertificate, introduced later, or certreq in Part 6).


Encrypting and decrypting with a public key (pkeyutl)

In Part 2, we wrote that “public key encryption cannot handle large data.” Let’s test whether that is true.

$ echo "hello world" > test.txt
$ openssl pkeyutl -encrypt -pubin -inkey rsa.pub -pkeyopt rsa_padding_mode:oaep \
    -pkeyopt rsa_oaep_md:sha256 -in test.txt -out test.enc
$ ls -l test.enc                     # 384 bytes because the key is 3072 bits
-rw-rw-r-- 1 user user 384 Sep 26 10:07 test.enc

$ openssl pkeyutl -decrypt -inkey rsa.key -pkeyopt rsa_padding_mode:oaep \
    -pkeyopt rsa_oaep_md:sha256 -in test.enc
hello world

$ openssl pkeyutl -encrypt -pubin -inkey rsa.pub -pkeyopt rsa_padding_mode:oaep \
    -pkeyopt rsa_oaep_md:sha256 -in big.bin -out big.enc        # A 1,000-byte file
Public Key operation error
…:data too large for key size:…(omitted)
  • pkeyutl is the successor to rsautl. Specify OAEP for the padding (if you do not, the old PKCS#1 v1.5 is used)
  • RSA can directly encrypt only data shorter than the key length, and a large file fails with data too large for key size
  • With an elliptic curve key, -encrypt itself is not possible (it is used for key exchange and signatures)

So how do you encrypt a large file? Windows’ Protect-CmsMessage shows the answer.

PS> $cert = New-SelfSignedCertificate -Type DocumentEncryptionCert -Subject "CN=cms-test" -CertStoreLocation Cert:\CurrentUser\My
PS> Protect-CmsMessage -To $cert -Path .\test.txt -OutFile .\test.cms
PS> Unprotect-CmsMessage -Path .\test.cms
hello world
Diagram of CMS hybrid encryption: the body, which may be large, is encrypted with a one-time AES key, that AES key is encrypted with the public key (RSA-OAEP) of the peer's certificate, and both are bundled into test.cms

Protect-CmsMessage uses the CMS format, which encrypts the content with AES and encrypts that AES key with the certificate’s public key (RSA-OAEP). RSA directly encrypts only the short key, so large data can be handled too. This is the same hybrid idea as TLS, which we saw in Part 2.


Calculating hashes (dgst / Get-FileHash / certutil)

Let’s calculate the hash value of the same file in three ways.

$ openssl dgst -sha256 test.txt
SHA2-256(test.txt)= a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
$ openssl dgst -sha3-256 test.txt
SHA3-256(test.txt)= a8009a7a528d87778c356da3a55d964719e818666a04e4f960c9e2439e35f138
$ sha256sum test.txt
a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447  test.txt
PS> Get-FileHash .\test.txt | Format-List
Algorithm : SHA256
Hash      : A948904F2F0F479B8F8197694B30184B0D2ED1C1CD2A1EC0FB85D299A192A447
Path      : C:\work\test.txt

PS> certutil -hashfile .\test.txt SHA256
SHA256 hash of .\test.txt:
a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
CertUtil: -hashfile command completed successfully.
  • OpenSSL 3 displays the result in the form SHA2-256(filename)=. With -r, the layout is the same as sha256sum
  • The default for Get-FileHash is SHA256, and -Algorithm lets you choose SHA384, SHA512, and others (SHA-3 cannot be chosen)
  • If you omit the algorithm, certutil -hashfile uses SHA1 (the first line becomes “SHA1 hash”), so always specify it. The output above is shown in the English form. The Japanese edition of Windows 11 (24H2) shows “SHA256 ハッシュ (対象 .\test.txt):” and “CertUtil: -hashfile コマンドは正常に完了しました。” (the same two lines in Japanese), and Windows Server 2016 shows “(ファイル .\test.txt)” in place of “(対象 .\test.txt)”

When the values do not match between Linux and Windows, suspect a difference in line endings (LF versus CRLF) or a BOM. Even if the files look the same, the hash value changes if the byte sequence differs (the example above uses files with the same bytes). For example, if you create the file with PowerShell’s Set-Content .\test.txt 'hello world', the line ending becomes CRLF, and SHA256 becomes a different value, 572a95fee9c0f320030789e4883707affe12482fbb1ea04b3ea8267c87a890fb.


Signing and verifying (dgst -sign / -verify)

Next is signing. We confirm that verification fails for a file with just one character rewritten.

$ openssl dgst -sha256 -sign rsa.key -out test.sig test.txt
$ openssl dgst -sha256 -verify rsa.pub -signature test.sig test.txt
Verified OK

$ sed 's/world/World/' test.txt > bad.txt          # A file with just one character changed
$ openssl dgst -sha256 -verify rsa.pub -signature test.sig bad.txt
(Lines with error details omitted)
Verification failure

$ openssl pkeyutl -sign -inkey ed.key -rawin -in test.txt -out ed.sig          # Ed25519
$ openssl pkeyutl -verify -pubin -inkey ed.pub -rawin -in test.txt -sigfile ed.sig
Signature Verified Successfully
  • dgst -sign calculates the hash value and signs it with the private key. Verification needs only the public key, so anyone can verify. If even one character differs, you get Verification failure
  • To use RSA-PSS, add -sigopt rsa_padding_mode:pss to both signing and verification
  • Ed25519 calculates the hash internally, so you sign by adding -rawin to pkeyutl

On Windows, you can confirm the same thing with the code signing of a script.

PS> Set-Content .\test.ps1 'Write-Output "hello"'
PS> $cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject "CN=Test Code Signing" -CertStoreLocation Cert:\CurrentUser\My
PS> Set-AuthenticodeSignature -FilePath .\test.ps1 -Certificate $cert
PS> (Get-AuthenticodeSignature .\test.ps1).Status
UnknownError          # The signature was added, but the issuer (self-signed) is not trusted
PS> (Get-Content .\test.ps1) -replace 'hello','HELLO' | Set-Content .\test.ps1   # Rewrite the content
PS> (Get-AuthenticodeSignature .\test.ps1).Status
HashMismatch          # Tampering detected
PS> Remove-Item "Cert:\CurrentUser\My\$($cert.Thumbprint)"   # Delete the certificate when you are done

UnknownError only means the issuer is not trusted. If you make the certificate trusted, it becomes Valid. And rewriting just one word in the content gives HashMismatch, which means tampering was detected.

  • The signature is added at the end of the file as comments from # SIG # Begin signature block to # SIG # End signature block
  • If you use Add-Content to add a line after the signature block, the status is NotSigned (no signature) rather than HashMismatch, because a signature block that is not at the end is not treated as a signature. In either case, the script does not run under an execution policy that requires signatures (such as AllSigned)
  • These are results confirmed with Windows PowerShell 5.1 on Windows Server 2016 and Windows 11 (24H2)

Trying key exchange and HMAC

The key exchange (X25519) explained with the paint analogy in Part 2 can also be tried for real.

$ openssl genpkey -algorithm X25519 -out alice.key
$ openssl pkey -in alice.key -pubout -out alice.pub
$ openssl genpkey -algorithm X25519 -out bob.key
$ openssl pkey -in bob.key -pubout -out bob.pub

$ openssl pkeyutl -derive -inkey alice.key -peerkey bob.pub | xxd -p -c 32
1e25233c0216702040dc433f8efa24d7dda654f72dae40db1bc1f91e04713442
$ openssl pkeyutl -derive -inkey bob.key -peerkey alice.pub | xxd -p -c 32
1e25233c0216702040dc433f8efa24d7dda654f72dae40db1bc1f91e04713442
Diagram showing that alice and bob each create an X25519 key pair and exchange only the public keys, and that alice.key + bob.pub and bob.key + alice.pub give the same 32-byte value with pkeyutl -derive

The two sides each create a key pair and exchange only the public keys. Calculating from your own private key and the other side’s public key gave the same 32-byte value on both sides. In real TLS, this value is processed into keys for communication with HKDF (key derivation that uses HMAC).

Let’s calculate an HMAC too.

$ openssl dgst -sha256 -hmac "secret" test.txt          # Calculate an HMAC with the key "secret"
HMAC-SHA2-256(test.txt)= 6dc8750717249a7f056dc06f26ff617ae5a7cf18980d4f179657eb93617a553a
PS> $hmac = [System.Security.Cryptography.HMACSHA256]::new([Text.Encoding]::UTF8.GetBytes("secret"))
PS> $mac = $hmac.ComputeHash([IO.File]::ReadAllBytes("$PWD\test.txt"))
PS> -join ($mac | ForEach-Object { $_.ToString("x2") })
6dc8750717249a7f056dc06f26ff617ae5a7cf18980d4f179657eb93617a553a

With HMAC, anyone who calculates with the same key and data gets the same value, and a different key gives a completely different value. Windows has no standard command for trying key exchange, but HMAC can be calculated with a .NET class, and for a file with the same bytes it gives the same value as openssl.


Creating a self-signed certificate (req -x509 / New-SelfSignedCertificate)

Finally, let’s create a certificate.

$ openssl req -x509 -newkey EC -pkeyopt ec_paramgen_curve:P-256 -noenc \
    -keyout server.key -out server.crt -days 30 -subj "/CN=test.example.com" \
    -addext "subjectAltName=DNS:test.example.com,DNS:www.example.com" \
    -addext "basicConstraints=critical,CA:FALSE" -addext "extendedKeyUsage=serverAuth"

$ openssl x509 -in server.crt -noout -subject -issuer -dates -ext subjectAltName
subject=CN=test.example.com
issuer=CN=test.example.com
notBefore=Sep 26 01:07:27 2026 GMT
notAfter=Oct 26 01:07:27 2026 GMT
X509v3 Subject Alternative Name:
    DNS:test.example.com, DNS:www.example.com
PS> New-SelfSignedCertificate -DnsName test.example.com,www.example.com -CertStoreLocation Cert:\CurrentUser\My `
      -KeyAlgorithm ECDSA_nistP256 -CurveExport CurveName -NotAfter (Get-Date).AddDays(30)

   PSParentPath: Microsoft.PowerShell.Security\Certificate::CurrentUser\My

Thumbprint                                Subject
----------                                -------
(40 hexadecimal digits)                   CN=test.example.com
Diagram showing that in the self-signed certificate server.crt the issuer and subject are the same, that it has a SAN, basicConstraints CA:FALSE, and a signature by its own private key, and that its structure is the same as a root certificate
  • A self-signed certificate is one in which the issuer and the subject are the same, signed by its own private key. Its structure is the same as a root certificate (Part 5)
  • If you do not specify them with -addext, OpenSSL’s default configuration creates it as CA:TRUE (a CA certificate). For a server certificate, set CA:FALSE and the SAN explicitly. What is used for hostname verification is the SAN, not the CN (Part 4)
  • New-SelfSignedCertificate puts the values of -DnsName in the SAN and uses the first name as the Subject. The key is created in the certificate store, and the default validity period is one year. To make files, use Export-Certificate and Export-PfxCertificate

Use self-signed certificates only for testing and temporary purposes. As we saw in Part 1, if you get used to warnings about untrusted certificates, you will overlook the warnings for real attacks as well.


Summary of the Windows approach

What you want to doLinux and Mac (openssl)Windows built-in (PowerShell and certutil)Notes
Create a key pairopenssl genpkeyNew-SelfSignedCertificate, certreq -newCreated inside the certificate store
Encrypt and decrypt with a public keyopenssl pkeyutl -encrypt / -decryptProtect-CmsMessage / Unprotect-CmsMessageNeeds a document encryption certificate
Hashopenssl dgst -sha256, sha256sumGet-FileHash, certutil -hashfile file SHA256Get-FileHash does not support SHA-3
HMACopenssl dgst -hmac, openssl macThe .NET HMACSHA256 classThere is no dedicated cmdlet
Sign and verifyopenssl dgst -sign / -verifySet-AuthenticodeSignature / Get-AuthenticodeSignatureTargets scripts and executables
Self-signed certificateopenssl req -x509New-SelfSignedCertificateThe default validity period is one year
View the contents of a certificateopenssl x509 -text -nooutcertutil -dump, [X509Certificate2]Covered in Part 4
Random numbersopenssl rand -hex 16.NET RandomNumberGenerator, Get-SecureRandom (PowerShell 7.4 and later)Get-Random is not cryptographic

This assumes Windows PowerShell 5.1, which comes with Windows (Get-SecureRandom is available only in PowerShell 7.4 and later, which is installed separately). If you use the openssl.exe bundled with Git for Windows, you can use the same commands as on Linux, but check the version with openssl version.


Think about it

  1. You tried to encrypt a large file with an RSA public key and it failed. How should you combine techniques to send a large file safely using the other party’s public key?
  2. When a signature verification succeeds, one thing you have confirmed is that “it has not been tampered with.” What is the other? And how do you confirm that the public key really belongs to the other party?
  3. Are certificates made with New-SelfSignedCertificate or openssl req -x509 being used in production at your workplace? Check the expiration, the SAN, and whether it is CA:TRUE.

Hint: The CMS in this article (a combination of AES and RSA), the issuer and subject of a self-signed certificate, and “the role of certificates” in Part 1 are good clues.


Summary

  • In OpenSSL 3, use genpkey, pkey, and pkeyutl. rsautl and -nodes are deprecated
  • The private key is used for decryption and signing, and the public key for encryption and verification
  • RSA can directly encrypt only short data. For large data, combine it with AES (CMS and TLS)
  • With certutil -hashfile, always specify the algorithm. When values do not match, suspect line endings
  • For a self-signed certificate, set CA:FALSE and the SAN explicitly, and use it only for testing

Next time, we read the contents (X.509) of the certificate created here, down to the SAN, extensions, and file formats.


Watch the video

This part is also explained in a YouTube video (about 18 min).

All parts of the series are in the Certificate Fundamentals playlist on YouTube.

The Certificate Fundamentals series (11 parts)

All 11 parts with a reading guide: Certificate Fundamentals

  1. Why Do We Need Certificates?
  2. Cryptography basics
  3. Trying it with openssl and PowerShell (this article)
  4. Inside an X.509 certificate
  5. PKI and how trust works
  6. Certificate types and issuance
  7. How TLS works
  8. Lifecycle and automation
  9. Private PKI and the cloud
  10. Certificate troubleshooting
  11. Certificate design exercises

This series is the English edition of 【証明書入門】, originally written in Japanese.

コメント

Copied title and URL