write pyton code for crypto
Sure, here's an example of Python code for basic encryption and decryption using the Caesar cipher:
def encrypt(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
if char.isupper():
encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)
else:
encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)
else:
encrypted_text += char
return encrypted_text
def decrypt(text, shift):
decrypted_text = ""
for char in text:
if char.isalpha():
if char.isupper():
decrypted_text += chr((ord(char) - 65 - shift) % 26 + 65)
else:
decrypted_text += chr((ord(char) - 97 - shift) % 26 + 97)
else:
decrypted_text += char
return decrypted_text
# Example usage
plaintext = "Hello, World!"
shift = 3
encrypted_text = encrypt(plaintext, shift)
print("Encrypted text:", encrypted_text)
decrypted_text = decrypt(encrypted_text, shift)
print("Decrypted text:", decrypted_text)
This 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.
In 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:
Encrypted text: Khoor, Zruog!
Decrypted text: Hello, World!
``
原文地址: https://www.cveoy.top/t/topic/h7bF 著作权归作者所有。请勿转载和采集!