Python字符串解密案例如何还原内容

wen python案例 26

本文目录导读:

Python字符串解密案例如何还原内容

  1. Base64编码解密
  2. Caesar密码(凯撒密码)
  3. XOR加密解密
  4. Rot13加密解密
  5. 异或位运算解密
  6. 简单替换密码解密
  7. 自动检测解密方法
  8. 实用解密函数封装
  9. 常见问题处理

我来为你介绍几种Python字符串解密的常见案例和还原方法。

Base64编码解密

import base64
# 加密字符串
encrypted_str = "SGVsbG8gV29ybGQh"
# Base64解码
decoded_str = base64.b64decode(encrypted_str).decode('utf-8')
print(f"解密结果: {decoded_str}")  # 输出: Hello World!

Caesar密码(凯撒密码)

def caesar_decrypt(text, shift):
    result = ""
    for char in text:
        if char.isalpha():
            # 计算偏移后的字符
            if char.isupper():
                result += chr((ord(char) - ord('A') - shift) % 26 + ord('A'))
            else:
                result += chr((ord(char) - ord('a') - shift) % 26 + ord('a'))
        else:
            result += char
    return result
# 示例
encrypted = "KHOOR ZRUOG"
# 尝试所有可能的偏移量
for shift in range(1, 26):
    decrypted = caesar_decrypt(encrypted, shift)
    print(f"偏移{shift:2d}: {decrypted}")

XOR加密解密

def xor_decrypt(encrypted_str, key):
    result = []
    for i, char in enumerate(encrypted_str):
        # XOR操作(可逆)
        decrypted_char = chr(ord(char) ^ ord(key[i % len(key)]))
        result.append(decrypted_char)
    return ''.join(result)
# 示例
key = "secret_key"
encrypted = "加密后的字符串"
decrypted = xor_decrypt(encrypted, key)
print(f"解密结果: {decrypted}")

Rot13加密解密

import codecs
# Rot13加密解密(同一函数)
encrypted = "Uryyb Jbeyq"
decrypted = codecs.decode(encrypted, 'rot_13')
print(f"解密结果: {decrypted}")  # 输出: Hello World

异或位运算解密

def bitwise_xor_decrypt(encrypted_bytes, key):
    return bytes([b ^ key for b in encrypted_bytes])
# 示例
encrypted_data = b'\x1a\x15\x0e\x1f\x08'  # 假设这是加密数据
key = 0x4A  # 密钥
decrypted = bitwise_xor_decrypt(encrypted_data, key)
print(f"解密结果: {decrypted.decode('utf-8', errors='ignore')}")

简单替换密码解密

def substitution_decrypt(encrypted, mapping):
    result = []
    for char in encrypted:
        if char in mapping:
            result.append(mapping[char])
        else:
            result.append(char)
    return ''.join(result)
# 示例映射表(字符替换)
substitution_map = {
    '!': 'H',
    '@': 'e',
    '#': 'l',
    '$': 'o',
    '%': 'W',
    '^': 'r',
    '&': 'd'
}
encrypted = "!@##$%^&"
decrypted = substitution_decrypt(encrypted, substitution_map)
print(f"解密结果: {decrypted}")

自动检测解密方法

import base64
import codecs
def auto_detect_decrypt(encrypted_str):
    """自动尝试多种解密方法"""
    # Base64检测
    try:
        result = base64.b64decode(encrypted_str).decode('utf-8')
        if result.isprintable():
            print(f"Base64解密: {result}")
            return
    except:
        pass
    # Rot13检测
    try:
        result = codecs.decode(encrypted_str, 'rot_13')
        print(f"Rot13解密: {result}")
        return
    except:
        pass
    # Caesar密码暴力破解
    for shift in range(1, 26):
        result = caesar_decrypt(encrypted_str, shift)
        if ' ' in result or 'the' in result.lower():
            print(f"Caesar密码(偏移{shift}): {result}")
            return
    print("无法自动解密")
# 使用示例
encrypted_list = [
    "SGVsbG8gV29ybGQh",
    "Uryyb Jbeyq",
    "KHOOR ZRUOG"
]
for encrypted in encrypted_list:
    print(f"\n尝试解密: {encrypted}")
    auto_detect_decrypt(encrypted)

实用解密函数封装

class StringDecryptor:
    def __init__(self, algorithm='base64'):
        self.algorithm = algorithm
        self.methods = {
            'base64': self._base64_decrypt,
            'rot13': self._rot13_decrypt,
            'caesar': self._caesar_decrypt,
            'xor': self._xor_decrypt
        }
    def decrypt(self, encrypted_text, **kwargs):
        if self.algorithm in self.methods:
            return self.methods[self.algorithm](encrypted_text, **kwargs)
        else:
            raise ValueError(f"不支持的解密算法: {self.algorithm}")
    def _base64_decrypt(self, text):
        return base64.b64decode(text).decode('utf-8')
    def _rot13_decrypt(self, text):
        return codecs.decode(text, 'rot_13')
    def _caesar_decrypt(self, text, shift=3):
        return caesar_decrypt(text, shift)
    def _xor_decrypt(self, text, key='key'):
        return xor_decrypt(text, key)
# 使用示例
decryptor = StringDecryptor('base64')
result = decryptor.decrypt("SGVsbG8gV29ybGQh")
print(f"解密结果: {result}")

常见问题处理

# 处理编码问题
def safe_decode(byte_data, encoding='utf-8'):
    try:
        return byte_data.decode(encoding)
    except UnicodeDecodeError:
        # 尝试其他编码
        for enc in ['gbk', 'latin-1', 'ascii']:
            try:
                return byte_data.decode(enc)
            except:
                continue
        return byte_data.decode('utf-8', errors='ignore')
# 处理十六进制字符串
def hex_to_string(hex_str):
    return bytes.fromhex(hex_str).decode('utf-8', errors='ignore')
# 示例
hex_data = "48656c6c6f20576f726c6421"
print(f"十六进制解密: {hex_to_string(hex_data)}")

这些方法覆盖了大多数常见的字符串加密场景,使用时需要根据实际情况选择合适的解密方法,并注意处理编码和异常情况。

抱歉,评论功能暂时关闭!