| name | tls-ssl |
| description | TLS/SSL certificate management and encryption |
| category | networking |
| difficulty | intermediate |
| tags | ["tls","ssl","encryption","certificate","https"] |
| author | OpenCode Community |
| version | 1 |
| last_updated | 2024-01-15T00:00:00.000Z |
TLS/SSL Certificates
What I Do
I am TLS (Transport Layer Security), the cryptographic protocol providing secure communications over networks. I evolved from SSL to provide encryption, authentication, and integrity for data in transit. I use X.509 certificates to authenticate servers and optionally clients. I support various cipher suites for encryption, with modern best practices favoring AEAD ciphers like AES-GCM and ChaCha20-Poly1305. I implement perfect forward secrecy through ephemeral key exchanges. I enable HTTPS, secure APIs, and encrypted microservices communication. I help organizations meet compliance requirements and protect sensitive data during transmission.
When to Use Me
- HTTPS web server configuration
- API security and authentication
- Service-to-service encryption
- Email server security (SMTPS, IMAPS)
- Database connection encryption
- VPN and secure tunnel establishment
- IoT device communication security
- Legacy system security upgrades
Core Concepts
X.509 Certificates: Digital documents binding public keys to identities, signed by certificate authorities.
Certificate Chain: Hierarchy from root CA to intermediate to leaf certificates.
TLS Handshake: Protocol negotiation, key exchange, and authentication process.
Cipher Suites: Combinations of algorithms for key exchange, encryption, and integrity.
Perfect Forward Secrecy: Ephemeral keys ensuring past communications remain secure.
OCSP Stapling: Real-time certificate validity checking.
Certificate Pinning: Hardcoding expected certificates for additional security.
Code Examples
Example 1: TLS Server Implementation (Go)
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"net"
"os"
"time"
)
type TLSServer struct {
addr string
port int
certFile string
keyFile string
minTLSVersion uint16
cipherSuites []uint16
}
func NewTLSServer(addr string, port int, certFile, keyFile string) *TLSServer {
return &TLSServer{
addr: addr,
port: port,
certFile: certFile,
keyFile: keyFile,
minTLSVersion: tls.VersionTLS13,
cipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
},
}
}
func (s *TLSServer) generateSelfSignedCert() error {
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return fmt.Errorf("failed to generate private key: %w", err)
}
serialNumber, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), ))
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []{},
Country: []{},
Province: []{},
Locality: []{},
StreetAddress: []{},
CommonName: ,
},
NotBefore: time.Now(),
NotAfter: time.Now().Add( * * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: ,
DNSNames: []{, },
IPAddresses: []net.IP{net.ParseIP(), net.ParseIP()},
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
err != {
fmt.Errorf(, err)
}
certFile, err := os.Create(s.certFile)
err != {
fmt.Errorf(, err)
}
certFile.Close()
pem.Encode(certFile, &pem.Block{Type: , Bytes: certDER})
keyFile, err := os.OpenFile(s.keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, )
err != {
fmt.Errorf(, err)
}
keyFile.Close()
pem.Encode(keyFile, &pem.Block{Type: , Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
}
createTLSConfig() *tls.Config {
cert, err := tls.LoadX509KeyPair(s.certFile, s.keyFile)
err != {
log.Printf(, err)
err := s.generateSelfSignedCert(); err != {
log.Fatalf(, err)
}
cert, _ = tls.LoadX509KeyPair(s.certFile, s.keyFile)
}
&tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: s.minTLSVersion,
CipherSuites: s.cipherSuites,
CurvePreferences: []tls.CurveID{
tls.X25519,
tls.CurveP256,
},
NextProtos: []{, },
SessionTicketsDisabled: ,
ClientAuth: tls.NoClientCert,
}
}
Start() {
config := s.createTLSConfig()
listener, err := tls.Listen(, fmt.Sprintf(, s.addr, s.port), config)
err != {
fmt.Errorf(, err)
}
listener.Close()
log.Printf(, s.addr, s.port)
{
conn, err := listener.Accept()
err != {
log.Printf(, err)
}
s.handleConnection(conn)
}
}
handleConnection(conn net.Conn) {
conn.Close()
state := conn.(*tls.Conn).State()
log.Printf(, conn.RemoteAddr())
log.Printf(, state.Version)
log.Printf(, state.CipherSuite)
buffer := ([], )
{
n, err := conn.Read(buffer)
err != {
log.Printf(, err)
}
log.Printf(, n)
response := [](fmt.Sprintf())
conn.Write(response)
}
}
{
(chain) == {
fmt.Errorf()
}
i, cert := chain {
cert.NotAfter.Before(time.Now()) {
fmt.Errorf(, i)
}
!cert.NotBefore.Before(time.Now()) {
fmt.Errorf(, i)
}
cert.KeyUsage&x509.KeyUsageDigitalSignature == {
fmt.Errorf(, i)
}
}
}
Example 2: Certificate Management (Python)
import subprocess
import datetime
import os
from typing import Optional, Dict, List
from dataclasses import dataclass
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from cryptography.x509.oid import NameOID
@dataclass
class CertificateInfo:
subject: str
issuer: str
serial_number: str
not_before: datetime.datetime
not_after: datetime.datetime
days_remaining: int
is_valid: bool
public_key_size: int
signature_algorithm: str
class CertificateManager:
def __init__(self, ca_cert_path: str = None, ca_key_path: str = None):
self.ca_cert_path = ca_cert_path
self.ca_key_path = ca_key_path
def generate_private_key(self, key_size: int = 4096, output_path: str = ) -> rsa.RSAPrivateKey:
private_key = rsa.generate_private_key(
public_exponent=,
key_size=key_size,
backend=default_backend()
)
output_path:
(output_path, ) f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
))
private_key
() -> x509.Certificate:
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, country),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, organization),
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
])
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(private_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow())
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=validity_days))
.add_extension(
x509.BasicConstraints(ca=, path_length=),
critical=,
)
.add_extension(
x509.KeyUsage(
digital_signature=,
key_encipherment=,
content_commitment=,
data_encipherment=,
key_agreement=,
key_cert_sign=,
crl_sign=,
encipher_only=,
decipher_only=,
),
critical=,
)
.sign(private_key, hashes.SHA256(), default_backend())
)
cert
() -> x509.Certificate:
subject = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
])
builder = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(ca_certificate.subject)
.public_key(private_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow())
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=validity_days))
)
sans:
san_list = []
san sans:
san.replace(, ).isdigit():
san_list.append(x509.IPAddress(x509.ip_address_bytes(san.encode())))
:
san_list.append(x509.DNSName(san))
builder = builder.add_extension(
x509.SubjectAlternativeName(san_list),
critical=,
)
cert = (
builder
.add_extension(
x509.BasicConstraints(ca=, path_length=),
critical=,
)
.add_extension(
x509.KeyUsage(
digital_signature=,
key_encipherment=,
content_commitment=,
data_encipherment=,
key_agreement=,
key_cert_sign=,
crl_sign=,
encipher_only=,
decipher_only=,
),
critical=,
)
.add_extension(
x509.ExtendedKeyUsage([
x509.oid.ExtendedKeyUsageOID.SERVER_AUTH,
]),
critical=,
)
.sign(ca_private_key, hashes.SHA256(), default_backend())
)
cert
():
(output_path, ) f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
() -> x509.Certificate:
(cert_path, ) f:
x509.load_pem_x509_certificate(f.read(), default_backend())
() -> CertificateInfo:
cert = .load_certificate(cert_path)
now = datetime.datetime.utcnow()
days_remaining = (cert.not_valid_after - now).days
:
common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[].value
IndexError:
common_name =
CertificateInfo(
subject=cert.subject.rfc4514_string(),
issuer=cert.issuer.rfc4514_string(),
serial_number=(cert.serial_number),
not_before=cert.not_valid_before_utc,
not_after=cert.not_valid_after_utc,
days_remaining=days_remaining,
is_valid=days_remaining > ,
public_key_size=cert.public_key().key_size,
signature_algorithm=cert.signature_hash_algorithm.name
)
() -> :
info = .get_certificate_info(cert_path)
status = {
: cert_path,
: info.subject,
: info.not_after.isoformat(),
: info.days_remaining,
:
}
info.days_remaining <= :
status[] =
info.days_remaining <= warning_days:
status[] =
status
() -> :
cert = .load_certificate(cert_path)
ca_cert = .load_certificate(ca_cert_path)
:
ca_cert.public_key().verify(
cert.signature,
cert.tbs_certificate_bytes,
padding=PKCS1v15(),
algorithm=cert.signature_hash_algorithm
)
Exception:
():
cert = .load_certificate(cert_path)
(output_path, ) f:
f.write(cert.public_bytes(serialization.Encoding.DER))
():
cert = .load_certificate(cert_path)
public_key = cert.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
=serialization.PublicFormat.SubjectPublicKeyInfo
)
(output_path, ) f:
f.write(public_key)
Example 3: ACME/Let's Encrypt Client (Python)
import json
import os
import base64
import hashlib
import time
from typing import Dict, Optional
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
import requests
class ACMEClient:
def __init__(self, email: str = None, directory_url: str = "https://acme-v02.api.letsencrypt.org/directory"):
self.email = email
self.directory_url = directory_url
self.directory: Dict = {}
self.account_key = None
self.account_url: Optional[str] = None
self.nonce: Optional[str] = None
def _load_or_create_account_key(self, key_path: str = "account.key"):
if os.path.exists(key_path):
with open(key_path, 'rb') as f:
.account_key = f.read()
:
cryptography.hazmat.primitives.asymmetric rsa
private_key = rsa.generate_private_key(
public_exponent=,
key_size=,
backend=default_backend()
)
.account_key = private_key.private_bytes(
encoding=
)
(key_path, ) f:
f.write(.account_key)
() -> :
cryptography.hazmat.primitives.asymmetric padding
cryptography.hazmat.primitives serialization
header = {
: ,
: ._get_jwk(),
: .nonce,
: url
}
protected = base64.urlsafe_b64encode(json.dumps(header).encode()).rstrip()
payload_b64 = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip()
signing_input = protected + + payload_b64
private_key = serialization.load_pem_private_key(
.account_key, password=, backend=default_backend()
)
signature = private_key.sign(
signing_input,
padding.PKCS1v15(),
hashes.SHA256()
)
{
: protected.decode(),
: payload_b64.decode(),
: base64.urlsafe_b64encode(signature).rstrip().decode()
}
() -> :
private_key = serialization.load_pem_private_key(
.account_key, password=, backend=default_backend()
)
public_numbers = private_key.public_key().public_numbers()
n_bytes = public_numbers.n.to_bytes((public_numbers.n.bit_length() + ) // , )
e_bytes = public_numbers.e.to_bytes((public_numbers.e.bit_length() + ) // , )
{
: ,
: base64.urlsafe_b64encode(n_bytes).rstrip().decode(),
: base64.urlsafe_b64encode(e_bytes).rstrip().decode(),
}
():
resp = requests.head(.directory[])
.nonce = resp.headers[]
() -> :
payload :
payload = {}
resp = requests.post(
url,
json=._jose(payload, url),
headers={: }
)
.nonce = resp.headers.get(, .nonce)
resp.status_code >= :
error = resp.json()
Exception()
resp.json()
() -> :
resp = requests.get(url)
resp.json()
():
.directory = ._get(.directory_url)
() -> :
payload = {
: terms_of_service_agreed,
}
.email:
payload[] = []
response = ._post(.directory[], payload)
.account_url = response
response
() -> :
payload = {: [{: , : } identifiers]}
._post(.directory[], payload)
() -> :
._get(auth_url)
() -> :
payload = {}
._post(challenge_url, payload)
() -> :
order = ._get(order_url)
order[] != :
Exception()
cert_url = order[]
cert_response = requests.get(cert_url)
cert_response.text
() -> :
.fetch_directory()
:
.create_account(terms_of_service_agreed=)
Exception e:
(e):
order = .create_order(domains)
auth_url order[]:
auth = .get_authorization(auth_url)
challenge auth[]:
challenge[] == :
._setup_http_challenge(auth, challenge)
:
order_status = ._get(order_url)
order_status[] == :
order_status[] == :
time.sleep()
:
Exception()
key = .generate_private_key(key_size)
._finalize_order(order[], key)
cert_pem = .download_certificate(order_url)
(cert_path, ) f:
f.write(cert_pem)
private_key_pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
(key_path, ) f:
f.write(private_key_pem)
():
cryptography.hazmat.primitives hashes
cryptography.hazmat.backends default_backend
challenge_token = challenge[]
key_auth =
(, ) f:
f.write(key_auth)
.complete_challenge(challenge[])
() -> :
jwk = ._get_jwk()
jwk_json = json.dumps(jwk, sort_keys=, separators=(, ))
digest = hashlib.sha256(jwk_json.encode()).digest()
base64.urlsafe_b64encode(digest).rstrip().decode()
Best Practices
- Use TLS 1.2+; disable TLS 1.0 and 1.1
- Prefer TLS 1.3 for reduced latency and improved security
- Use strong cipher suites with AEAD encryption
- Implement certificate pinning for critical applications
- Use OCSP stapling for certificate revocation checking
- Configure proper certificate chains
- Set reasonable session ticket lifetimes
- Monitor certificate expiration proactively
- Use HSTS headers to enforce HTTPS
- Implement certificate transparency monitoring
Core Competencies
- X.509 certificate generation and management
- TLS protocol implementation
- Cipher suite configuration
- Certificate chain validation
- ACME protocol for automated certificates
- Perfect forward secrecy
- OCSP and CRL management
- Certificate pinning
- TLS termination configuration
- Mutual TLS (mTLS) implementation
- Security headers (HSTS, CSP)
- Performance optimization