Encrypt and Decrypt a File — Boto 3 Docs 1.9.185 documentation (2024)

The example program uses AWS KMS keys to encrypt and decrypt a file.

A master key, also called a Customer Master Key or CMK, is created and used to generate a data key.The data key is then used to encrypt a disk file. The encrypted data key is stored withinthe encrypted file. To decrypt the file, the data key is decrypted and then used to decryptthe rest of the file. This manner of using master and data keys is called envelope encryption.

To encrypt and decrypt data, the example uses the well-known Python cryptography package.This package is not part of the Python standard library and must be installed separately, forexample, with the pip command.

pip install cryptography

Each section describes a single function from the example's entiresource file.

Retrieve an Existing Master Key

Master keys are created, managed, and stored within AWS KMS. A KMS master key is also referred toas a customer master key or CMK. An AWS storage cost is incurred for each CMK, therefore, one CMK isoften used to manage multiple data keys.

The example retrieve_cmk function searches for an existing CMK. A key description is specifiedwhen a CMK is created, and this description is used to identify and retrieve the desired key. Ifmany CMKs exist, they are processed in batches until either the desired key is found or all keys areexamined.

If the example function finds the desired CMK, it returns both the CMK's ID and its ARN (AmazonResource Name). Either of these identifiers can be used to reference the CMK in subsequent callsto AWS KMS methods.

def retrieve_cmk(desc): """Retrieve an existing KMS CMK based on its description :param desc: Description of CMK specified when the CMK was created :return Tuple(KeyId, KeyArn) where: KeyId: CMK ID KeyArn: Amazon Resource Name of CMK :return Tuple(None, None) if a CMK with the specified description was not found """ # Retrieve a list of existing CMKs # If more than 100 keys exist, retrieve and process them in batches kms_client = boto3.client('kms') try: response = kms_client.list_keys() except ClientError as e: logging.error(e) return None, None done = False while not done: for cmk in response['Keys']: # Get info about the key, including its description try: key_info = kms_client.describe_key(KeyId=cmk['KeyArn']) except ClientError as e: logging.error(e) return None, None # Is this the key we're looking for? if key_info['KeyMetadata']['Description'] == desc: return cmk['KeyId'], cmk['KeyArn'] # Are there more keys to retrieve? if not response['Truncated']: # No, the CMK was not found logging.debug('A CMK with the specified description was not found') done = True else: # Yes, retrieve another batch try: response = kms_client.list_keys(Marker=response['NextMarker']) except ClientError as e: logging.error(e) return None, None # All existing CMKs were checked and the desired key was not found return None, None

Create a Customer Master Key

If the example does not find an existing CMK, it creates a new one and returns its ID and ARN.

def create_cmk(desc='Customer Master Key'): """Create a KMS Customer Master Key The created CMK is a Customer-managed key stored in AWS KMS. :param desc: key description :return Tuple(KeyId, KeyArn) where: KeyId: AWS globally-unique string ID KeyArn: Amazon Resource Name of the CMK :return Tuple(None, None) if error """ # Create CMK kms_client = boto3.client('kms') try: response = kms_client.create_key(Description=desc) except ClientError as e: logging.error(e) return None, None # Return the key ID and ARN return response['KeyMetadata']['KeyId'], response['KeyMetadata']['Arn']

Create a Data Key

To encrypt a file, the example create_data_key function creates a data key. The data key iscustomer managed and does not incur an AWS storage cost. The example creates a data key foreach file it encrypts, but it's possible to use a single data key to encrypt multiple files.

The example function returns the data key in both its plaintext and encrypted forms. Theplaintext form is used to encrypt the data. The encrypted form will be stored with the encryptedfile. The data key is associated with a CMK which is capable of decrypting the encrypted data keywhen necessary.

def create_data_key(cmk_id, key_spec='AES_256'): """Generate a data key to use when encrypting and decrypting data :param cmk_id: KMS CMK ID or ARN under which to generate and encrypt the data key. :param key_spec: Length of the data encryption key. Supported values: 'AES_128': Generate a 128-bit symmetric key 'AES_256': Generate a 256-bit symmetric key :return Tuple(EncryptedDataKey, PlaintextDataKey) where: EncryptedDataKey: Encrypted CiphertextBlob data key as binary string PlaintextDataKey: Plaintext base64-encoded data key as binary string :return Tuple(None, None) if error """ # Create data key kms_client = boto3.client('kms') try: response = kms_client.generate_data_key(KeyId=cmk_id, KeySpec=key_spec) except ClientError as e: logging.error(e) return None, None # Return the encrypted and plaintext data key return response['CiphertextBlob'], base64.b64encode(response['Plaintext'])

Encrypt a File

