Change the terminal key. The encrypted_key is a hex string.
        encrypted_key is expected to be encrypted under master key
191334
def set_terminal_key(self, encrypted_key):
        
        if encrypted_key:
            try:
                new_key = bytes.fromhex(encrypted_key)
                if len(self.terminal_key) != len(new_key):
                    # The keys must have equal length
                    return False

                self.terminal_key = self.tmk_cipher.decrypt(new_key)
                self.store_terminal_key(raw2str(self.terminal_key))

                self.tpk_cipher = DES3.new(self.terminal_key, DES3.MODE_ECB)
                self.print_keys()
                return True

            except ValueError:
                return False

        return False
75403
def import_gpg_key(key):
    """"""
    if not key:
        raise CryptoritoError('Invalid GPG Key')

    key_fd, key_filename = mkstemp("cryptorito-gpg-import")
    key_handle = os.fdopen(key_fd, 'w')

    key_handle.write(polite_string(key))
    key_handle.close()
    cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename])
    output = stderr_output(cmd)
    msg = 'gpg: Total number processed: 1'
    output_bits = polite_string(output).split('\n')
    return len([line for line in output_bits if line == msg]) == 1
569083
public boolean setRxMasterKey(byte[] key) {
		boolean res = false;
		if ((key.length == MASTER_KEY_SIZE_32_BYTES)
				|| (key.length == MASTER_KEY_SIZE_16_BYTES)) {
			rxMasterKey = null;
			rxMasterKey = platform.getUtils().copy(key);
			res = true;
			logDebug("setRxMasterKey "
					+ platform.getUtils().byteToHexString(rxMasterKey));
		} else {
			logError("Wrong length iRxMasterKey: " + key.length);
		}
		return res;
	}
908628
def get_encrypted_pin(self, clear_pin, card_number):
        
        if not self.terminal_key:
            print('Terminal key is not set')
            return ''

        if self.pinblock_format == '01':
            try:
                pinblock = bytes.fromhex(get_pinblock(clear_pin, card_number))
                #print('PIN block: {}'.format(raw2str(pinblock)))
            except TypeError:
                return ''

            encrypted_pinblock = self.tpk_cipher.encrypt(pinblock)
            return raw2str(encrypted_pinblock)

        else:
            print('Unsupported PIN Block format')
            return ''
172471
def _replace_auth_key(
        user,
        key,
        enc='ssh-rsa',
        comment='',
        options=None,
        config='.ssh/authorized_keys'):
    '''
    
    '''

    auth_line = _format_auth_line(key, enc, comment, options or [])

    lines = []
    full = _get_config_file(user, config)

    try:
        # open the file for both reading AND writing
        with salt.utils.files.fopen(full, 'r') as _fh:
            for line in _fh:
                # We don't need any whitespace-only containing lines or arbitrary doubled newlines
                line = salt.utils.stringutils.to_unicode(line.strip())
                if line == '':
                    continue
                line += '\n'

                if line.startswith('#'):
                    # Commented Line
                    lines.append(line)
                    continue
                comps = re.findall(r'((.*)\s)?(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s([a-zA-Z0-9+/]+={0,2})(\s(.*))?', line)
                if comps and len(comps[0]) > 3 and comps[0][3] == key:
                    # Found our key, replace it
                    lines.append(auth_line)
                else:
                    lines.append(line)
            _fh.close()
            # Re-open the file writable after properly closing it
            with salt.utils.files.fopen(full, 'wb') as _fh:
                # Write out any changes
                _fh.writelines(salt.utils.data.encode(lines))
    except (IOError, OSError) as exc:
        raise CommandExecutionError(
            'Problem reading or writing to key file: {0}'.format(exc)
        )
1248647
def dumpkey(key):
    
    def hex3fy(key):
        """Helper to convert string into hex string (Python 3 compatible)"""
        from binascii import hexlify
        # Python 3 strings are no longer binary, encode them for hexlify()
        if PY3K:
           key = key.encode('utf-8')
        keyhex = hexlify(key).upper()
        if PY3K:
           keyhex = keyhex.decode('utf-8')
        return keyhex
    if type(key) == str:
        return hex3fy(key)
    else:
        return ' '.join( [hex3fy(s) for s in key] )
