예제 #1
0
    def generate_key_pair(self):  # 3.1.1
        questions = [{
            'type': 'list',
            'name': 'regenerate',
            'message': 'Do you want to regenerate the key pair?',
            'choices': ['Yes', 'No'],
            'filter': lambda val: val.lower()
        }, {
            'type': 'list',
            'name': 'save_pwd',
            'message': 'Do you want save password?',
            'choices': ['Yes', 'No'],
            'filter': lambda val: val.lower(),
            'when': lambda answer: answer['regenerate'] == 'yes'
        }]
        crypto = CryptoUtility()

        answer = prompt(questions, style=self.style)

        if answer['regenerate'] == 'yes':
            crypto.generate_key_pair()
            print('Generating key pair...')
            crypto.password = self._set_password()
            if answer['save_pwd'] == 'yes':
                print(crypto.export_password_hash_to_file())
            else:
                crypto.delete_password_hash_file()
            print(crypto.export_private_key_to_file())
            print(crypto.export_public_key_to_file())
            print('Key pair successfully generated!\n')
            self._show_public_key()
            self.configure_key_pair()
        else:
            self.configure_key_pair()
예제 #2
0
 def encrypt(self):  # 1
     questions = [
         {'type': 'password', 'message': 'Enter the string to be encrypted:', 'name': 'password'}
     ]
     crypto = CryptoUtility(self.key_path)
     if not crypto.import_public_key_from_file():
         print('No public Key found!')
     else:
         answer = prompt(questions)
         qprint('Encrypted password: (use incl. "crypt:")\n', style='#06c8ff')
         cipher_text = crypto.encrypt_text(answer['password'])
         qprint(f"{cipher_text}\n", style='bold #06c8ff')
예제 #3
0
 def delete_public_key(self):
     delete_password = [{
         'type': 'list',
         'name': 'delete_public',
         'message': 'Do you really want to delete public key?',
         'choices': ['Yes', 'No'],
         'filter': lambda val: val.lower(),
     }]
     answer = prompt(delete_password, style=custom_style_fancy)
     if answer['delete_public'] == 'yes':
         crypto = CryptoUtility()
         if crypto.delete_public_key_file():
             print('Successfully deleted!')
예제 #4
0
 def delete_saved_password(self):  # 3.1.6
     delete_password = [{
         'type': 'list',
         'name': 'delete_pwd',
         'message': 'Do you really want to delete saved password?',
         'choices': ['Yes', 'No'],
         'filter': lambda val: val.lower()
     }]
     answer = prompt(delete_password, style=self.style)
     if answer['delete_pwd'] == 'yes':
         crypto = CryptoUtility()
         if crypto.delete_password_hash_file():
             print('Successfully deleted!')
     self.configure_key_pair()
예제 #5
0
 def encrypt(self):  # 1
     questions = [{
         'type': 'password',
         'message': 'Enter the password to encrypt',
         'name': 'password'
     }]
     crypto = CryptoUtility()
     if not crypto.import_public_key_from_file():
         print('No public Key found!')
     else:
         answer = prompt(questions, style=custom_style_fancy)
         print('Encrypted password: (use incl. "crypt:")\n')
         cipher_text = crypto.encrypt_text(answer['password'])
         print(f"{cipher_text}\n", style='bold blink #06c8ff')
예제 #6
0
 def set_public_key_from_string(self):  # 3.2.2
     questions = [{
         'type': 'input',
         'name': 'public_key',
         'message': 'Input public_key as Base64:',
     }]
     crypto = CryptoUtility()
     answer = prompt(questions, style=self.style)
     if answer['public_key'] != '':
         try:
             crypto.set_public_key(answer['public_key'])
             print(crypto.export_public_key_to_file())
             print('Key successfully stored!\n')
         except Exception as e:
             print(e)
     self.configure_public_key()
