用Python加密字符串成纯数字与解密方式附源码
时间: 2024-12-28 19:31:38 浏览: 49
在Python中,我们可以使用简单的数学运算如位移(shift操作)或异或(XOR)来将字符串转换成看起来像数字的序列,但实际上这并不是真正的加密,而是编码。这是一种常见的伪加密技术,因为这种变换可以很容易逆向。这里有一个基础的示例,使用异或(XOR)对字符串字符进行处理:
```python
def encode_string_to_numbers(s):
encrypted = ''.join(chr(ord(c) ^ ord('a')) for c in s)
return encrypted
def decode_numbers_to_string(encrypted):
original = ''.join(chr(ord(c) ^ ord('a')) for c in encrypted)
return original
# 示例
plaintext = "Hello, World!"
encoded = encode_string_to_numbers(plaintext)
print("Encoded:", encoded)
decoded = decode_numbers_to_string(encoded)
print("Decoded:", decoded)
```
在这个例子中,我们假设原始字母表'a'作为我们的“密钥”,但实际上这个过程非常简单,不提供真正的保密性。
请注意,这仅用于演示目的,实际加密会涉及更复杂的算法,例如AES、RSA等,并且需要专业的库支持才能保证安全性。
相关问题
python压缩加密解密exec
### 文件处理与安全操作
在 Python 中可以利用多种库来实现文件的压缩、加密以及解密功能。对于这些需求,`zlib` 库用于压缩和解压数据;而 `cryptography` 或者更轻量级的选择如 `PyCryptodome` 可以为用户提供强大的加/解密能力。
#### 压缩与解压缩
为了对文件内容进行压缩并随后能够恢复原始状态,下面展示了怎样使用内置模块 `gzip` 来完成这项工作:
```python
import gzip
from pathlib import Path
def compress_file(input_path, output_path):
with open(input_path, 'rb') as f_in:
with gzip.open(output_path, 'wb') as f_out:
f_out.writelines(f_in)
def decompress_file(gzip_path, output_path):
with gzip.open(gzip_path, 'rb') as f_in:
with open(output_path, 'wb') as f_out:
f_out.write(f_in.read())
```
上述代码片段定义了两个函数分别用来压缩和解压给定路径下的文件[^1]。
#### 加密与解密
当涉及到敏感信息保护时,则需要引入专门设计的安全算法来进行加密处理。这里采用 PyCryptodome 库中的 AES 对称加密方式作为例子展示如何加密和平稳地解密一段消息或整个文件的内容:
安装所需的包可以通过 pip 安装命令:`pip install pycryptodomex`.
接下来是具体的编码实践部分:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64encode, b64decode
import hashlib
class AesEncryptionTool:
def __init__(self, key):
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw_data):
cipher = AES.new(self.key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(raw_data.encode('utf-8'), AES.block_size))
iv = b64encode(cipher.iv).decode('utf-8')
ciphertext = b64encode(ct_bytes).decode('utf-8')
return {'iv': iv, 'ciphertext': ciphertext}
def decrypt(self, enc_dict):
try:
cipher = AES.new(
self.key,
AES.MODE_CBC,
b64decode(enc_dict['iv'])
)
pt = unpad(
cipher.decrypt(b64decode(enc_dict['ciphertext'])),
AES.block_size
).decode('utf-8')
return pt
except (ValueError, KeyError):
print("Incorrect decryption")
raise
```
这段脚本创建了一个名为 `AesEncryptionTool` 的类实例化对象接受一个密码串参数初始化,并提供了两种公共方法——`encrypt()` 和 `decrypt()`. 这些方法允许使用者轻松地将任意长度的数据转换成经过AES CBC模式加密的形式存储起来,在必要时候又可以从这种形式还原回来[^2].
#### 结合 exec 动态执行
如果希望进一步增强安全性的同时还能动态加载和运行被保护过的Python源码,则可以在之前的基础上加入额外一层防护措施即先将其转义为字符串表示后再调用内建函数 `exec()` :
```python
aes_tool = AesEncryptionTool('your-secret-key')
source_code = """
print("This is a secret message!")
"""
encrypted_source_info = aes_tool.encrypt(source_code)
compressed_and_encoded = zlib.compress(encrypted_source_info.__str__().encode())
# Save compressed and encrypted code to file or send over network...
recovered_str = zlib.decompress(compressed_and_encoded).decode()
decrypted_source_info = eval(recovered_str) # Convert string back into dictionary format.
final_decoded_script = aes_tool.decrypt(decrypted_source_info)
exec(final_decoded_script)
```
此段示例说明了完整的流程:从最初编写的一段简单的打印语句开始直到最后成功解析并执行它为止。值得注意的是实际应用中应当谨慎对待任何来自外部未经验证就准备被执行的代码片段以防潜在风险[^3].
阅读全文
相关推荐


















