services.py 2.21 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
'''
Service functions for encryption.tools module
'''
import gnupg

from modules.encryption.tools.all_tools.exceptions import GPGError

GNUPG_HOME = 'modules/encryption/tools/all_tools/gnupg_home'


def create_gnupg_object():
    '''
    Creating and returning GnuPG object
    '''
    gpg = gnupg.GPG(gnupghome=GNUPG_HOME)
    gpg.encoding = 'utf-8'
    return gpg


def create_key_pair(name, email, comment, expire_date, passphrase=''):
    '''
    Creating fresh public and private keys and returning key's fingerprint
    '''
    gpg = create_gnupg_object()

    key_length = 1024
    key_type = 'RSA'

    input_data = gpg.gen_key_input(
        key_length=key_length,
        key_type=key_type,
        name_real=name,
        name_comment=comment,
        name_email=email,
        expire_date=expire_date,
        passphrase=passphrase
    )
    key = gpg.gen_key(input_data)
    if key.fingerprint:
        return key.fingerprint
    else:
        raise GPGError(message=getattr(key, 'stderr'))


def list_all_keys():
    '''
    Returning all public and private keys available in keyring
    '''
    gpg = create_gnupg_object()

    return {
        'all_public_keys': gpg.list_keys().key_map,
        'all_private_keys': gpg.list_keys(True).key_map
    }


def export_single_key(keyid, passphrase=None):
    '''
    Returning public or private key in ascii format
    '''
    gpg = create_gnupg_object()

    if passphrase:
        return gpg.export_keys(keyid, True, passphrase=passphrase)
    return gpg.export_keys(keyid)


def encrypt_message(keyid, message):
    '''
    Encrypting a message using a public key
    '''
    gpg = create_gnupg_object()

    encrypted_message_object = gpg.encrypt(message, keyid)

    if encrypted_message_object.ok:
        return str(encrypted_message_object)
    else:
        raise GPGError(message=encrypted_message_object.status)


def decrypt_message(message, passphrase):
    '''
    Decrypting a message using private key and passphrase
    '''
    gpg = create_gnupg_object()

    decrypted_message_object = gpg.decrypt(message, passphrase=passphrase)
    if decrypted_message_object.ok:
        return str(decrypted_message_object)
    else:
        raise GPGError(message=decrypted_message_object.status)