Junior
Provide an example of asymmetric encryption.
sobes.tech AI
Answer from AI
Asymmetric encryption uses a pair of keys: a public key and a private key. An example is the RSA algorithm. The public key is used for encrypting data, and the private key is used for decrypting it. This allows secure communication without the need to exchange a secret key beforehand.
Example of using RSA in Python with the cryptography library:
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
# Generate keys
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
message = b"Secret message"
# Encrypt with the public key
ciphertext = public_key.encrypt(
message,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
)
# Decrypt with the private key
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
)
print(plaintext.decode()) # Will output: Secret message