Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_scramble.py

raw
1 # Copyright 2016 Red Hat | Ansible
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import base64
11 import random
12
13 from ansible.module_utils.common.text.converters import to_bytes, to_text
14
15
16 def generate_insecure_key() -> bytes:
17 """Do NOT use this for cryptographic purposes!"""
18 while True:
19 # Generate a one-byte key. Right now the functions below do not use more
20 # than one byte, so this is sufficient.
21 key = bytes([random.randint(0, 255)])
22 # Return anything that is not zero
23 if key != b"\x00":
24 return key
25
26
27 def scramble(value: str, key: bytes) -> str:
28 """Do NOT use this for cryptographic purposes!"""
29 if len(key) < 1:
30 raise ValueError("Key must be at least one byte")
31 b_value = to_bytes(value)
32 k = key[0]
33 b_value = bytes([k ^ b for b in b_value])
34 return f"=S={to_text(base64.b64encode(b_value))}"
35
36
37 def unscramble(value: str, key: bytes) -> str:
38 """Do NOT use this for cryptographic purposes!"""
39 if len(key) < 1:
40 raise ValueError("Key must be at least one byte")
41 if not value.startswith("=S="):
42 raise ValueError("Value does not start with indicator")
43 b_value = base64.b64decode(value[3:])
44 k = key[0]
45 b_value = bytes([k ^ b for b in b_value])
46 return to_text(b_value)