Python Cryptography: Caesar Cipher Implementation
Sure, here's an example of Python code for basic encryption and decryption using the Caesar cipher:\n\npython\ndef encrypt(text, shift):\n encrypted_text = ""\n for char in text:\n if char.isalpha():\n if char.isupper():\n encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)\n else:\n encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)\n else:\n encrypted_text += char\n return encrypted_text\n\ndef decrypt(text, shift):\n decrypted_text = ""\n for char in text:\n if char.isalpha():\n if char.isupper():\n decrypted_text += chr((ord(char) - 65 - shift) % 26 + 65)\n else:\n decrypted_text += chr((ord(char) - 97 - shift) % 26 + 97)\n else:\n decrypted_text += char\n return decrypted_text\n\n# Example usage\nplaintext = "Hello, World!"\nshift = 3\n\nencrypted_text = encrypt(plaintext, shift)\nprint("Encrypted text:", encrypted_text)\n\ndecrypted_text = decrypt(encrypted_text, shift)\nprint("Decrypted text:", decrypted_text)\n\n\nThis code defines two functions encrypt() and decrypt() that use the Caesar cipher algorithm to perform encryption and decryption respectively. The encrypt() function takes a text and shift (number of positions to shift each character) as input and returns the encrypted text. The decrypt() function takes the encrypted text and shift as input and returns the decrypted text.\n\nIn the example usage, the plaintext "Hello, World!" is encrypted using a shift of 3, and then decrypted back to the original plaintext. The output will be:\n\n\nEncrypted text: Khoor, Zruog!\nDecrypted text: Hello, World!\n
原文地址: https://www.cveoy.top/t/topic/pP5p 著作权归作者所有。请勿转载和采集!