예제 #7
0
 def encrypt(self):  # 1
     questions = [{
         'type': 'password',
         'message': 'Enter the password to encrypt',
         'name': 'password'
     }]
     crypto = CryptoUtility()
     if not crypto.import_public_key_from_file():
         print('No public Key found!')
     else:
         answer = prompt(questions, style=self.style)
         print('Encrypted password: (use inlc. "crypt:")\n')
         cipher_text = crypto.encrypt_text(answer['password'])
         print(cipher_text)
         print()
     self.main_menu()
예제 #8
0
 def delete_key_pair(self):  # 3.1.4
     delete_password = [
         {
             'type': 'list',
             'name': 'delete_keys',
             'message': 'Do you really want to delete key pair?',
             'choices': ['Yes', 'No'],
             'filter': lambda val: val.lower(),
         }
     ]
     answer = prompt(delete_password)
     if answer['delete_keys'] == 'yes':
         crypto = CryptoUtility(self.key_path)
         if crypto.delete_key_store():
             print('Successfully deleted!')
     self.configure_key_pair()
예제 #9
0
    def __init__(self, password=None, variable_decryption=False):
        """
+--------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+
| **password:**            | Password for private key can be given as argument.                                                                                      |
+--------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+
| **variable_decryption:** | If set to ``True`` all variables that are available on Test Case start, that contain a encrypted text, will be decrypted automatically. |
+--------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+
        """
        self.ROBOT_LIBRARY_LISTENER = self
        self.value_list = list()
        self.crypto = CryptoUtility()
        self.original_log_level = 'INFO'
        self.disable_logging = False
        if password:
            self.crypto.password = password
        self.variable_decryption = variable_decryption
        self.builtin = BuiltIn()
예제 #10
0
 def decrypt(self):  # 2
     questions = [
         {
             'type': 'input',
             'name': 'cipher_text',
             'message': 'Input encrypted cipher text:',
         }
     ]
     input_password = [
         {
             'type': 'password',
             'name': 'password',
             'message': 'Enter the password of private key to decrypt:',
         }
     ]
     answer = prompt(questions)
     crypto = CryptoUtility(self.key_path)
     if not crypto.password:
         input_pwd = prompt(input_password)
         crypto.password = input_pwd['password']
     print(f' Decrypting...', end="\r")
     crypto.import_private_key_from_file()
     password = crypto.decrypt_text(answer['cipher_text'])
     qprint(f'Your password is:', style='#06c8ff', flush=True)
     qprint(f'\n{password}\n', style='bold #06c8ff')
예제 #11
0
class Plugin(LibraryComponent):
    def __init__(self, ctx):
        self.crypto = CryptoUtility()
        LibraryComponent.__init__(self, ctx)

    @keyword
    def input_password(self, locator, password, clear=True):
        """Types the given password into the text field identified by ``locator``.

        The `password` argument may be encrypted with CryptoLibrary.
        Then this Keyword decrypts it automatically.
        Be aware that the crypt: prefix is needed for automatic decryption.

        See the `Locating elements` section for details about the locator
        syntax. See `Input Text` for ``clear`` argument details.

        Difference compared to `Input Text` is that this keyword does not
        log the given password on the INFO level. Notice that if you use
        the keyword like

        | Input Password | password_field | password |

        the password is shown as a normal keyword argument. A way to avoid
        that is using variables like

        | Input Password | password_field | ${PASSWORD} |

        Please notice that Robot Framework logs all arguments using
        the TRACE level and tests must not be executed using level below
        DEBUG if the password should not be logged in any format.

        The `clear` argument is new in SeleniumLibrary 4.0. Hiding password
        logging from Selenium logs is new in SeleniumLibrary 4.2.
        """
        self.info("Typing password into text field '%s'." % locator)
        if isinstance(password, str) and re.fullmatch(
                self.crypto.CIPHER_PATTERN, password):
            plaintext = self.crypto.decrypt_text(password)
        else:
            plaintext = password
        self._input_text_into_text_field(locator, plaintext, clear)

    def _input_text_into_text_field(self, locator, text, clear=True):
        element = self.find_element(locator)
        if is_truthy(clear):
            element.clear()
        previous_level = BuiltIn().set_log_level('NONE')
        try:
            element.send_keys(text)
        finally:
            BuiltIn().set_log_level(previous_level)
