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

开发支持多位数密钥的凯撒(Julius Caesar)密码加解密应用的技术需求问询

Got it, let's walk through building this custom Caesar cipher app that meets your requirements. I'll break down the core logic, share a working Python implementation, and explain each step so you can adapt it to your preferred language.

Core Requirements Recap

First, let's restate the key rules to make sure we're aligned:

  • Key Rules: The secret key must be a number with 4 or more digits. We'll split it into a list of individual integers (e.g., 1234 becomes [1,2,3,4]).
  • Shift Logic: For encryption/decryption, we cycle through this digit list to shift each character in the input text. The first character uses the first digit, second uses the second, and so on—once we reach the end of the digit list, we loop back to the start.
  • Character Handling: We should preserve non-alphabet characters (spaces, punctuation, numbers) as-is, only shifting letters while maintaining their case (uppercase stays uppercase, lowercase stays lowercase).
Step-by-Step Implementation Approach
  1. Key Validation & Processing:

    • Check that the input key is a string/number with at least 4 digits. If not, throw an error or prompt the user for a valid key.
    • Convert the key into a list of integers (e.g., str(12345) → ['1','2','3','4','5'] → [1,2,3,4,5]).
  2. Character Shift Function:
    For each character in the input text:

    • If it's an uppercase letter: Calculate the shifted character using (ord(char) - ord('A') + shift_amount) % 26 + ord('A') (for encryption; subtract shift_amount for decryption).
    • If it's a lowercase letter: Use (ord(char) - ord('a') + shift_amount) % 26 + ord('a') (again, subtract for decryption).
    • If it's not a letter, leave it unchanged.
  3. Cycle Through Key Digits:
    Use the index of the current character modulo the length of the key digit list to get the correct shift amount for each character. For example, the 5th character (index 4) with a 4-digit key uses 4 % 4 = 0 → the first digit in the list.

Working Code Example (Python)

Here's a complete implementation that handles encryption, decryption, and key validation:

def validate_key(key):
    # Convert key to string and check it's 4+ digits only
    key_str = str(key)
    if len(key_str) < 4 or not key_str.isdigit():
        raise ValueError("Key must be a number with 4 or more digits")
    return [int(digit) for digit in key_str]

def custom_caesar(text, key, encrypt=True):
    key_digits = validate_key(key)
    key_length = len(key_digits)
    result = []
    
    for idx, char in enumerate(text):
        shift = key_digits[idx % key_length]
        if not encrypt:
            shift = -shift  # Reverse shift for decryption
        
        if char.isupper():
            shifted = (ord(char) - ord('A') + shift) % 26
            result.append(chr(shifted + ord('A')))
        elif char.islower():
            shifted = (ord(char) - ord('a') + shift) % 26
            result.append(chr(shifted + ord('a')))
        else:
            # Non-alphabet characters stay the same
            result.append(char)
    
    return ''.join(result)

# Example usage
if __name__ == "__main__":
    input_text = "don't touch my spaghetti"
    secret_key = 1234
    
    encrypted = custom_caesar(input_text, secret_key, encrypt=True)
    print(f"Encrypted: {encrypted}")
    # Output: "epq'v vqxea qa vxeviiwxj"
    
    decrypted = custom_caesar(encrypted, secret_key, encrypt=False)
    print(f"Decrypted: {decrypted}")
    # Output: "don't touch my spaghetti"
Notes for Adaptation
  • Case Sensitivity: The code preserves case, but you can modify it to ignore case if needed (convert all to lowercase/uppercase before shifting, then restore).
  • Non-Latin Characters: If you need to support other alphabets, adjust the base ordinal values (e.g., ord('À') for French accented characters) and the modulus value (match the number of letters in the target alphabet).
  • UI Integration: If you're building a GUI or web app, wrap this logic in a user-friendly interface—add input fields for text, key, and buttons for encrypt/decrypt.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 01:32:38