pythonazure-databrickspublic-key-encryptiongnupgpgp

Encrypt Decrypt file using GNUPG


I created PGP keys using this key generator website (Algo - RSA, Key Size - 4096 bits). I am using Databricks to write its encrypt and decrypt function and store public and private keys generated through pgpkeygen.com. I tried multiple ways to achieve this functionality but failed every time. Below is the latest code I have for encryption and decryption:

Encryption:

import gnupg
import os

gpg = gnupg.GPG(gnupghome = 'pgp_keys/')

def encrypt_file(file_path, output_path):
    with open(file_path, 'rb') as f:
        encrypted_data = gpg.encrypt_file(f, "a@xyz.com")
        with open(output_path, 'wb') as encrypted_file:
            encrypted_file.write(encrypted_data.data)
    
    print('ok: ', encrypted_data.ok)
    print('status: ', encrypted_data.status)
    print('stderr: ', encrypted_data.stderr)

Below are logs I gathered after executing the encryption function-

ok: False status: invalid recipient stderr: gpg: WARNING: unsafe permissions on homedir '/Workspace/Users/a@xyz.com/pgp_keys' [GNUPG:] KEY_CONSIDERED 337B0001AEB11E875CBFE01C99E7824740791203 0 [GNUPG:] KEY_CONSIDERED 337B0001AEB11E875CBFE01C99E7824740791203 0 gpg: 01E18C0B5E758C10: There is no assurance this key belongs to the named user [GNUPG:] INV_RECP 10 a@xyz.com [GNUPG:] FAILURE encrypt 53 gpg: [stdin]: encryption failed: Unusable public key

The keys are correct and usable. Uploaded them multiple times after seeing the Unusable public key message.

Below is the decryption code:

def decrypt_file(file_path, output_path):
    with open(file_path, 'rb') as f:
        decrypted_data = gpg.decrypt_file(f,passphrase='passphrase', output=output_path)
    return decrypted_data.ok

I tried multiple things to rectify these errors but was not able to perform correct encryption and decryption. I need help to perform correct encryption and decryption using PGP keys.


Solution

  • Below shell command will help to decrypt the files

    gpg --no-tty --batch --import /dbfs/mnt/datalake/configuration/config_decrypt/privatekey.asc  
    
    mkdir -p /dbfs/mnt/datalake/<Output directory>  
    
    gpg --no-tty --batch --yes --ignore-mdc-error --pinentry-mode=loopback --passphrase-fd 1 --passphrase-file /dbfs/mnt/datalake/configuration/config_decrypt/Passphrase.txt --output /dbfs/mnt/datalake/<Output directory>/${output_decrypted_filename} --decrypt /dbfs/mnt/datalake/<Input Directory>/${input_encrypted_filename}
    

    refer this for more details.