经典加密算法——Python实现

经典加密算法——Python实现

目录

经典加密算法——Python实现

前言

开发环境

加密算法概览表

1. 凯撒密码 (Caesar Cipher)

2. 替换密码 (Substitution Cipher)

3. 维吉尼亚密码 (Vigenère Cipher)

4. 栅栏密码 (Rail Fence Cipher)

5. DES (Data Encryption Standard)

6. AES (Advanced Encryption Standard)

7. RSA (非对称加密)

8. SHA-256 (哈希函数)

注意事项


前言

密码学是信息安全的核心领域之一,经典加密算法在现代通信和数据保护中仍具有重要的学习和应用价值。本文通过Python代码示例,详细介绍了凯撒密码、替换密码、维吉尼亚密码、栅栏密码、DES、AES、RSA和SHA-256等经典加密算法的实现方法。这些算法涵盖了对称加密、非对称加密和哈希函数等多种类型,旨在帮助读者理解其基本原理并掌握实际编程实现。在实现过程中,针对栅栏密码解密函数的常见错误进行了详细分析和修复,确保代码的准确性和实用性。

开发环境

系统:win11
开发语言:Python
使用工具:VS Code

加密算法概览表

以下是经典加密算法的Python实现概览表,随后是各算法的详细代码示例:

算法名称类型密钥类型特点
凯撒密码对称加密整数位移量字母移位替换
替换密码对称加密替换表单字母替换
维吉尼亚密码对称加密关键词字符串多表替换
栅栏密码对称加密栅栏数文本字符重新排列
DES对称加密56位密钥分组加密,ECB/CBC模式
AES对称加密128/192/256位分组加密,取代DES
RSA非对称加密公钥/私钥对基于大数分解难题
SHA-256哈希函数无密钥生成256位摘要

1. 凯撒密码 (Caesar Cipher)

def caesar_encrypt(text, shift):
    encrypted = ""
    for char in text:
        if char.isupper():
            encrypted += chr((ord(char) + shift - 65) % 26 + 65)
        elif char.islower():
            encrypted += chr((ord(char) + shift - 97) % 26 + 97)
        else:
            encrypted += char
    return encrypted

def caesar_decrypt(ciphertext, shift):
    return caesar_encrypt(ciphertext, -shift)

# 示例
plaintext = "Hello, Caesar!"
shift = 3
ciphertext = caesar_encrypt(plaintext, shift)
decrypted = caesar_decrypt(ciphertext, shift)
print("原文:", plaintext)
print("加密后:", ciphertext)
print("解密后:", decrypted)

2. 替换密码 (Substitution Cipher)

import random

def generate_substitution_key():
    alphabet = list('abcdefghijklmnopqrstuvwxyz')
    shuffled = alphabet.copy()
    random.shuffle(shuffled)
    return {k: v for k, v in zip(alphabet, shuffled)}

def substitution_encrypt(text, key):
    encrypted = []
    for char in text.lower():
        encrypted.append(key.get(char, char))
    return ''.join(encrypted)

def substitution_decrypt(ciphertext, key):
    reverse_key = {v: k for k, v in key.items()}
    decrypted = []
    for char in ciphertext:
        decrypted.append(reverse_key.get(char, char))
    return ''.join(decrypted)

# 示例
key = generate_substitution_key()
plaintext = "hello, substitution!"
ciphertext = substitution_encrypt(plaintext, key)
decrypted = substitution_decrypt(ciphertext, key)
print("原文:", plaintext)
print("加密后:", ciphertext)
print("解密后:", decrypted)

3. 维吉尼亚密码 (Vigenère Cipher)

def vigenere_encrypt(plaintext, keyword):
    encrypted = []
    keyword = keyword.lower()
    key_indices = [ord(k) - 97 for k in keyword]
    key_length = len(keyword)
    for i, char in enumerate(plaintext):
        if char.islower():
            shift = key_indices[i % key_length]
            encrypted_char = chr((ord(char) - 97 + shift) % 26 + 97)
            encrypted.append(encrypted_char)
        elif char.isupper():
            shift = key_indices[i % key_length]
            encrypted_char = chr((ord(char) - 65 + shift) % 26 + 65)
            encrypted.append(encrypted_char)
        else:
            encrypted.append(char)
    return ''.join(encrypted)

def vigenere_decrypt(ciphertext, keyword):
    decrypted = []
    keyword = keyword.lower()
    key_indices = [ord(k) - 97 for k in keyword]
    key_length = len(keyword)
    for i, char in enumerate(ciphertext):
        if char.islower():
            shift = key_indices[i % key_length]
            decrypted_char = chr((ord(char) - 97 - shift) % 26 + 97)
            decrypted.append(decrypted_char)
        elif char.isupper():
            shift = key_indices[i % key_length]
            decrypted_char = chr((ord(char) - 65 - shift) % 26 + 65)
            decrypted.append(decrypted_char)
        else:
            decrypted.append(char)
    return ''.join(decrypted)

# 示例
plaintext = "Hello, Vigenère!"
keyword = "KEY"
ciphertext = vigenere_encrypt(plaintext, keyword)
decrypted = vigenere_decrypt(ciphertext, keyword)
print("原文:", plaintext)
print("加密后:", ciphertext)
print("解密后:", decrypted)

