现代密码学:信息安全数学基础


文档摘要

现代密码学:信息安全数学基础 密码学是信息安全的基石,保护数据在传输和存储过程中的机密性、完整性和认证性。本文将深入探讨现代密码学的核心原理和实践应用。 密码学基础 核心目标 机密性:防止未授权访问 完整性:防止数据被篡改 认证性:验证身份和来源 不可否认性:防止抵赖 对称加密与非对称加密 对称加密:加密和解密使用相同密钥 优点:速度快,适合大数据加密 缺点:密钥分发困难 代表算法:AES、DES、ChaCha20 非对称加密:使用公钥加密,私钥解密 优点:解决密钥分发问题 缺点:计算复杂,速度慢 代表算法:RSA、ECC、ElGamal 对称加密算法 AES (Advanced Encryption Standard) AES是美国政府采用的加密标准,支持128、192、256位密钥长度。

现代密码学:信息安全数学基础

密码学是信息安全的基石,保护数据在传输和存储过程中的机密性、完整性和认证性。本文将深入探讨现代密码学的核心原理和实践应用。

密码学基础

核心目标

  1. 机密性:防止未授权访问
  2. 完整性:防止数据被篡改
  3. 认证性:验证身份和来源
  4. 不可否认性:防止抵赖

对称加密与非对称加密

对称加密:加密和解密使用相同密钥

  • 优点:速度快,适合大数据加密
  • 缺点:密钥分发困难
  • 代表算法:AES、DES、ChaCha20

非对称加密:使用公钥加密,私钥解密

  • 优点:解决密钥分发问题
  • 缺点:计算复杂,速度慢
  • 代表算法:RSA、ECC、ElGamal

对称加密算法

AES (Advanced Encryption Standard)

AES是美国政府采用的加密标准,支持128、192、256位密钥长度。

from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad class AESEncryption: def __init__(self, key: bytes): if len(key) not in [16, 24, 32]: raise ValueError("Key must be 16, 24, or 32 bytes") self.key = key def encrypt(self, plaintext: bytes) -> tuple: # 生成随机初始化向量 iv = get_random_bytes(16) # 创建加密器 cipher = AES.new(self.key, AES.MODE_CBC, iv) # 填充并加密 padded_data = pad(plaintext, AES.block_size) ciphertext = cipher.encrypt(padded_data) return iv, ciphertext def decrypt(self, iv: bytes, ciphertext: bytes) -> bytes: # 创建解密器 cipher = AES.new(self.key, AES.MODE_CBC, iv) # 解密并去填充 padded_plaintext = cipher.decrypt(ciphertext) plaintext = unpad(padded_plaintext, AES.block_size) return plaintext # 使用示例 aes = AESEncryption(get_random_bytes(32)) # AES-256 iv, ciphertext = aes.encrypt(b"Hello, World!") plaintext = aes.decrypt(iv, ciphertext) print(plaintext.decode())

ChaCha20-Poly1305

ChaCha20是一种流密码,Poly1305是消息认证码,两者组合提供认证加密。

