可以使用簡(jiǎn)單的凱撒密碼來(lái)對(duì)字符串進(jìn)行加密。以下是一個(gè)使用凱撒密碼實(shí)現(xiàn)字符串加密和解密的示例代碼:
def encrypt(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
if char.islower():
encrypted_text += chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
elif char.isupper():
encrypted_text += chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
else:
encrypted_text += char
return encrypted_text
def decrypt(encrypted_text, shift):
return encrypt(encrypted_text, -shift)
# 測(cè)試加密和解密
text = "Hello, World!"
shift = 3
encrypted_text = encrypt(text, shift)
decrypted_text = decrypt(encrypted_text, shift)
print("Original text:", text)
print("Encrypted text:", encrypted_text)
print("Decrypted text:", decrypted_text)
在上面的示例代碼中,encrypt
函數(shù)將輸入的字符串進(jìn)行加密,decrypt
函數(shù)將加密后的字符串進(jìn)行解密。您可以根據(jù)需要更改shift
的值來(lái)改變加密和解密的偏移量。