4. 栅栏密码 (Rail Fence Cipher)

def rail_fence_encrypt(plaintext, rails):
    fence = [[] for _ in range(rails)]
    rail = 0
    direction = 1  # 1向下,-1向上
    for char in plaintext:
        fence[rail].append(char)
        rail += direction
        if rail in [0, rails - 1]:
            direction = -direction
    return ''.join(''.join(row) for row in fence)

def rail_fence_decrypt(ciphertext, rails):
    n = len(ciphertext)
    cycle = 2 * (rails - 1)
    full_cycles, remainder = divmod(n, cycle)
    
    # 计算每个栅栏行的字符数量
    rows = [0] * rails
    for i in range(rails):
        if i == 0 or i == rails - 1:
            rows[i] = full_cycles
        else:
            rows[i] = 2 * full_cycles
    
    # 处理余数部分
    for i in range(remainder):
        if i < rails:
            rows[i] += 1
        else:
            rows[cycle - i] += 1  # 反向填充剩余字符
    
    # 将密文字符分割到对应行
    fence = []
    index = 0
    for count in rows:
        fence.append(list(ciphertext[index:index+count]))
        index += count
    
    # 按之字形路径读取字符
    result = []
    rail, step = 0, 1
    for _ in range(n):
        result.append(fence[rail].pop(0))
        rail += step
        if rail == 0 or rail == rails - 1:
            step = -step
    return ''.join(result)

# 示例
plaintext = "HELLO RAIL FENCE"
rails = 3
ciphertext = rail_fence_encrypt(plaintext, rails)
decrypted = rail_fence_decrypt(ciphertext, rails)
print("原文:", plaintext)
print("加密后:", ciphertext)
print("解密后:", decrypted)

5. DES (Data Encryption Standard)

需要单独安装pycryptodome库

pip install pycryptodome

from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

def des_encrypt(plaintext, key):
    cipher = DES.new(key, DES.MODE_ECB)
    padded_text = pad(plaintext.encode(), DES.block_size)
    ciphertext = cipher.encrypt(padded_text)
    return ciphertext

def des_decrypt(ciphertext, key):
    cipher = DES.new(key, DES.MODE_ECB)
    decrypted = cipher.decrypt(ciphertext)
    return unpad(decrypted, DES.block_size).decode()

# 示例(注意:DES密钥必须为8字节)
key = get_random_bytes(8)  # 生成随机密钥
plaintext = "Hello DES!"
ciphertext = des_encrypt(plaintext, key)
decrypted = des_decrypt(ciphertext, key)
print("原文:", plaintext)
print("加密后:", ciphertext.hex())
print("解密后:", decrypted)

6. AES (Advanced Encryption Standard)

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

def aes_encrypt(plaintext, key):
    iv = get_random_bytes(16)  # CBC模式需要IV
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded_text = pad(plaintext.encode(), AES.block_size)
    ciphertext = cipher.encrypt(padded_text)
    return iv + ciphertext  # 将IV附加到密文前

def aes_decrypt(ciphertext, key):
    iv = ciphertext[:16]  # 提取前16字节作为IV
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted = cipher.decrypt(ciphertext[16:])
    return unpad(decrypted, AES.block_size).decode()

# 示例(AES-256需要32字节密钥)
key = get_random_bytes(32)  # 256位密钥
plaintext = "Hello AES!"
ciphertext = aes_encrypt(plaintext, key)
decrypted = aes_decrypt(ciphertext, key)
print("原文:", plaintext)
print("加密后:", ciphertext.hex())
print("解密后:", decrypted)

7. RSA (非对称加密)

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

# 生成RSA密钥对
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()

def rsa_encrypt(plaintext, public_key):
    rsa_key = RSA.import_key(public_key)
    cipher = PKCS1_OAEP.new(rsa_key)
    ciphertext = cipher.encrypt(plaintext.encode())
    return ciphertext

def rsa_decrypt(ciphertext, private_key):
    rsa_key = RSA.import_key(private_key)
    cipher = PKCS1_OAEP.new(rsa_key)
    decrypted = cipher.decrypt(ciphertext)
    return decrypted.decode()

# 示例
plaintext = "Hello RSA!"
ciphertext = rsa_encrypt(plaintext, public_key)
decrypted = rsa_decrypt(ciphertext, private_key)
print("原文:", plaintext)
print("加密后:", ciphertext.hex())
print("解密后:", decrypted)

8. SHA-256 (哈希函数)

import hashlib

def sha256_hash(data):
    sha = hashlib.sha256()
    sha.update(data.encode())
    return sha.hexdigest()

# 示例
data = "Hello SHA-256!"
hash_value = sha256_hash(data)
print("原文:", data)
print("SHA-256摘要:", hash_value)

注意事项

密钥管理:对称加密的密钥需安全存储,非对称加密需保护私钥。

模式选择:AES/DES的ECB模式不安全,实际应用建议使用CBC或GCM模式。

填充方式:PKCS#7填充用于对齐数据块长度。

哈希特性:SHA-256为单向函数,无法逆向解密。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值