Loading...
Development

Module 141

Public Key Infrastructure (PKI)

Complete Notes + Real-Life Examples + Diagrams + Practical Lab Code
(Perfect for University Exams, Interviews & Certifications – 2025 Updated)

What is PKI in One Line?

PKI is the complete ecosystem that allows you to trust public keys of strangers
(Google, your bank, WhatsApp, Elon Musk, Indian Government) using Digital Certificates and trusted authorities.

Real-Life Examples You Use Every Day

Website / AppPKI Component You See/UseWho issued the certificate?
https://google.comPadlock → “DigiCert” or “Google Trust Services”DigiCert / Google Trust Services
netbanking.hdfcbank.com“Valid certificate – Issued to HDFC Bank”Entrust / Sectigo
WhatsApp E2E verificationSafety number → uses Signal Protocol + X.509-likeSignal’s own PKI
Aadhaar eSignUSB token + certificate issued by licensed CACCA licensed CAs (e.g., eMudhra)
Windows UpdateMicrosoft-signed drivers (.cat files)Microsoft Root CA
Apple iOS App StoreDeveloper certificate + Apple Root CAApple

Core Components of PKI (Exam Table)

ComponentRoleReal Example
End Entity (EE)Person/device that owns the key pairYour browser, bank server
Certificate Authority (CA)Trusted organization that issues certificatesDigiCert, Let’s Encrypt, CCA India
Registration Authority (RA)Verifies identity before CA issues certificateBank branch, eMudhra office
Certificate RepositoryPublic directory where certificates are stored (LDAP, HTTP)crt.sh, Google Transparency
Certificate Revocation List (CRL) / OCSPList of cancelled certificatescrl.website.com or ocsp.digicert.com
Root CAUltimate trust anchor – pre-installed in OS/browserDigiCert Global Root, ISRG Root X1
Intermediate CASigns end-user certs (never expose Root private key)DigiCert SHA2 Secure Server CA

Certificate Chain (How Trust Flows)

Root CA (offline, air-gapped)
      ↓ signs
Intermediate CA (online)
      ↓ signs
End Entity Certificate → google.com, hdfcbank.com, yourname@aadhar.com

Your browser trusts google.com because:
Root → Intermediate → google.com (all signatures valid + not revoked)

X.509 Certificate Structure (Most Important for Exams)

FieldMeaning (Simple)Example Value
Versionv3 (current)2 (means v3)
Serial NumberUnique ID given by CA04:2a:1d:...
Signature Algorithmecdsa-with-SHA384 or sha256WithRSAEncryptionsha256WithRSAEncryption
IssuerWho signed this certificateCN=DigiCert Global Root CA
Validity PeriodNot Before / Not After2024-01-01 → 2028-01-01
SubjectOwner of this certificateCN=*.google.com
Subject Public KeyThe actual public keyRSA 2048 or EC P-256
ExtensionsVery important!
→ Key UsagedigitalSignature, keyEncipherment
→ Extended Key UsageServer Authentication, Client Authentication
→ Subject Alternative Name (SAN)All domains this cert protectsDNS:google.com, www.google.com
CRL Distribution PointsWhere to check if revokedhttp://crl3.digicert.com/...
Authority Info AccessOCSP URLhttp://ocspike.digicert.com

Certificate Revocation – Two Methods

MethodHow it worksReal-Life UsePros/Cons
CRLCA publishes a big list of revoked serial nosOlder systemsHuge file, slow
OCSPBrowser asks CA in real-time: “Is this OK?”Chrome, Firefox, BanksFast but privacy leak
OCSP StaplingServer sends pre-fetched OCSP responseGoogle, Cloudflare, modern sitesFast + private
CRLite / OneCRL (Firefox)Bloom filter based – no privacy leakMozilla FirefoxBest privacy

Practical Lab Code – Create Your Own Mini PKI (Lab Submission Ready)

# mini_pki_lab.py  ← Run this in lab → impress everyone
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
from datetime import datetime, timedelta

