🔒 Security

HTTPS

HTTP Secure (HyperText Transfer Protocol Secure)

HTTPS is the HTTP protocol encrypted with TLS (Transport Layer Security). It uses default port 443 and guarantees confidentiality, integrity, and authentication of communication between client and server. An essential security element of the modern web, HTTPS is recommended for all websites.

📖 Detailed Explanation

HTTPS (HyperText Transfer Protocol Secure) is a protocol that adds a TLS (Transport Layer Security) encryption layer to HTTP. While HTTP transmits data in plaintext, HTTPS encrypts all communication, preventing man-in-the-middle (MITM) attacks, eavesdropping, and data tampering. You can confirm an HTTPS connection by the padlock icon in the address bar and the "https://" prefix.

The history of HTTPS began in 1994 when Netscape introduced SSL (Secure Sockets Layer). SSL was replaced by TLS due to security vulnerabilities, and TLS 1.3 is currently the latest standard. TLS 1.3 simplified the handshake process (1-RTT) and removed legacy cryptographic algorithms, improving both security and performance. NIST recommended support for TLS 1.3 by 2024, and PCI DSS prohibits the use of TLS 1.0.

HTTPS achieves three core security goals. Confidentiality protects data with symmetric-key encryption such as AES-GCM and ChaCha20-Poly1305. Integrity detects data tampering with a message authentication code (MAC). Authentication verifies the server's identity with an X.509 certificate. During the TLS handshake, keys are exchanged using ECDHE (Elliptic Curve Diffie-Hellman Ephemeral), and subsequent communication is encrypted with the symmetric key.

In the modern web, HTTPS is not optional but essential. Google gives HTTPS sites an SEO ranking boost, and Chrome displays a "Not secure" warning on HTTP sites. The emergence of free certificate authorities (CAs) such as Let's Encrypt has removed the cost barrier to adopting HTTPS. HTTP/2 and HTTP/3 are designed on the premise of HTTPS, so modern web performance optimizations are also possible only with HTTPS. As of 2025, more than 95% of global web traffic uses HTTPS.

💻 Code Example

// Node.js HTTPS 서버 구현 예제
const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();

// TLS 인증서 로드 (Let's Encrypt 또는 자체 서명)
const options = {
    key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem'),
    // TLS 1.2 이상만 허용 (TLS 1.3 권장)
    minVersion: 'TLSv1.2',
    // 안전한 암호 스위트만 사용
    ciphers: [
        'TLS_AES_256_GCM_SHA384',
        'TLS_CHACHA20_POLY1305_SHA256',
        'TLS_AES_128_GCM_SHA256',
        'ECDHE-RSA-AES256-GCM-SHA384',
        'ECDHE-RSA-AES128-GCM-SHA256'
    ].join(':'),
    // ECDHE 키 교환 우선
    ecdhCurve: 'X25519:P-256:P-384'
};

// HSTS (HTTP Strict Transport Security) 헤더 설정
app.use((req, res, next) => {
    res.setHeader('Strict-Transport-Security',
        'max-age=31536000; includeSubDomains; preload');
    next();
});

// HTTP를 HTTPS로 리다이렉트
const http = require('http');
http.createServer((req, res) => {
    res.writeHead(301, {
        'Location': `https://${req.headers.host}${req.url}`
    });
    res.end();
}).listen(80);

app.get('/', (req, res) => {
    res.json({
        message: 'Secure HTTPS Connection',
        protocol: req.protocol,
        tlsVersion: req.socket.getProtocol?.() || 'TLS'
    });
});

// HTTPS 서버 시작 (포트 443)
https.createServer(options, app).listen(443, () => {
    console.log('HTTPS server running on port 443');
});

// 인증서 자동 갱신 (Let's Encrypt certbot 사용)
// crontab: 0 0 1 * * certbot renew --post-hook "systemctl restart nodejs"
# Nginx TLS 1.3 최적 설정 (2025 베스트 프랙티스)
# /etc/nginx/conf.d/ssl.conf

server {
    listen 80;
    server_name example.com www.example.com;

    # HTTP를 HTTPS로 301 리다이렉트
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com www.example.com;

    # 인증서 경로 (Let's Encrypt)
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # TLS 버전 - TLS 1.2, 1.3만 허용 (TLS 1.0, 1.1 비활성화)
    ssl_protocols TLSv1.2 TLSv1.3;

    # 암호 스위트 - TLS 1.3은 자동, TLS 1.2는 명시
    ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
    ssl_prefer_server_ciphers off;  # TLS 1.3에서는 클라이언트 우선

    # 세션 캐싱 (성능 향상)
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;  # Perfect Forward Secrecy 보장

    # OCSP Stapling (인증서 검증 속도 향상)
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    # 보안 헤더
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # DH 파라미터 (2048비트 이상)
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;

    # 키 크기: RSA 2048비트 또는 ECDSA P-256 이상
    # ECDSA 권장 (더 작은 키로 동등한 보안, 더 빠른 핸드셰이크)

    location / {
        root /var/www/html;
        index index.html;
    }
}