예제 #12
0
    def save_private_key_password(self):  # 3.1.5
        input_password = [
            {
                'type': 'password',
                'name': 'password',
                'message': 'Enter the password to decrypt private key:',
            }
        ]
        crypto = CryptoUtility(self.key_path)

        if not crypto.password:
            input_pwd = prompt(input_password)
            crypto.password = input_pwd['password']
            if crypto.import_private_key_from_file():
                crypto.export_password_hash_to_file()
                print('Saved password successfully!')
            else:
                print('Wrong Password!')
        else:
            print('Password already saved.')
        self.configure_key_pair()
예제 #13
0
 def decrypt(self):  # 2
     questions = [{
         'type': 'input',
         'name': 'cipher_text',
         'message': 'Input encrypted cipher text:',
     }]
     input_password = [{
         'type': 'password',
         'name': 'password',
         'message': 'Enter the password to decrypt'
     }]
     answer = prompt(questions, style=self.style)
     crypto = CryptoUtility()
     if not crypto.password:
         input_pwd = prompt(input_password, style=self.style)
         crypto.password = input_pwd['password']
     crypto.import_private_key_from_file()
     password = crypto.decrypt_text(answer['cipher_text'])
     print(f'Your password is: {password}')
     print()
     self.main_menu()
예제 #14
0
 def _show_public_key(self):
     crypto = CryptoUtility()
     key = crypto.import_public_key_from_file()
     if key:
         print(f'Public Key: {key}')
         print()