The encrypt_file function creates a data key and uses it to encrypt the contents of a disk file.

The encryption operation is performed by a Fernet object created by the Python cryptographypackage.

The encrypted form of the data key is saved within the encrypted file and will be used in the futureto decrypt the file. The encrypted file can be decrypted by any program with the credentials todecrypt the encrypted data key.

def encrypt_file(filename, cmk_id): """Encrypt a file using an AWS KMS CMK A data key is generated and associated with the CMK. The encrypted data key is saved with the encrypted file. This enables the file to be decrypted at any time in the future and by any program that has the credentials to decrypt the data key. The encrypted file is saved to <filename>.encrypted Limitation: The contents of filename must fit in memory. :param filename: File to encrypt :param cmk_id: AWS KMS CMK ID or ARN :return: True if file was encrypted. Otherwise, False. """ # Read the entire file into memory try: with open(filename, 'rb') as file: file_contents = file.read() except IOError as e: logging.error(e) return False # Generate a data key associated with the CMK # The data key is used to encrypt the file. Each file can use its own # data key or data keys can be shared among files. # Specify either the CMK ID or ARN data_key_encrypted, data_key_plaintext = create_data_key(cmk_id) if data_key_encrypted is None: return False logging.info('Created new AWS KMS data key') # Encrypt the file f = Fernet(data_key_plaintext) file_contents_encrypted = f.encrypt(file_contents) # Write the encrypted data key and encrypted file contents together try: with open(filename + '.encrypted', 'wb') as file_encrypted: file_encrypted.write(len(data_key_encrypted).to_bytes(NUM_BYTES_FOR_LEN, byteorder='big')) file_encrypted.write(data_key_encrypted) file_encrypted.write(file_contents_encrypted) except IOError as e: logging.error(e) return False # For the highest security, the data_key_plaintext value should be wiped # from memory. Unfortunately, this is not possible in Python. However, # storing the value in a local variable makes it available for garbage # collection. return True

Decrypt a Data Key

To decrypt an encrypted file, the encrypted data key used to perform the encryption must firstbe decrypted. This operation is performed by the example decrypt_data_key function which returnsthe plaintext form of the key.

def decrypt_data_key(data_key_encrypted): """Decrypt an encrypted data key :param data_key_encrypted: Encrypted ciphertext data key. :return Plaintext base64-encoded binary data key as binary string :return None if error """ # Decrypt the data key kms_client = boto3.client('kms') try: response = kms_client.decrypt(CiphertextBlob=data_key_encrypted) except ClientError as e: logging.error(e) return None # Return plaintext base64-encoded binary data key return base64.b64encode((response['Plaintext']))

Decrypt a File

The example decrypt_file function first extracts the encrypted data key from the encrypted file. Itthen decrypts the key to get its plaintext form and uses that to decrypt the file contents.

The decryption operation is performed by a Fernet object created by the Python cryptographypackage.

def decrypt_file(filename): """Decrypt a file encrypted by encrypt_file() The encrypted file is read from <filename>.encrypted The decrypted file is written to <filename>.decrypted :param filename: File to decrypt :return: True if file was decrypted. Otherwise, False. """ # Read the encrypted file into memory try: with open(filename + '.encrypted', 'rb') as file: file_contents = file.read() except IOError as e: logging.error(e) return False # The first NUM_BYTES_FOR_LEN bytes contain the integer length of the # encrypted data key. # Add NUM_BYTES_FOR_LEN to get index of end of encrypted data key/start # of encrypted data. data_key_encrypted_len = int.from_bytes(file_contents[:NUM_BYTES_FOR_LEN], byteorder='big') \ + NUM_BYTES_FOR_LEN data_key_encrypted = file_contents[NUM_BYTES_FOR_LEN:data_key_encrypted_len] # Decrypt the data key before using it data_key_plaintext = decrypt_data_key(data_key_encrypted) if data_key_plaintext is None: return False # Decrypt the rest of the file f = Fernet(data_key_plaintext) file_contents_decrypted = f.decrypt(file_contents[data_key_encrypted_len:]) # Write the decrypted file contents try: with open(filename + '.decrypted', 'wb') as file_decrypted: file_decrypted.write(file_contents_decrypted) except IOError as e: logging.error(e) return False # The same security issue described at the end of encrypt_file() exists # here, too, i.e., the wish to wipe the data_key_plaintext value from # memory. return True
Encrypt and Decrypt a File — Boto 3 Docs 1.9.185 documentation (2024)

FAQs

How do I encrypt and decrypt a file? ›

How to encrypt a file
  1. Right-click (or press and hold) a file or folder and select Properties.
  2. Select the Advanced button and select the Encrypt contents to secure data check box.
  3. Select OK to close the Advanced Attributes window, select Apply, and then select OK.