# DH 파라미터 생성: openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048
# 테스트: https://www.ssllabs.com/ssltest/
# Python에서 HTTPS 요청 및 인증서 검증
import requests
import ssl
import urllib3
from requests.adapters import HTTPAdapter
from urllib3.util.ssl_ import create_urllib3_context

# 기본 HTTPS 요청 (인증서 자동 검증)
response = requests.get('https://api.example.com/data')
print(f"Status: {response.status_code}")
print(f"TLS Version: {response.raw.version}")

# 커스텀 TLS 설정 어댑터
class TLS13Adapter(HTTPAdapter):
    """TLS 1.3 전용 어댑터"""

    def init_poolmanager(self, *args, **kwargs):
        ctx = create_urllib3_context()
        # TLS 1.3만 허용 (최고 보안)
        ctx.minimum_version = ssl.TLSVersion.TLSv1_3
        # 안전한 암호 스위트
        ctx.set_ciphers('TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256')
        kwargs['ssl_context'] = ctx
        return super().init_poolmanager(*args, **kwargs)

# TLS 1.3 전용 세션 사용
session = requests.Session()
session.mount('https://', TLS13Adapter())

try:
    response = session.get('https://api.example.com/secure')
    print("TLS 1.3 connection successful")
except requests.exceptions.SSLError as e:
    print(f"TLS Error: {e}")

# 인증서 핀닝 (Certificate Pinning)
# 특정 인증서의 공개키 해시를 검증
EXPECTED_CERT_HASH = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="

def verify_certificate_pin(host, port=443):
    """인증서 핀 검증"""
    import hashlib
    import socket

    context = ssl.create_default_context()
    with socket.create_connection((host, port)) as sock:
        with context.wrap_socket(sock, server_hostname=host) as ssock:
            cert_der = ssock.getpeercert(binary_form=True)
            cert_hash = hashlib.sha256(cert_der).digest()
            cert_pin = f"sha256/{cert_hash.hex()}"

            if cert_pin != EXPECTED_CERT_HASH:
                raise ssl.SSLError(f"Certificate pin mismatch: {cert_pin}")

            print(f"Certificate verified: {cert_pin}")
            return True

# 주의: 자체 서명 인증서 허용은 보안 위험!
# requests.get(url, verify=False)  # 절대 프로덕션에서 사용 금지!

🗣️ Say It Like This in Practice

💬 In response to a security audit
"We applied TLS 1.3 to all services and disabled TLS 1.0/1.1. We are also registered on the HSTS preload list, so browsers always connect via HTTPS. We received an A+ rating on the SSL Labs test, and certificates are automatically renewed through Let's Encrypt."
💬 In an Infrastructure Design Meeting
"TLS termination is done at the load balancer, and the backends communicate over HTTP since they are on an internal network. However, if there is sensitive data, end-to-end encryption is required, so we need to apply mTLS (mutual TLS) all the way to the backend. Certificates are centrally managed with HashiCorp Vault."
💬 In a code review
"You must not turn off certificate verification with verify=False. Even in a development environment, issue and use a self-signed certificate. If this code is deployed to production, it will be completely exposed to man-in-the-middle attacks. It is risky even if you branch on an environment variable."

⚠️ Cautions & Best Practices

❌
Mixed Content

Loading HTTP resources (images, scripts) on an HTTPS page triggers security warnings and may be blocked. Load all resources over HTTPS, or use protocol-relative URLs (//).

❌
Neglecting Certificate Expiration

When a certificate expires, browsers block access. Set up automatic renewal with Let's Encrypt + certbot, and monitor so that you receive an alert 7 days before expiration. If the certificate chain is incomplete, errors occur on mobile devices.

❌
Allowing Legacy TLS Versions

TLS 1.0/1.1 have known vulnerabilities such as POODLE and BEAST. PCI DSS regulations also prohibit the use of TLS 1.0. Allow at least TLS 1.2, and preferably only TLS 1.3.

✅
HTTPS Best Practices

Use TLS 1.3 by default, apply the HSTS header (including preload), enable OCSP Stapling, use RSA 2048-bit or ECDSA P-256 or higher keys, automatically renew certificates, and implement HTTP→HTTPS 301 redirects. Aim for an A+ rating on SSL Labs.

🔗 Related Terms

📚 Learn More