溫馨提示×

python字符串簡單加密怎么實現

小億
128
2024-04-08 10:55:39
欄目: 編程語言

可以使用簡單的凱撒密碼來對字符串進行加密。以下是一個使用凱撒密碼實現字符串加密和解密的示例代碼:

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)

# 測試加密和解密
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函數將輸入的字符串進行加密,decrypt函數將加密后的字符串進行解密。您可以根據需要更改shift的值來改變加密和解密的偏移量。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女