AES
ECB 模式
python3 加密 解密
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
def encrypt_AES_ECB(text, key):
cipher = AES.new(key.encode(), AES.MODE_ECB)
padded_text = pad(text.encode(), AES.block_size, style='pkcs7')
ciphertext = cipher.encrypt(padded_text)
return base64.b64encode(ciphertext).decode()
def decrypt_AES_ECB(ciphertext, key):
cipher = AES.new(key.encode(), AES.MODE_ECB)
ciphertext = base64.b64decode(ciphertext)
decrypted_text = cipher.decrypt(ciphertext)
return unpad(decrypted_text, AES.block_size, style='pkcs7').decode()
# 密码和明文
key = '1234567891234569'
# 加密
encrypted_text = encrypt_AES_ECB('4', key)
print(f'Encrypted text: {encrypted_text}')
# 解密
decrypted_text = decrypt_AES_ECB('LRjAo6Nz8zT6jC3c0vv6Mw==', key)
print(f'Decrypted text: {decrypted_text}')
RSA 对称加密
python3
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# 生成 RSA 密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# 将密钥序列化为 PEM 格式
private_key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# 加密函数
def encrypt_RSA(public_key, plaintext):
ciphertext = public_key.encrypt(
plaintext.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext
# 解密函数
def decrypt_RSA(private_key, ciphertext):
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext.decode()
# 明文
plaintext = 'Hello, RSA!'
# 加密
ciphertext = encrypt_RSA(public_key, plaintext)
print(f'Encrypted text: {ciphertext}')
# 解密
decrypted_text = decrypt_RSA(private_key, ciphertext)
print(f'Decrypted text: {decrypted_text}')
时间戳
python3
import time
# 生成 13 位时间戳
def generate_13_bit_timestamp():
return int(time.time() * 1000)
# 解析 13 位时间戳
def parse_13_bit_timestamp(timestamp):
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp / 1000))
# 生成 10 位时间戳
def generate_10_bit_timestamp():
return int(time.time())
# 解析 10 位时间戳
def parse_10_bit_timestamp(timestamp):
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
# 生成和解析 13 位时间戳
timestamp_13 = generate_13_bit_timestamp()
print(f'Generated 13-bit timestamp: {timestamp_13}')
print(f'Parsed 13-bit timestamp: {parse_13_bit_timestamp(timestamp_13)}')
# 生成和解析 10 位时间戳
timestamp_10 = generate_10_bit_timestamp()
print(f'Generated 10-bit timestamp: {timestamp_10}')
print(f'Parsed 10-bit timestamp: {parse_10_bit_timestamp(timestamp_10)}')