Cryptography

CryptographyFree Lesson

Advertisement

Cryptography

Encryption, hashing, digital signatures, PKI, and cryptographic protocols.

Overview

Cryptography protects data confidentiality, integrity, and authenticity.

Key Concepts

  • Symmetric Encryption — Same key for encrypt/decrypt
  • Asymmetric Encryption — Public/private key pairs
  • Hashing — One-way data transformation
  • Digital Signatures — Authentication and integrity
  • PKI — Public Key Infrastructure

Symmetric Encryption

AES (Advanced Encryption Standard)

from cryptography.fernet import Fernet

# Generate key
key = Fernet.generate_key()
cipher = Fernet(key)

# Encrypt
plaintext = b"Secret message"
ciphertext = cipher.encrypt(plaintext)

# Decrypt
decrypted = cipher.decrypt(ciphertext)

Common Algorithms

AlgorithmKey SizeStatus
DES56-bitBroken
3DES168-bitDeprecated
AES128/192/256-bitSecure
ChaCha20256-bitSecure

Asymmetric Encryption

RSA

from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

# Generate key pair
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)
public_key = private_key.public_key()

# Encrypt with public key
ciphertext = public_key.encrypt(
    plaintext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# Decrypt with private key
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

Hashing Algorithms

AlgorithmOutput SizeSecurity
MD5128-bitBroken
SHA-1160-bitWeak
SHA-256256-bitSecure
SHA-3VariableSecure
bcryptVariableSecure (passwords)

Digital Signatures

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

# Sign message
signature = private_key.sign(
    message,
    padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    hashes.SHA256()
)

# Verify signature
try:
    public_key.verify(
        signature,
        message,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    print("Signature is valid")
except:
    print("Signature is invalid")

Practice

Implement a simple encryption/decryption tool using Python.

Advertisement

Need Expert Cybersecurity Help?

Get personalized security training or professional consulting.

Advertisement