예제 #15
0
class CryptoLibrary(object):
    """|
|

===================================================
robotframework-crypto
===================================================

CryptoLibrary is a library for secure password handling.
`project page <https://github.com/Snooz82/robotframework-datadriver>`_

For more information about Robot Framework, see http://robotframework.org.

|

Installation
------------

If you already have Python >= 3.6 with pip installed, you can simply
run:

``pip install --upgrade robotframework-crypto``

or if you have Python 2 and 3 installed in parallel you may use

``pip3 install --upgrade robotframework-crypto``

If you have Python 2 ... i am very sorry! Please update!

|

How it works
------------

CryptoLibrary uses asymmetric crypto with elliptic curve cryptography to store confidential data securely.

With ``python -m CryptoLibrary`` you can generate a key pair (private and public key) for your test env.
You will get the public key after generating.

this public key can now be used to encrypt every data you do not want to be public.
Passwords, personal data, etc.

you can use ``python -m CryptoClient`` on you computer where you want to encrypt data.
Encrypted Data will look like this:

``tIdr5s65+ggfJZl46pJgljioCUePUdZLozgiwquznw+xSlmzT3dcvfrTL9wIdRwmNOJuONT7FBW5``

this encrypted data can now be decrypted with CryptoLibrary within RobotFramework.

CryptoLibrary need the private_key_store.json for this.
This is what is generated as key pair.
Private key can be imported in test env with ``python -m CryptoLibrary`` .

|

Suppressing encrypted Text from Logs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All Data that is decrypted by CryptoLibrary is replaced in the log by ``***``
This works always and can not be disabled.
No need to use special keywords for this.

|

Usage in Test
~~~~~~~~~~~~~

.. code :: robotframework

    *** Settings ***
    Resource    imports.resource
    Library     CryptoLibrary    ${decryption_password}    #private key which should be secret is also protected by a password

    *** Variables ***
    ${secret}=     KILL ALL HUMANS!!!
    ${enc_user}=   nkpEPOVKfOko3t04XxOupA+F/ANTEuR9aQuPaPeMBGBQenwYf6UNESEl9MWRKGuj60ZWd10=
    ${enc_pwd}=    TVpamLXCtrzRsl8UAgD0YuoY+lSJNV73+bTYhOP51zM1GQihgyCvSZ2CoGoKsUHLFjokyJLHxFzPEB4=

    *** Test Cases ***
    Valid Login
        Open Browser    ${BASE-URL}
        Suppress Logging                                  #disable Robot Framework logging
        ${var}=    set Variable   ${secret}
        Log    ${var}
        Suppress Logging    False                         #disable Robot Framework logging
        Decrypt Text To Variable    user    ${enc_user}   #puts the decrypted pain text into ${user}
        ${var2}=    set Variable    ${user}
        log    ${var2}
        Input Text      id:input_username    ${user}
        ${password}=    Get Decrypted Text    ${enc_pwd}  #decrypts cipher text and returns plain text
        Input Password    id:input_password    ${password}
        Click Button    id:button_login
        Page Should Contain Element    //a[text()='Logout']
        Location Should Be    ${BASE-URL}list
        [Teardown]   Close Browser

in this case the decryption password for the private key.
It can also be saved on test env persistently as a hash.


THIS IS JUST AN ALPHA VERSION !!11!!1
-------------------------------------
    """

    ROBOT_LIBRARY_DOC_FORMAT = 'reST'
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = __version__
    ROBOT_LISTENER_API_VERSION = 3

    def __init__(self, password=None, variable_decryption=False):
        """
+--------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+
| **password:**            | Password for private key can be given as argument.                                                                                      |
+--------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+
| **variable_decryption:** | If set to ``True`` all variables that are available on Test Case start, that contain a encrypted text, will be decrypted automatically. |
+--------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+
        """
        self.ROBOT_LIBRARY_LISTENER = self
        self.value_list = list()
        self.crypto = CryptoUtility()
        self.original_log_level = 'INFO'
        self.disable_logging = False
        if password:
            self.crypto.password = password
        self.variable_decryption = variable_decryption
        self.builtin = BuiltIn()

    def conceal_logs_for_password(self, plaintext):
        """Conceal logs for the password passed as input."""
        logger.info(f'Conceal logs for the password passed as input')
        self.value_list.append(plaintext)

    def decrypt_text_to_variable(self, variable_name, cipher_text):
        """Decrypts cipher_text and stores the decrypted plain text into a scalar variable.
        Variable would be i.e. ${variable_name}"""
        logger.info(f'Decrypting text into variable ${{{variable_name}}}')
        plaintext = self.crypto.decrypt_text(cipher_text)
        self.value_list.append(plaintext)
        name = self.builtin._get_var_name(f'${{{variable_name}}}')
        value = self.builtin._get_var_value(name, [plaintext])
        self.builtin._variables.set_test(name, value)

    def get_decrypted_text(self, cipher_text):
        """Decrypts cipher text and returns the plain text."""
        logger.info(f'Decrypting text and return value.')
        plaintext = self.crypto.decrypt_text(cipher_text)
        self.value_list.append(plaintext)
        return plaintext

    def suppress_logging(self, disable: bool = True):
        """Disables the logging of robot framework until ``Suppress Logging    False`` has been called."""
        if disable:
            logger.info('disable logging...')
            self.original_log_level = self.builtin.set_log_level('NONE')
        else:
            self.builtin.set_log_level(self.original_log_level)
            logger.info('enable logging...')
            logger.debug(f'Switching Loglevel from NONE to {self.original_log_level}.')

    def _start_test(self, test, result):
        self._decrypt_variable_in_scope(self.builtin.set_test_variable)

    def _decrypt_variable_in_scope(self, set_scope_variable):
        if self.variable_decryption:
            variables = self.builtin.get_variables()
            for var in variables:
                value = self.builtin.get_variable_value(var)
                if isinstance(value, str) and re.fullmatch(self.crypto.CIPHER_PATTERN, value):
                    plain = self.get_decrypted_text(value)
                    set_scope_variable(var, plain)

    def _log_message(self, message):
        if self.value_list:
            pattern = re.compile("|".join(self.value_list))
            message.message = pattern.sub('***', message.message)
