in Python/Encrypt credentials/Encryption sample/helper/asymmetric1024keyencryptionhelper.py [0:0]
def encrypt_segment(self, modulus_bytes, exponent_bytes, data):
''' Encrypts the message segment with RSA, MGF and SHA hashes
Args:
plain_text_bytes (bytes): Message to be encrypted
modulus_bytes (bytes): Modulus bytes returned from GET gateway API
exponent_bytes (bytes): Exponent bytes returned from GET gateway API
Returns:
String: Encrypted credentials
'''
if not data:
raise TypeError('Data is null')
if data == '':
return data
# For loop to execute the encryption
for attempt in range(0, self.MAX_ATTEMPTS):
try:
# Convert exponent and modulus byte arrays to integer
exponent = int.from_bytes(exponent_bytes, 'big')
modulus = int.from_bytes(modulus_bytes, 'big')
# Generate public key based on modulus and exponent returned by the API
public_key = rsa.RSAPublicNumbers(
exponent, modulus).public_key(default_backend())
# Encrypt the data using encrypt method
# Pass padding algorithm, mask generation function and hashing algorithm
encrypted_bytes = public_key.encrypt(bytes(data),
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None))
return encrypted_bytes
except Exception as ex:
# Sleep for 50 milliseconds
sleep(0.05)
if attempt == self.MAX_ATTEMPTS - 1:
raise Exception(ex)
raise Exception("Invalid Operation")