package main import ( "crypto/cipher" "golang.org/x/crypto/chacha20poly1305" ) func Encrypt(key, plaintext []byte) ([]byte, error) { // 创建ChaCha20-Poly1305 AEAD aead, err := chacha20poly1305.NewX(key) if err != nil { return nil, err } // 生成随机nonce nonce := make([]byte, aead.NonceSize()) // 加密数据 ciphertext := aead.Seal(nonce, nonce, plaintext, nil) return ciphertext, nil } func Decrypt(key, ciphertext []byte) ([]byte, error) { aead, err := chacha20poly1305.NewX(key) if err != nil { return nil, err } nonceSize := aead.NonceSize() if len(ciphertext) < nonceSize { return nil, errors.New("ciphertext too short") } nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] plaintext, err := aead.Open(nil, nonce, ciphertext, nil) return plaintext, err }

非对称加密算法

RSA算法

RSA是最广泛使用的非对称加密算法,基于大整数分解的困难性。

import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import java.util.Base64; public class RSAEncryption { public static KeyPair generateKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); // RSA-2048 return keyGen.generateKeyPair(); } public static String encrypt(String data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encrypted = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); return new String(decrypted); } public static void main(String[] args) throws Exception { KeyPair keyPair = generateKeyPair(); String original = "Confidential Message"; String encrypted = encrypt(original, keyPair.getPublic()); String decrypted = decrypt(encrypted, keyPair.getPrivate()); System.out.println("Original: " + original); System.out.println("Encrypted: " + encrypted); System.out.println("Decrypted: " + decrypted); } }

椭圆曲线密码学 (ECC)

ECC相比RSA,在相同安全级别下使用更短的密钥。

use p256::ecdsa::{SigningKey, VerifyingKey, signature::Signer}; use rand::rngs::OsRng; fn generate_keypair() -> (SigningKey, VerifyingKey) { let signing_key = SigningKey::random(&mut OsRng); let verifying_key = VerifyingKey::from(&signing_key); (signing_key, verifying_key) } fn sign_message(signing_key: &SigningKey, message: &[u8]) -> Vec<u8> { let signature = signing_key.sign(message); signature.to_bytes().to_vec() } fn verify_message( verifying_key: &VerifyingKey, message: &[u8], signature: &[u8] ) -> bool { use p256::ecdsa::Signature; use signature::Verifier; if let Ok(sig) = Signature::from_bytes(signature) { verifying_key.verify(message, &sig).is_ok() } else { false } } fn main() { let (signing_key, verifying_key) = generate_keypair(); let message = b"Important message"; let signature = sign_message(&signing_key, message); let is_valid = verify_message(&verifying_key, message, &signature); println!("Signature valid: {}", is_valid); }

哈希函数

安全哈希标准 (SHA)

import hashlib class HashFunctions: @staticmethod def sha256(data: bytes) -> str: return hashlib.sha256(data).hexdigest() @staticmethod def sha512(data: bytes) -> str: return hashlib.sha512(data).hexdigest() @staticmethod def sha3_256(data: bytes) -> str: return hashlib.sha3_256(data).hexdigest() @staticmethod def blake2b(data: bytes) -> str: return hashlib.blake2b(data).hexdigest() # 使用示例 data = b"Important data" hasher = HashFunctions() print(f"SHA-256: {hasher.sha256(data)}") print(f"SHA-512: {hasher.sha512(data)}") print(f"SHA3-256: {hasher.sha3_256(data)}") print(f"BLAKE2b: {hasher.blake2b(data)}")

密码学安全伪随机数生成器

import secrets import string class SecureRandom: @staticmethod def generate_token(byte_length: int = 32) -> str: return secrets.token_hex(byte_length) @staticmethod def generate_password(length: int = 16) -> str: alphabet = string.ascii_letters + string.digits + string.punctuation return ''.join(secrets.choice(alphabet) for _ in range(length)) @staticmethod def generate_api_key() -> str: return secrets.token_urlsafe(32) # 使用示例 random_gen = SecureRandom() print(f"Token: {random_gen.generate_token()}") print(f"Password: {random_gen.generate_password()}") print(f"API Key: {random_gen.generate_api_key()}")

数字签名

数字签名原理

数字签名提供消息认证和不可否认性:

  1. 签名:发送者用私钥对消息哈希签名
  2. 验证:接收者用公钥验证签名
package main import ( "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "encoding/base64" "fmt" "log" ) func GenerateKeyPair() (*rsa.PrivateKey, *rsa.PublicKey, error) { privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, nil, err } return privateKey, &privateKey.PublicKey, nil } func SignMessage(privateKey *rsa.PrivateKey, message []byte) ([]byte, error) { hashed := sha256.Sum256(message) signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed[:]) return signature, err } func VerifySignature(publicKey *rsa.PublicKey, message, signature []byte) bool { hashed := sha256.Sum256(message) err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed[:], signature) return err == nil } func main() { privateKey, publicKey, err := GenerateKeyPair() if err != nil { log.Fatal(err) } message := []byte("Important message to sign") // 签名 signature, err := SignMessage(privateKey, message) if err != nil { log.Fatal(err) } fmt.Printf("Signature: %s\n", base64.StdEncoding.EncodeToString(signature)) // 验证签名 isValid := VerifySignature(publicKey, message, signature) fmt.Printf("Signature valid: %v\n", isValid) }

密钥交换协议

Diffie-Hellman密钥交换

from cryptography.hazmat.primitives.asymmetric import dh from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes import os def generate_dh_parameters(): # 生成DH参数 parameters = dh.generate_parameters(generator=2, key_size=2048) return parameters def generate_dh_keypair(parameters): # 生成密钥对 private_key = parameters.generate_private_key() public_key = private_key.public_key() return private_key, public_key def derive_shared_secret(private_key, peer_public_key): # 计算共享密钥 shared_key = private_key.exchange(peer_public_key) # 使用HKDF派生密钥 hkdf = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'dh key derivation', ) return hkdf.derive(shared_key) # 模拟两方密钥交换 parameters = generate_dh_parameters() # Alice生成密钥对 alice_private, alice_public = generate_dh_keypair(parameters) # Bob生成密钥对 bob_private, bob_public = generate_dh_keypair(parameters) # 双方交换公钥后计算共享密钥 alice_shared = derive_shared_secret(alice_private, bob_public) bob_shared = derive_shared_secret(bob_private, alice_public) # 验证双方计算的共享密钥相同 assert alice_shared == bob_shared print("Shared secret established successfully")

密码学应用

TLS/SSL通信

import ssl import socket def create_secure_context(): context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(certfile="server.crt", keyfile="server.key") context.options |= ssl.OP_NO_TLSv1 # 禁用不安全的TLSv1 context.options |= ssl.OP_NO_TLSv1_1 context.set_ciphers('ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384') return context def start_secure_server(): context = create_secure_context() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind(('0.0.0.0', 443)) sock.listen(5) with context.wrap_socket(sock, server_side=True) as secure_sock: conn, addr = secure_sock.accept() print(f"Connection from {addr}") # 安全通信 data = conn.recv(1024) conn.sendall(b"Secure response")

密码学最佳实践

  1. 使用标准算法:选择经过充分验证的加密算法
  2. 密钥管理:使用密钥管理系统,避免硬编码密钥
  3. 定期更新:定期更换密钥,使用最新的安全协议
  4. 前向保密:使用临时密钥,保护历史通信安全
  5. 避免常见错误
    • 不要使用ECB模式
    • 不要重复使用IV/Nonce
    • 不要使用自定义加密算法
    • 不要忽略证书验证

总结

密码学是信息安全的数学基础,通过合理使用对称加密、非对称加密、哈希函数和数字签名等技术,可以构建安全的通信和数据存储系统。随着量子计算的发展,后量子密码学也成为重要研究方向。掌握密码学原理对于任何从事安全相关工作的人员都至关重要。


发布者: 作者: 转发
评论区 (0)
U