예제 #16
0
class CryptoLibrary(object):
    """===================================================
robotframework-crypto
===================================================

CryptoLibrary is a library for secure password handling.
`project page <https://github.com/Snooz82/robotframework-crypto>`_

For more information about Robot Framework, see http://robotframework.org.

|

Installation
------------

If you already have Python >= 3.6 with pip installed, you can simply
run:

``pip install --upgrade robotframework-crypto``

or if you have Python 2 and 3 installed in parallel you may use

``pip3 install --upgrade robotframework-crypto``

If you have Python 2 ... i am very sorry! Please update!

|

How it works
------------

CryptoLibrary uses asymmetric crypto with elliptic curve cryptography to store confidential data securely.

With ``python -m CryptoLibrary`` you can generate a key pair (private and public key) for your test env.
You will get the public key after generating.

this public key can now be used to encrypt every data you do not want to be public.
Passwords, personal data, etc.

you can use ``python -m CryptoClient`` on you computer where you want to encrypt data.
Encrypted Data will look like this:

``crypt:tIdr5s65+ggfJZl46pJgljioCUePUdZLozgiwquznw+xSlmzT3dcvfrTL9wIdRwmNOJuONT7FBW5``

this encrypted data can now be decrypted with CryptoLibrary within RobotFramework.

CryptoLibrary need the private_key_store.json for this.
This is what is generated as key pair.
Private key can be imported in test env with ``python -m CryptoLibrary`` .

|

Suppressing encrypted Text from Logs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All Data that is decrypted by CryptoLibrary is replaced in the log by ``***``
This works always and can not be disabled.
No need to use special keywords for this.

|

Usage in Test
~~~~~~~~~~~~~

.. code :: robotframework

    *** Settings ***
    Resource    imports.resource
    Library     CryptoLibrary    %{private_key_password}    variable_decryption=False
    #private key which should be secret, should also be protected by a password

    *** Variables ***
    ${secret}=     KILL ALL HUMANS!!!
    ${enc_user}=   crypt:nkpEPOVKfOko3t04XxOupA+F/ANTEuR9aQuPaPeMBGBQenwYf6UNESEl9MWRKGuj60ZWd10=
    ${enc_pwd}=    crypt:TVpamLXCtrzRsl8UAgD0YuoY+lSJNV73+bTYhOP51zM1GQihgyCvSZ2CoGoKsUHLFjokyJLHxFzPEB4=

    *** Test Cases ***
    Valid Login
        Open Browser    ${BASE-URL}
        Suppress Logging                                  #disable Robot Framework logging
        ${var}=    set Variable   ${secret}
        Log    ${var}
        Unsuppress Logging                                #enable Robot Framework logging
        ${user}=    Get Decrypted Text    ${enc_user}     #decrypts cipher text and returns plain text
        Input Text      id:input_username    ${user}
        ${password}=    Get Decrypted Text    ${enc_pwd}  #decrypts cipher text and returns plain text
        Input Password    id:input_password    ${password}
        Click Button    id:button_login
        Page Should Contain Element    //a[text()='Logout']
        [Teardown]   Close Browser

in this case the decryption password for the private key.
It can also be saved on test env persistently as a hash.

The parameter **variable_decryption** in the Library call, if set to true it will automatically decode ALL passwords defined in the variables section
and then ``"Get Decrypted Text"`` isn't needed.

|

Menu walkthrough
----------------

|

CryptoLibrary Command Line Tool
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This Command Line tool has to be used to create a key pair.
It can also show the public key and encrypt or decrypt data.

``python -m CryptoLibrary``::

 ? What do you want to do?  (Use arrow keys)
   Encrypt
   Decrypt
   Open config --->  ? What do you want to do?  (Use arrow keys)
   Quit                 Configure key pair    ----------------------------------------------------------------------------------------->  ? What do you want to do?  (Use arrow keys)
                        Configure public key  --->  ? What do you want to do?  (Use arrow keys)                                             Generate key pair
                        Back                          Set public key from string  --->   ? Input public_key as Base64:  ThePublicKey        Set key pair from file
                                                      Get public key from string  --->   Public Key: ThePublicKey                           Set key pair from string
                                                      Delete public key           --->   ? Do you really want to delete public key?         Delete key pair
                                                      Back                                                                                  Save private key password
                                                                                                                                            Delete saved password
                                                                                                                                            Back
 ? What do you want to do?  (Use arrow keys)
   Encrypt     ------------------------------------------------------------------->   ? Enter the password to encrypt  YourPassword
   Decrypt     -----> ? Input encrypted cipher text:  crypt:TheEncryptedPassword      Encrypted password: (use inlc. "crypt:")
   Open config        ? Enter the password to decrypt  **********
   Quit               Your password is: YourPassword                                  crypt:TheEncryptedPassword=

To start using the CryptoLibrary, start ``python -m CryptoLibrary`` and choose ``Open config`` -> ``Configure key pair``-> ``Generate key pair``.

This generates the private and public keys in the ``private_key.json`` and ``public_key.key`` files.
The ``private_key.json`` is needed to decrypt the values on your test server and has to be copied manually or added through the CLI interface.
See ``Set key pair from...`` above.

Next you can encrypt the values needed on your test server, looking something like ``crypt:nkpEPOVKfOko3t04XxOupA+F/ANTEuR9aQuPaPeMBGBQenwYf6UNESEl9MWRKGuj60ZWd10=``

There are two options to decrypt your values in the robot file. When CryptoLibrary is loaded with ``variable_decryption=True``,
ALL variables defined in that section, will automatically get decrypted.
When the option is turned off (the default) the keyword ``Get Decrypted Text`` explicitly decrypts specific values.

|

CryptoClient Command Line Tool
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This CryptoClient command line tool is the tool for all test designers that want to encrypt data.
I can only import and show the public key and encrypt data.

``python -m CryptoClient``::

 ? What do you want to do?  (Use arrow keys)
   Encrypt     --------------------------------------------------------------------------------------->   ? Enter the password to encrypt  YourPassword
   Open config -----> ? What do you want to do?  (Use arrow keys)                                           Encrypted password: (use inlc. "crypt:")
   Quit                 Set public key from string  --->   ? Input public_key as Base64:  ThePublicKey
                        Get public key from string  --->   Public Key: ThePublicKey                         crypt:TheEncryptedPassword
                        Delete public key           --->   ? Do you really want to delete public key?
                        Back

|

SeleniumLibrary Plugin
----------------------

CryptoLibrary.Plugin is a SeleniumLibrary Plugin.
When taken into usage, the ``Input Password`` Keyword can now handle decrypted cipher texts as well.

Example:

.. code :: robotframework

    *** Settings ***
    Library    SeleniumLibrary    plugins=CryptoLibrary.Plugin


    *** Variables ***
    ${Admins-Password}=    crypt:fQ5Iqn/j2lN8rXwimyz0JXlYzD0gTsPRwb0YJ3YSvDchkvDpfwYDmhHxsZ2i7bIQDlsWKJVhBb+Dz4w=


    *** Test Cases ***
    Decrypt as Plugin
        Open Browser      http://www.keyword-driven.de
        Input Text        input_username    admin
        Input Password    input_password    ${Admins-Password}

|

This is still a Proof of Concept !!11!!1 ;-)
--------------------------------------------

It may happen that keywords changes.
i try not to do, but it can happen.
Feel free to make a pull Request to improve docs or write some tests for it.

    """

    ROBOT_LIBRARY_DOC_FORMAT = 'reST'
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = __version__
    ROBOT_LISTENER_API_VERSION = 3

    def __init__(self, password=None, variable_decryption=False):
        """
        +--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
        | **password:**            | Password for private key can be given as argument. This should be stored as secret! Use environment variables instead of hard coding it here.            |
        +--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
        | **variable_decryption:** | If set to ``True`` all variables that are available on Test Suite or on Test Case start,                                                                 |
        |                          | that contain a encrypted text, will be decrypted automatically.                                                                                          |
        +--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
        """
        self.ROBOT_LIBRARY_LISTENER = self
        self.value_list = list()
        self.crypto = CryptoUtility()
        self.original_log_level = 'INFO'
        self.disable_logging = False
        if password:
            self.crypto.password = password
        self.variable_decryption = variable_decryption
        self.builtin = BuiltIn()

    def conceal_text_in_logs(self, text):
        """This keyword conceals the password, passed as input, in the logs.
        Only ``***`` will be shown in the logs.

        Because CrytoLibrary is a global Library, this text will be hidden from the point
        where it is concealed until robot execution ends.
        Earlier appearances will be visible in the logs!"""
        logger.info(f'Conceal the text in the logs.')
        self.value_list.append(text)

    def get_decrypted_text(self, cipher_text):
        """Decrypts cipher text and returns the plain text.

        Example:

        .. code :: robotframework

            ${plain_text}=    Get Decrypted Text    crypt:sZ2i7bIQDlsWKJVhBb+Dz4w=

        """
        logger.info(f'Decrypting text and return value.')
        plaintext = self.crypto.decrypt_text(cipher_text)
        self.value_list.append(plaintext)
        return plaintext

    def suppress_logging(self, disable: bool = True):
        """Disables the logging of robot framework until ``Unsuppress Logging`` has been called."""
        if disable:
            logger.info('disable logging...')
            self.original_log_level = self.builtin.set_log_level('NONE')
        else:
            self.builtin.set_log_level(self.original_log_level)
            logger.info('enable logging...')
            logger.debug(
                f'Switching Loglevel from NONE to {self.original_log_level}.')

    def unsuppress_logging(self):
        """Enables the logging of robot framework and set it back to the original log level."""
        self.suppress_logging(False)

    def _start_test(self, test, result):
        self._decrypt_variable_in_scope(self.builtin.set_test_variable)

    def _start_suite(self, suite, result):
        self._decrypt_variable_in_scope(self.builtin.set_suite_variable)

    def _decrypt_variable_in_scope(self, set_scope_variable):
        if self.variable_decryption:
            variables = self.builtin.get_variables()
            for var in variables:
                value = self.builtin.get_variable_value(var)
                if isinstance(value, str) and re.fullmatch(
                        self.crypto.CIPHER_PATTERN, value):
                    plain = self.get_decrypted_text(value)
                    set_scope_variable(var, plain)

    def _log_message(self, message):
        if self.value_list:
            pattern = re.compile("|".join(self.value_list))
            message.message = pattern.sub('***', message.message)