56279
def change_password(self, password):
        
        self.update(password_hash=self.encrypt_password(password),
                    require_password_change=False)

        # Whenever the password is changed, reset the secret key to invalidate
        # any tokens in the wild
        self.reset_secret_key()
204092
def encrypt_password(self):
        
        if self.password and not self.password.startswith('$pbkdf2'):
            self.set_password(self.password)
1317038
def set_tcp_md5sig(s, addr, key):
    
    impls = {
        'FreeBSD': _set_tcp_md5sig_bsd,
        'Linux': _set_tcp_md5sig_linux,
        'NetBSD': _set_tcp_md5sig_bsd,
    }
    system = platform.system()
    try:
        impl = impls[system]
    except KeyError:
        raise NotImplementedError("TCP-MD5 unsupported on this platform")
    impl(s, addr, key)
1334675
def set_key(key: str, value: str) -> dict:
    
    if not _conf.path:
        return {}

    if "toml" in _conf.path:
        with open(_conf.path, "r") as f:
            parser = parse(f.read())
        parser["tool"]["commitizen"][key] = value
        with open(_conf.path, "w") as f:
            f.write(parser.as_string())
    else:
        parser = configparser.ConfigParser()
        parser.read(_conf.path)
        parser["commitizen"][key] = value
        with open(_conf.path, "w") as f:
            parser.write(f)

    return _conf.config
260487
def update_credentials(self, key, secret):
        '''  '''
        self.access_key = key
        self.secret_key = secret
1197300
def unlock_key(self, data):
        
        if data.startswith(b'h:'):
            new = binascii.unhexlify(data[2:])
        else:
            new = data
        if len(new) == 6:
            self.unlock_code = new
            if not self.access_code:
                # Don't reset the access code when programming, unless that seems
                # to be the intent of the calling program.
                self.access_code = new
        else:
            raise yubico_exception.InputError('Unlock key must be exactly 6 bytes')
1358917
def rename_key(pki_dir, id_, new_id):
    '''
    
    '''
    oldkey = os.path.join(pki_dir, 'minions', id_)
    newkey = os.path.join(pki_dir, 'minions', new_id)
    if os.path.isfile(oldkey):
        os.rename(oldkey, newkey)
541234
def update(self, key, value):
        
        if not is_string(key):
            raise Exception("Key must be string")

        # if len(key) > 32:
        #     raise Exception("Max key length is 32")

        if not is_string(value):
            raise Exception("Value must be string")

        # if value == '':
        #     return self.delete(key)
        old_root = copy.deepcopy(self.root_node)
        self.root_node = self._update_and_delete_storage(
            self.root_node,
            bin_to_nibbles(to_string(key)),
            to_string(value))
        self.replace_root_hash(old_root, self.root_node)
322825
def _prepare_key(key, *args, **kwargs):
    

    if not args and not kwargs:
        return key

    items = sorted(kwargs.items())
    hashable_args = (args, tuple(items))
    args_key = hashlib.md5(pickle.dumps(hashable_args)).hexdigest()

    return "%s/args:%s" % (key, args_key)
545004
def getSecurityHkey(self, s):
        '''
        
        '''
        try:
            return self.hkeys_security[s]
        except KeyError:
            raise CommandExecutionError((
                'No HKEY named "{0}".  It should be one of the following:  {1}'
                ).format(s, ', '.join(self.hkeys_security)))
1227084
def _convert_key_to_str(key):
    '''
    
    '''
    # IMPORTANT: on PY2, the secret key must be str and not unicode to work
    # properly with hmac.new (see http://bugs.python.org/issue5285)
    #
    # pylint: disable=incompatible-py3-code,undefined-variable
    return salt.utils.data.encode(key) \
        if six.PY2 and isinstance(key, unicode) \
        else key