summaryrefslogtreecommitdiff
path: root/filter_plugins/crypto.py
blob: b3dc32c4f8595414c86526e5e2b455c16dd46a7c (plain) (blame)
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
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import hashlib
from passlib.utils.binary import Base64Engine, HASH64_CHARS, BCRYPT_CHARS
from ansible.module_utils._text import to_bytes, to_text
from ansible import errors


def _hash64_salt(seed, length):
    h = hashlib.new('sha256')
    e = Base64Engine(HASH64_CHARS)
    h.update(to_bytes(seed, errors='surrogate_or_strict'))
    return to_text(e.encode_bytes(h.digest()[0:length]))


def apr_md5_crypt_salt(seed):
    ''' generate salt for apr_md5_crypt algorithm based on seed-value '''
    try:
        return _hash64_salt(seed, 6)
    except Exception as e:
        raise errors.AnsibleFilterError("apr_md5_crypt_salt(): %s" % str(e))


def sha2_crypt_salt(seed):
    ''' generate salt for sha256/sha512_crypt algorithms based on seed-value '''
    try:
        return _hash64_salt(seed, 12)
    except Exception as e:
        raise errors.AnsibleFilterError("sha2_crypt_salt(): %s" % str(e))


def bcrypt_salt(seed):
    ''' generate salt for bcrypt algorithm based on seed-value '''
    try:
        h = hashlib.new('sha256')
        e = Base64Engine(BCRYPT_CHARS)
        h.update(to_bytes(seed, errors='surrogate_or_strict'))
        return to_text(e.encode_bytes(h.digest()[0:16]))
    except Exception as e:
        raise errors.AnsibleFilterError("bcrypt_salt(): %s" % str(e))


class FilterModule(object):

    ''' crypto helpers '''
    filter_map = {
        'apr_md5_crypt_salt': apr_md5_crypt_salt,
        'sha256_salt': sha2_crypt_salt,
        'sha512_salt': sha2_crypt_salt,
        'bcrypt_salt': bcrypt_salt,
    }

    def filters(self):
        return self.filter_map