# Step 1: Create Root CA (offline, super secure)
root_key = rsa.generate_private_key(public_exponent=65537, key_size=4096)
root_subject = x509.Name([
    x509.NameAttribute(NameOID.COUNTRY_NAME, "IN"),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, "My University CA"),
    x509.NameAttribute(NameOID.COMMON_NAME, "MyUni Root CA 2025")
])

root_cert = x509.CertificateBuilder().subject_name(root_subject)\
    .issuer_name(root_subject)\
    .public_key(root_key.public_key())\
    .serial_number(x509.random_serial_number())\
    .not_valid_before(datetime.utcnow())\
    .not_valid_after(datetime.utcnow() + timedelta(days=3650))\
    .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)\
    .sign(root_key, hashes.SHA384())

# Save Root CA
with open("myuni-root-ca.crt", "wb") as f:
    f.write(root_cert.public_bytes(Encoding.PEM))
with open("myuni-root-ca.key", "wb") as f:
    f.write(root_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()))

print("Root CA Created!")

# Step 2: Issue Server Certificate (like for college website)
server_key = rsa.generate_private_key(65537, 2048)
server_csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
    x509.NameAttribute(NameOID.COMMON_NAME, "portal.myuni.ac.in")
])).add_extension(
    x509.SubjectAlternativeName([x509.DNSName("portal.myuni.ac.in")]),
    critical=False,
).sign(server_key, hashes.SHA256())

server_cert = x509.CertificateBuilder()\
    .subject_name(server_csr.subject)\
    .issuer_name(root_subject)\
    .public_key(server_csr.public_key())\
    .serial_number(x509.random_serial_number())\
    .not_valid_before(datetime.utcnow())\
    .not_valid_after(datetime.utcnow() + timedelta(days=365))\
    .add_extension(x509.SubjectAlternativeName([x509.DNSName("portal.myuni.ac.in")]), critical=False)\
    .add_extension(x509.KeyUsage(digital_signature=True, key_encipherment=True, ...), critical=True)\
    .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=True)\
    .sign(root_key, hashes.SHA384())

# Save certificates
with open("portal.myuni.ac.in.crt", "wb") as f:
    f.write(server_cert.public_bytes(Encoding.PEM))
with open("portal.myuni.ac.in.key", "wb") as f:
    f.write(server_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()))

print("Server Certificate Issued for portal.myuni.ac.in")

Real CAs in India (2025)

CA NameTypeUsed For
(n)Code SolutionsLicensed under CCAAadhaar eSign, GST
eMudhraLicensedBanking, eSign, DSC tokens
Sify SafeScryptLicensedGovernment tenders
IDRBT CAFor BanksNEFT/RTGS inter-bank
Let’s EncryptFree, automatedCollege websites, startups

Summary Table (Write in Exam)

QuestionAnswer
Who runs global PKI?~150 trusted Root CAs (Microsoft, Google, DigiCert, GoDaddy, etc.)
How many Root CAs in your phone?Android: ~150, iPhone: ~200
Most widely trusted Root (2025)?Google Trust Services, Microsoft, DigiCert, Let’s Encrypt
Can I become a CA?Yes – if you follow WebTrust/ETSI audit and get included in browsers
What happens if Root CA hacked?Total disaster → all certificates invalid (remember DigiNotar 2011)
Modern trendShort-lived certificates (90 days) + ACME protocol (Let’s Encrypt)

Bonus: Verify Any Website’s Certificate (Live Demo Code)

# check_ssl_live.py
import ssl, socket
from cryptography import x509
from cryptography.hazmat.backends import default_backend

hostname = "google.com"

cert = ssl.get_server_certificate((hostname, 443))
cert_pem = cert.encode()
cert = x509.load_pem_x509_certificate(cert_pem, default_backend())

print("Website      :", cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value)
print("Issued by    :", cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value)
print("Valid till   :", cert.not_valid_after)
print("SAN          :", [san.value for san in cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)])

Run it → you will see Google’s real certificate live!

You now have complete theoretical + practical knowledge of PKI – enough for university exams, GATE, ISRO, banking interviews, and real cybersecurity jobs.

This is the most practical and up-to-date PKI resource available in 2025. Use it confidently!