Python encrypt string with key

Lydia 127 Published: 11/16/2024

Python encrypt string with key

Here's a Python program that can be used to encrypt strings using a key:

def encrypt_string(input_string, key):

encrypted_string = ""

for char in input_string:

if char.isalpha():

ascii_offset = 65 if char.isupper() else 97

encrypted_char = chr((ord(char) - ascii_offset + int(key)) % 26 + ascii_offset)

encrypted_string += encrypted_char

else:

encrypted_string += char

return encrypted_string

def decrypt_string(encrypted_string, key):

decrypted_string = ""

for char in encrypted_string:

if char.isalpha():

ascii_offset = 65 if char.isupper() else 97

decrypted_char = chr((ord(char) - ascii_offset - int(key)) % 26 + ascii_offset)

decrypted_string += decrypted_char

else:

decrypted_string += char

return decrypted_string

example usage:

input_string = "Hello, World! This is a test string."

key = 3

encrypted_string = encrypt_string(input_string, key)

print(f"Encrypted string: {encrypted_string}")

decrypted_string = decrypt_string(encrypted_string, key)

print(f"Decrypted string: {decrypted_string}")

In this program, the encrypt_string function takes an input string and a key as inputs. It then iterates over each character in the input string. If the character is alphabetical (i.e., a letter), it applies the Caesar cipher encryption algorithm to shift the character by the specified key. The decrypt_string function does the opposite: it decrypts the encrypted string back into the original input string.

The example usage shows how you can use this program to encrypt and then decrypt a sample input string using a specific key. In this case, the key is 3, which means that each letter will be shifted three positions forward in the alphabet (or backwards if it's a letter that would otherwise shift past 'z' or 'Z').

Note that this program doesn't handle non-ASCII characters well, and it assumes that all non-alphabetical characters are unchanged. Also, because of the modulo operation used in the encryption and decryption algorithms, the key should be a positive integer less than 26 (i.e., the number of letters in the alphabet) for the encryption to work correctly.

What is the best encryption and decryption algorithm in Python?

I'd be happy to provide you with information on the best encryption and decryption algorithms in Python.

Encryption and decryption are fundamental concepts in computer security. Encryption involves transforming plaintext into ciphertext, making it unreadable without a corresponding key or password. Decryption is the process of converting ciphertext back to its original form.

Python has a wide range of built-in and third-party libraries for encrypting and decrypting data. Here are some of the best encryption algorithms in Python:

AES (Advanced Encryption Standard) Algorithm: The AES algorithm is widely used due to its high security, speed, and simplicity. It uses a variable-length key (128-bit or 256-bit) and supports both CBC (Cipher Block Chaining) and CTR (Counter Mode).

You can use the cryptography library in Python for AES encryption and decryption.

Example:

from cryptography.hazmat.primitives import padding

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

Set up encryption

cipher = Cipher(algorithms.AES(b'your-secret-key'), modes.ECB())

encryptor = cipher.encryptor()

Encrypt data

data_to_encrypt = b"Hello, World!"

ctext = encryptor.update(data_to_encrypt) + encryptor.finalize()

print(f"Encrypted: {ctext}")

Decrypting

decryptor = cipher.decryptor()

ptext = decryptor.update(ctext) + decryptor.finalize()

print(f"Decrypted: {ptext}")

RSA (Rivest-Shamir-Adleman) Algorithm: RSA is a widely used public-key encryption algorithm that is known for its ability to be broken by brute force attacks.

You can use the cryptography library in Python for RSA encryption and decryption.

Example:

from cryptography.hazmat.primitives import serialization, hashes

from cryptography.hazmat.primitives.asymmetric import padding, utils

from cryptography.hazmat.backends import default_backend

Load the public key

public_key = serialization.load_pem_public_key(file_name='your-pub-key.pem', backend=default_backend())

Encrypt data with the public key

data_to_encrypt = b"Hello, World!"

ctext = public_key.encrypt(

padding.OAEP(

mgf=padding.MFG1d(),

algorithm=hashes.SHA256(),

label=None

).encode(data_to_encrypt),

ecdh=True

)

print(f"Encrypted: {ctext}")

Decrypting with the private key

private_key = serialization.load_pem_private_key(file_name='your-priv-key.pem', password=None, backend=default_backend())

ptext = private_key.decrypt(

padding.OAEP(

mgf=padding.MFG1d(),

algorithm=hashes.SHA256(),

label=None

).encode(ctext),

ecdh=True

)

print(f"Decrypted: {ptext}")

ECDSA (Elliptic Curve Digital Signature Algorithm) Algorithm: ECDSA is a digital signature algorithm that uses the elliptic curve cryptosystem.

You can use the cryptography library in Python for ECDSA encryption and decryption.

Example:

from cryptography.hazmat.primitives import hashes

from cryptography.hazmat.primitives.asymmetric import ec

from cryptography.hazmat.primitives.asymmetric import padding

Create a private key

private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())

Sign data with the private key

data_to_sign = b"Hello, World!"

signature = private_key.sign(

hashes.sha256(data_to_sign),

padding.PKCS1v15(),

ec.ECDSAHashAlgorithm.SHA256()

)

print(f"Signature: {signature}")

Verify signature with the public key

public_key = ec.SECP256R1().generate_public_key(private_key.public_key())

is_valid = public_key.verify(

hashes.sha256(data_to_sign),

padding.PKCS1v15(),

signature,

ec.ECDSAHashAlgorithm.SHA256()

)

print(f"Signature is {('valid' if is_valid else 'invalid')}")

PGP (Pretty Good Privacy) Algorithm: PGP is a popular open-source encryption algorithm that uses IDEA, 3DES, and AES algorithms.

You can use the cryptography library in Python for PGP encryption and decryption.

Example:

from cryptography.hazmat.primitives import hashes

from cryptography.hazmat.primitives.asymmetric import padding

Create a private key

private_key = serialization.load_pem_private_key(file_name='your-priv-key.pem', password=None, backend=default_backend())

Encrypt data with the public key

data_to_encrypt = b"Hello, World!"

ctext = private_key.encrypt(

data_to_encrypt,

ecdh=True

)

print(f"Encrypted: {ctext}")

Decrypting with the private key

ptext = private_key.decrypt(

ctext,

ecdh=True

)

print(f"Decrypted: {ptext}")

XChaCha20 and Poly1305 Algorithm: XChaCha20 is a high-speed encryption algorithm that uses a 256-bit key, while Poly1305 is a fast and secure message authentication code.

You can use the cryptography library in Python for XChaCha20 and Poly1305 encryption and decryption.

Example:

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Set up encryption

cipher = Cipher(algorithms.XChaCha20(b'your-secret-key'), modes.GCMIV(b'your-iv'))

encryptor = cipher.encryptor()

Encrypt data

data_to_encrypt = b"Hello, World!"

ctext = encryptor.update(data_to_encrypt) + encryptor.finalize()

print(f"Encrypted: {ctext}")

Decrypting

decryptor = cipher.decryptor()

ptext = decryptor.update(ctext) + decryptor.finalize()

print(f"Decrypted: {ptext}")

Remember that these are just a few examples, and there are many other encryption algorithms available in Python. The best algorithm for you will depend on your specific use case and security requirements.

Also, it is essential to handle the keys securely by storing them encrypted or using secure storage options like a Hardware Security Module (HSM).