Basic Encryption/Decryption Tool Python

👤 Sharing: AI
```python
def encrypt(text, shift):
    """Encrypts a string using a Caesar cipher.

    Args:
        text: The string to encrypt.
        shift: The number of positions to shift each character.

    Returns:
        The encrypted string.
    """
    result = ''
    for char in text:
        if char.isalpha():
            start = ord('a') if char.islower() else ord('A')
            shifted_char = chr((ord(char) - start + shift) % 26 + start)
        elif char.isdigit():
            shifted_char = str((int(char) + shift) % 10)
        else:
            shifted_char = char
        result += shifted_char
    return result


def decrypt(text, shift):
    """Decrypts a string that was encrypted using a Caesar cipher.

    Args:
        text: The string to decrypt.
        shift: The number of positions to shift each character (same as during encryption).

    Returns:
        The decrypted string.
    """
    return encrypt(text, -shift)


if __name__ == '__main__':
    while True:
        print("\nEncryption/Decryption Tool")
        print("1. Encrypt")
        print("2. Decrypt")
        print("3. Exit")

        choice = input("Enter your choice (1/2/3): ")

        if choice == '1':
            text = input("Enter the text to encrypt: ")
            try:
                shift = int(input("Enter the shift value (integer): "))
                encrypted_text = encrypt(text, shift)
                print("Encrypted text:", encrypted_text)
            except ValueError:
                print("Invalid shift value. Please enter an integer.")
        elif choice == '2':
            text = input("Enter the text to decrypt: ")
            try:
                shift = int(input("Enter the shift value (same as during encryption): "))
                decrypted_text = decrypt(text, shift)
                print("Decrypted text:", decrypted_text)
            except ValueError:
                print("Invalid shift value. Please enter an integer.")
        elif choice == '3':
            print("Exiting...")
            break
        else:
            print("Invalid choice. Please enter 1, 2, or 3.")
```
👁️ Viewed: 9

Comments