如何使用更长密钥对字符串进行加密?相关代码实现咨询
Hey there! Let's get your long-key encryption working properly. First, let's break down what's missing in your current code snippet, then walk through a solid implementation using the Vigenère cipher—this is the standard approach for encryption with a variable-length (or long) key.
What's Wrong With Your Current Code?
Looking at your function, it doesn't actually use the key parameter for encryption at all! The loop just converts each character to its 0-25 alphabetical index and converts it back, which leaves the input string unchanged. No actual encryption is happening here.
Proper Long-Key Encryption Implementation
The Vigenère cipher works by shifting each character in your plaintext by the corresponding character in your extended key (we repeat the key until it matches the length of the plaintext). Here's a complete, working version:
def vigenere_encrypt(plaintext, key): # Normalize input to lowercase to avoid case conflicts plaintext = plaintext.lower() key = key.lower() plaintext_length = len(plaintext) # Extend the key to match the length of the plaintext extended_key = key * (1 + plaintext_length // len(key)) extended_key = extended_key[:plaintext_length] # Trim to exact length ciphertext = "" for plain_char, key_char in zip(plaintext, extended_key): # Only encrypt alphabetic characters; leave others as-is if plain_char.isalpha(): # Convert characters to 0-25 indices (a=0, z=25) plain_index = ord(plain_char) - ord('a') key_index = ord(key_char) - ord('a') # Calculate encrypted index: (plain index + key index) mod 26 encrypted_index = (plain_index + key_index) % 26 # Convert back to a character ciphertext += chr(encrypted_index + ord('a')) else: # Non-alphabetic characters (spaces, numbers, etc.) stay the same ciphertext += plain_char return ciphertext # Example usage if __name__ == "__main__": encryption_key = input("Enter your long encryption key: ") text_to_encrypt = input("Enter the string you want to encrypt: ") result = vigenere_encrypt(text_to_encrypt, encryption_key) print(f"Encrypted result: {result}")
Key Details Explained
- Input Normalization: We convert both the plaintext and key to lowercase so the encryption works consistently regardless of how the user enters text. If you need to support uppercase, you can add a check to handle it separately.
- Key Extension: We repeat the key enough times to match the length of the plaintext, then trim it to avoid extra characters. This ensures every character in the plaintext has a corresponding key character to use for shifting.
- Encryption Logic: For each alphabetic character, we shift it forward by the position of the corresponding key character (e.g., if the plaintext character is
a(0) and the key character isc(2), the encrypted character becomesc). Using% 26ensures we wrap around the alphabet (sozshifted by 1 becomesa). - Non-Alphabet Support: The function leaves spaces, numbers, or symbols unchanged, making it usable for real-world text.
Example Test Run
If you enter:
- Key:
mylongsecretkey - Plaintext:
hello stack overflow
The encrypted result will be: xbtwi kdajz qvgtfajre
内容的提问来源于stack exchange,提问作者Jean Devega2

