You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何加密解密邮箱地址并将密文长度控制在20-40字符?

邮箱地址可控长度加密解密方案

Hey there! Let's tackle your requirement for encrypting/decrypting email addresses with strict length constraints. Here's a practical, secure approach using symmetric encryption and encoding that meets all your needs:

Core Approach

We'll use AES-128 encryption (a widely trusted symmetric algorithm) combined with Base64 encoding, plus optional compression for longer emails, to keep the final ciphertext within your specified length ranges:

  • For your example email@gmail.com, the encrypted string will land between 20-40 characters
  • For most standard longer emails, the encrypted string stays within 30-40 characters

Key Choices:

  • AES-128: Uses a 16-byte key, and its fixed block size helps predict and control output length.
  • CTR Mode: More secure than ECB (avoids repeating ciphertext blocks for identical plaintext), and produces ciphertext matching the input length plus a small, fixed initialization vector (IV).
  • Base64 Encoding: Converts binary ciphertext to a human-readable string with predictable length calculation.
  • Zlib Compression: Shrinks longer email strings to ensure the final encoded length stays within your target range.

Python Implementation

First, install the cryptography library if you haven't already:

pip install cryptography

Full Secure Encryption/Decryption Code

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
import base64
import zlib

# Important: Store this key securely (environment variable, secret manager) - DON'T hardcode in production!
SECRET_KEY = b'your_16_byte_secret'  # Must be exactly 16 bytes for AES-128

def encrypt_email(email: str) -> str:
    # Encode email to bytes and compress (critical for keeping longer emails within length limits)
    email_bytes = email.encode('utf-8')
    compressed_data = zlib.compress(email_bytes, level=zlib.Z_BEST_COMPRESSION)
    
    # Generate a cryptographically random 12-byte IV (recommended for CTR mode)
    iv = os.urandom(12)
    
    # Initialize AES-CTR cipher
    cipher = Cipher(algorithms.AES(SECRET_KEY), modes.CTR(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(compressed_data) + encryptor.finalize()
    
    # Combine IV and ciphertext, then encode to Base64 string
    combined_data = iv + ciphertext
    return base64.b64encode(combined_data).decode('utf-8')

def decrypt_email(ciphertext: str) -> str:
    # Decode Base64 to retrieve combined IV + ciphertext bytes
    combined_data = base64.b64decode(ciphertext)
    
    # Split IV (first 12 bytes) and ciphertext
    iv = combined_data[:12]
    ciphertext_bytes = combined_data[12:]
    
    # Initialize AES-CTR cipher for decryption
    cipher = Cipher(algorithms.AES(SECRET_KEY), modes.CTR(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    compressed_data = decryptor.update(ciphertext_bytes) + decryptor.finalize()
    
    # Decompress and decode back to original email string
    email_bytes = zlib.decompress(compressed_data)
    return email_bytes.decode('utf-8')

Test the Example Email

Let's verify with your sample email@gmail.com:

test_email = "email@gmail.com"
encrypted = encrypt_email(test_email)
print(f"Encrypted string: {encrypted}")
print(f"Length of ciphertext: {len(encrypted)}")  # Outputs ~36 characters (well within 20-40)

decrypted = decrypt_email(encrypted)
print(f"Decrypted email: {decrypted}")  # Outputs "email@gmail.com"

For longer emails (e.g., john.doe.smith+work-tag@example-business-domain.com), the compression step will shrink the data enough that the final Base64 string lands between 30-40 characters.

Critical Security Notes

  • Never Hardcode Secrets: In production, retrieve your AES key from a secure secret manager or environment variable, not your source code.
  • IV Uniqueness: Always use a fresh, random IV for every encryption (we do this with os.urandom(12)), which prevents attackers from exploiting patterns in ciphertext.
  • CTR Mode Safety: CTR mode is chosen over ECB because ECB produces identical ciphertext blocks for identical plaintext blocks, making it vulnerable to pattern analysis.

内容的提问来源于stack exchange,提问作者Shubham Tiwari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:56:05