예제 #17
0
    def set_key_pair_from_string(self):  # 3.1.3
        questions = [{
            'type': 'input',
            'name': 'private_key_store',
            'message': 'Input private key store json:',
        }, {
            'type': 'password',
            'message': 'Enter the password to decrypt private key:',
            'name': 'password',
            'when': lambda answer: answer['private_key_store'] != ''
        }]

        new_password = [{
            'type': 'list',
            'name': 'new_pwd',
            'message': 'Do you want set a new password?',
            'choices': ['Yes', 'No'],
            'filter': lambda val: val.lower()
        }]

        save_password = [{
            'type': 'list',
            'name': 'save_pwd',
            'message': 'Do you want to save password?',
            'choices': ['Yes', 'No'],
            'filter': lambda val: val.lower()
        }]

        crypto = CryptoUtility()
        answer = prompt(questions, style=self.style)
        if answer['private_key_store'] != '':
            print('Setting key pair...')
            try:
                crypto.password = answer['password']
                if not crypto.set_private_key(answer['private_key_store']):
                    self.configure_key_pair()

                answer = prompt(new_password, style=self.style)
                if answer['new_pwd'] == 'yes':
                    crypto.password = self._set_password()

                answer = prompt(save_password, style=self.style)
                if answer['save_pwd'] == 'yes':
                    crypto.export_password_hash_to_file()
                else:
                    crypto.delete_password_hash_file()
                print(crypto.export_private_key_to_file())
                print(crypto.export_public_key_to_file())
                print('Key pair successfully generated!')
            except Exception as e:
                print(e)
        self.configure_key_pair()
예제 #18
0
 def __init__(self, ctx):
     self.crypto = CryptoUtility()
     LibraryComponent.__init__(self, ctx)