How to decrypt encrypted files without certificate in Windows 10? ›

You can follow the steps below to decrypt a file on Windows 10:
  1. Select "Programs or All Programs" under the start menu, click "Accessories", and then choose "Windows Explorer".
  2. Right-click the file you want to decrypt, and click "Properties".
  3. Click "Advanced".
  4. Clear the Encrypt contents and then click "OK".
Oct 27, 2023

How to decrypt an encrypted file in Python? ›

Decrypt the encrypted file
  1. Initialize the Fernet object and store it in the fernet variable.
  2. Read the encrypted file.
  3. Decrypt the file and store it into an object.
  4. Then write the decrypted data into the same file nba. csv.
Jun 3, 2022

How can you tell if the file is encrypted or decrypted? ›

Examining the storage medium or file properties lets you check if your data is encrypted. Encrypted data appears unreadable gibberish, making it inaccessible without the appropriate decryption key. Data encryption, in its simplest sense, is changing data into a code to avoid unauthorized access.

What is the easiest way to encrypt a file? ›

How to encrypt files with Windows
  1. Right-click or press and hold the file or folder you want to encrypt. Select Properties.
  2. Click the Advanced… button and check the box next to Encrypt contents to secure data.
  3. Select OK to close the Advanced Attributes window and then select Apply.
  4. Click OK.
Mar 15, 2023

How do I convert an encrypted file to a decrypted file? ›

How to decrypt ransomware encrypted files (and recover your data without a previous backup)
  1. Step 1: Identify the ransomware variant. ...
  2. Step 2: Back up encrypted files. ...
  3. Step 3: Download a decryption tool. ...
  4. Step 4: Run the decryption tool. ...
  5. Step 5: Check the decrypted files. ...
  6. Step 6: Remove the ransomware.
Feb 28, 2023

How do I open hidden encrypted files? ›

Type command prompt in the Search. Right-click the Command Prompt and select Run as administrator. Type dir D: /a:h /b /s and press Enter to show hidden files in drive D (if you want to see your hidden files in any other hard drive, just type its letter instead of D, as we only use it here as an example).

Does Windows 10 have file encryption? ›

Microsoft's Windows operating system and Office suite have some built-in file-encryption features. Here's how to use them. If you're looking for a simple way to keep files and folders private on your Windows computer, you have several options right in front of you.

Can you unencrypt an encrypted file? ›

If you're wondering “Can ransomware encrypt encrypted files?” The answer is, unfortunately, yes. As ransomware attacks are on the rise, more and more people are keen to learn ransomware defense mechanisms they can utilize for their cybersecurity.

How to encrypt a file? ›

How to encrypt a file on Android. You'll need third-party software to encrypt files on an Android — unless you wish to encrypt your entire device. Third-party apps will ask you to import the files you want to protect. This will save an encrypted copy of the file on the app's drive.

What is an example of a encrypted file? ›

Examples of file encryption include AES, RSA, Blowfish, and Twofish. These methods encrypt files in such a way that without possessing a key generated by the specific algorithm, decrypting it would be computationally impossible.

How to encrypt a text file? ›

Open the text file you want to encrypt using a text editor of your choice. Go to the “File” menu and select “Save As…” to create a new, encrypted version of the file. Choose a secure password that is easy for you to remember but difficult for others to guess.

How do I read an encrypted file? ›

Encrypted files do not have a special file extension, but they do have a padlock displayed on the icon. To unlock these files, all you need to do is log into your computer using your password.

How do I read a decrypt file? ›

To decrypt an encrypted file, simply repeat the steps above and uncheck the box next to Encrypt contents to secure data. After unchecking the box, select OK in the Advanced Attributes window and the Properties window. Double-check to make sure the padlock is no longer attached to your file.

How to check if a file is encrypted or not in Python? ›

If you want to check if a file is encrypted, use the GetFileInfo() method that returns the file type and flag that indicates if the file is encrypted.

Is there a way to encrypt a file? ›

  1. Open your Microsoft Word document.
  2. Go to File > Info.
  3. Click Protect Document.
  4. Click Encrypt with Password.

How do I decrypt a file or folder? ›

How to decrypt a folder on Windows
  1. Ensure you are logged in with the user account you used to encrypt the folder.
  2. Right-click the folder and select “Show more options” then “Properties”.
  3. Make sure you're on the General tab and click on “Advanced”.
  4. Uncheck the box next to “Encrypt contents to secure data” and click “o*k”.

What is the command to encrypt a file? ›

Encrypt the File
  1. Open a command prompt.
  2. From the command prompt, enter: pgp --encrypt (input) --recipient (user)
  3. Press Enter.
Jan 26, 2022

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 6130

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.