Certificates
A certificate ties a public key to a name and a time of validity. HTTPS sites, signed programs and services that must prove who they are all use them. This lesson makes a self-signed X.509 certificate, reads what it contains, exports it with and without the private key, signs with it, and shows why a computer does not trust it.
What you will learn#
- what a certificate is: public key, subject, issuer, validity, thumbprint,
- making a self-signed certificate (
CertificateRequest,CreateSelfSigned), - extensions such as basic constraints,
- exporting: PFX (with the private key and a password) and PEM / .cer (public only),
- signing with the private key and verifying with the public certificate,
- trust and the chain.
The tutorial Digital signatures signed data with a bare key pair. A certificate adds the answer to "whose key is this?".
The program#
# certificates - a self-signed X.509 certificate, what it contains, export with and without the private key, and signing with it
load "dotnet.ring"
using {
"System"
"System.Text"
"System.Security.Cryptography"
"System.Security.Cryptography.X509Certificates"
}
func main
oUtf8 = new UTF8Encoding()
# A certificate is a public key together with a name (the SUBJECT), a time of validity, and a signature of whoever vouches for it (the
# ISSUER). Web sites use certificates for HTTPS, programs use them to sign code and documents, and services use them to prove who they
# are. Here we make a SELF-SIGNED certificate: the subject and the issuer are the same, so nobody but us vouches for it. That is good
# for tests and for talking between your own programs, but a browser or another computer does not trust it.
# 1. A key pair (RSA, 2048 bits), then a request that says who the certificate is for
oRsa = new RSA().Create(2048)
oName = new X500DistinguishedName("CN=Demo Server, O=RingDotNet, C=EG")
oSha = new HashAlgorithmName().SHA256
oPadding = new RSASignaturePadding().Pkcs1
oRequest = (new CertificateRequest).@New([ :subjectName = oName, :key = oRsa, :hashAlgorithm = oSha, :padding = oPadding ])
# Extensions say what the certificate may be used for. This one is a plain server certificate (not a CA that signs others).
oBasic = new X509BasicConstraintsExtension().@New([ :certificateAuthority = False, :hasPathLengthConstraint = False, :pathLengthConstraint = 0, :critical = True ])
oRequest.CertificateExtensions.Add(oBasic)
# Create it: valid from yesterday (a margin for computers whose clocks differ) until a year from today
oNow = new DateTimeOffset().UtcNow
oCertificate = oRequest.CreateSelfSigned(oNow.AddDays(-1),oNow.AddDays(365))
? "1. subject: " + oCertificate.Subject
? " issuer: " + oCertificate.Issuer + " (the same: self-signed)"
? " thumbprint: " + len(oCertificate.Thumbprint) + " hex characters (the SHA-1 of the certificate: it identifies it)"
? " has a private key: " + oCertificate.HasPrivateKey
? " valid for " + floor(oCertificate.NotAfter.Subtract(oCertificate.NotBefore).TotalDays + 0.5) + " days, and it is valid now: " + isValidNow(oCertificate)
# 2. Export WITH the private key as PFX (a file with a password), and load it again. A PFX is the secret: protect it like a password.
cPfx = oCertificate.Export([ :contentType = "Pfx", :password = "correct horse battery" ])
oLoaded = new X509Certificate2().@New([ :rawData = cPfx, :password = "correct horse battery" ])
? nl + "2. the PFX is bigger than 1000 bytes: " + (len(cPfx) > 1000) + "; loaded again it has the same thumbprint: " + (oLoaded.Thumbprint = oCertificate.Thumbprint) + " and a private key: " + oLoaded.HasPrivateKey
lWrong = False
try
new X509Certificate2().@New([ :rawData = cPfx, :password = "wrong password" ])
catch
lWrong = True
done
? " a wrong password is refused: " + lWrong
# 3. Export the PUBLIC part only (a .cer or PEM file): this is what you give to others. It has no private key.
cPem = oCertificate.ExportCertificatePem()
? nl + "3. the public certificate as PEM starts with: " + left(substr(cPem,char(13),""),27)
cCer = oCertificate.Export("Cert")
oPublic = new X509Certificate2().@New([ :rawData = cCer ])
? " loaded from the public export: same thumbprint " + (oPublic.Thumbprint = oCertificate.Thumbprint) + ", private key: " + oPublic.HasPrivateKey
# 4. Signing: the owner signs with the private key, anybody with the public certificate verifies
cMessage = oUtf8.GetBytes("Invoice 2024-001: 1250.00")
oPrivateKey = oCertificate.GetRSAPrivateKey()
cSignature = oPrivateKey.SignData([ :data = cMessage, :hashAlgorithm = oSha, :padding = oPadding ])
oPublicKey = oPublic.GetRSAPublicKey()
cChanged = oUtf8.GetBytes("Invoice 2024-001: 9250.00")
? nl + "4. signature of " + len(cSignature) + " bytes (2048-bit key); verified with the public certificate: " + oPublicKey.VerifyData([ :data = cMessage, :signature = cSignature, :hashAlgorithm = oSha, :padding = oPadding ])
? " the message changed: " + oPublicKey.VerifyData([ :data = cChanged, :signature = cSignature, :hashAlgorithm = oSha, :padding = oPadding ])
? " the public certificate can not sign: " + canSign(oPublic)
# 5. Is it trusted? A chain check asks whether the issuer is one that this computer trusts. For a self-signed certificate it is not.
oChain = new X509Chain()
oChain.ChainPolicy.RevocationMode = "NoCheck"
? nl + "5. the system trusts this self-signed certificate: " + oChain.Build(oPublic) + " (nobody else vouches for it)"
oRsa.Dispose()
func isValidNow oCertificate
oNow = (new DateTime).Now
return oNow.CompareTo(oCertificate.NotBefore) >= 0 and oNow.CompareTo(oCertificate.NotAfter) <= 0
func canSign oPublic
try
oPublic.GetRSAPrivateKey().SignData(new UTF8Encoding().GetBytes("x"),new HashAlgorithmName().SHA256,new RSASignaturePadding().Pkcs1)
return True
catch
return False
done1. subject: CN=Demo Server, O=RingDotNet, C=EG
issuer: CN=Demo Server, O=RingDotNet, C=EG (the same: self-signed)
thumbprint: 40 hex characters (the SHA-1 of the certificate: it identifies it)
has a private key: 1
valid for 366 days, and it is valid now: 1
2. the PFX is bigger than 1000 bytes: 1; loaded again it has the same thumbprint: 1 and a private key: 1
a wrong password is refused: 1
3. the public certificate as PEM starts with: -----BEGIN CERTIFICATE-----
loaded from the public export: same thumbprint 1, private key: 0
4. signature of 256 bytes (2048-bit key); verified with the public certificate: 1
the message changed: 0
the public certificate can not sign: 0
5. the system trusts this self-signed certificate: 0 (nobody else vouches for it)This program uses a few generic functions (dnNew, dnStatic) where a class cannot be used. The lesson The generic functions explains them.
How it works#
What a certificate says#
A certificate is a small document, signed by an issuer, that says: the public key below belongs to the subject named here, and this is true from this date to that date. The subject is a distinguished name such as CN=Demo Server, O=RingDotNet, C=EG (common name, organization, country). The thumbprint is the SHA-1 hash of the whole certificate: a short identifier that you compare to be sure it is this certificate and not another one with the same name.
In the real world the issuer is a certificate authority (CA) that your computer trusts, and it checks who you are before it signs. In a self-signed certificate the subject and the issuer are the same: the certificate vouches for itself. That is useful for tests, for development and for programs that talk to each other on a network you control (you install the certificate on both sides yourself), but no browser trusts it.
Making one#
RSA.Create(2048) makes the key pair. A CertificateRequest collects the subject name (an X500DistinguishedName), the key, the hash algorithm (SHA-256) and the padding (PKCS #1). Extensions are added to CertificateExtensions: here basic constraints with not a CA, because this certificate must not be able to sign other certificates. A server certificate also usually has a subject alternative name with the host names and a key usage. CreateSelfSigned(notBefore, notAfter) signs it with its own key. The validity starts a day in the past, because computers whose clocks differ by a few minutes would otherwise refuse a certificate that was just made. The classes HashAlgorithmName and RSASignaturePadding have their values as static properties, read through an object (new HashAlgorithmName().SHA256); the constructor of CertificateRequest has several forms, so dnNew takes names (Core concepts).
Exporting#
- PFX (also PKCS #12) holds the certificate and the private key, protected by a password.
Export("Pfx", password)makes the bytes andnew X509Certificate2(bytes, password)loads them again; a wrong password raises an error. A PFX is a secret: store it like a password, and give it only to the program that must sign or serve with it. - PEM (
ExportCertificatePem(), the text between-----BEGIN CERTIFICATE-----lines) and .cer (Export("Cert")) hold the public part only. This is what you give to everybody. A certificate loaded from it hasHasPrivateKeyfalse.
Signing and verifying#
The owner takes the private key out of the certificate (oCertificate.GetRSAPrivateKey(), an extension method of the certificate) and signs the data; anybody with the public certificate verifies it with GetRSAPublicKey and VerifyData. The signature has 256 bytes for a 2048-bit key. A changed message is refused, and the public-only certificate cannot sign at all (it has no private key). The two helper methods are extension methods, so they are called with dnStatic (the tutorial Caching).
Trust#
X509Chain.Build(certificate) asks the system whether it can build a chain from the certificate up to a trusted root. For a self-signed certificate that nobody installed as trusted, the answer is false. To make a computer trust such a certificate, you add it to its store of trusted roots (X509Store), which needs the user's decision and often administrator rights; do that only for certificates you made yourself and for development. Never ask users to install a certificate "to make the warning go away" for a site on the internet.
A certificate is only as good as the care of its private key. If the PFX or its password is stolen, the thief can sign as you until the certificate expires or is revoked. Keep validity short, keep keys out of source control, and renew before the end date.
What you learned#
- subject, issuer, validity and thumbprint,
CertificateRequestandCreateSelfSigned,- PFX with a password for the private key, PEM and .cer for the public part,
- signing with the private key, verifying with the public certificate,
- why a self-signed certificate is not trusted.
Exercises#
- Add a subject alternative name (
SubjectAlternativeNameBuilder) forlocalhostand127.0.0.1. - Write the PEM to a file (the tutorial Files and folders) and read it back with
X509Certificate2.CreateFromPem. - Make a second certificate with a validity of one second and look at
NotAfterand the check inisValidNowafter a pause. - Find the certificates of your own computer: open the store
RootwithX509Storeand print the subjects of the first five (the tutorial The Windows Registry shows another store of Windows).