def set(self, new_value): encrypted_password = win32crypt.CryptProtectData( new_value, "Password", None, None, None, 0) base64_password = base64.b64encode(encrypted_password) # Add hash at end to force qouting by configobj module value = 'crypt:%s#' % base64_password self.caller.WpkgConfig[self.name] = value self.caller.configobj.write()
def encrypt_data(word): entropy = get_entropy() word_bytes = win32crypt.CryptProtectData(word.encode(), None, entropy, None, None, 0) encrypt_word = base64.b64encode(word_bytes).decode() return encrypt_word
def encrypt(str): encrypted = None if generic_utility.windows(): encrypted = win32crypt.CryptProtectData(str, None, None, None, None, 0) else: length = 16 - (len(str) % 16) encrypted = 'v10' + get_cipher().encrypt(str + chr(length) * length) return encrypted
def testSimple(self): data = str2bytes("My test.py data") entropy = None desc = "My description" flags = 0 ps = None blob = win32crypt.CryptProtectData(data, desc, entropy, None, ps, flags) got_desc, got_data = win32crypt.CryptUnprotectData(blob, entropy, None, ps, flags) self.failUnlessEqual(data, got_data) self.failUnlessEqual(desc, got_desc)
def seal_windpapi(secret: bytes, entropy=None) -> bytes: import win32crypt sealed = win32crypt.CryptProtectData( secret, None, # description entropy, None, # reserved None, # prompt 0x01) # flags return sealed
def testSimple(self): data = str2bytes("My test data") entropy = None desc = "My description" flags = 0 ps = None blob = win32crypt.CryptProtectData(data, desc, entropy, None, ps, flags) got_desc, got_data = win32crypt.CryptUnprotectData( blob, entropy, None, ps, flags) assert data == got_data assert desc == got_desc
def testEntropy(self): data = "My test data" entropy = "My test entropy" desc = "My description" flags = 0 ps = None blob = win32crypt.CryptProtectData(data, desc, entropy, None, ps, flags) got_desc, got_data = win32crypt.CryptUnprotectData( blob, entropy, None, ps, flags) self.failUnlessEqual(data, got_data) self.failUnlessEqual(desc, got_desc)
def testEntropy(self): data = str2bytes("My test data") entropy = str2bytes("My test entropy") desc = "My description" flags = 0 ps = None blob = win32crypt.CryptProtectData( data, desc, entropy, None, ps, flags) got_desc, got_data = win32crypt.CryptUnprotectData( blob, entropy, None, ps, flags) self.assertEqual(data, got_data) self.assertEqual(desc, got_desc)
def update_password(service, username, password): """ Updating the password of the service and username according to the input. :param service: :param username: :param password: password in plain text :return: Nothing """ password = win32crypt.CryptProtectData(password).encode("hex") conn = sqlite3.connect(PASSWORD_MANAGER_DB_PATH) cursor = conn.cursor() query = "UPDATE auth SET password = '******' where service = '{}' and username = '******'".format(password, service, username) cursor.execute(query) conn.commit()
def patch_license_expiration_date(data, reg_key, new_date): year_bytes = int.to_bytes(new_date.year, length=2, byteorder='little') month_bytes = int.to_bytes(new_date.month, length=2, byteorder='little') day_bytes = int.to_bytes(new_date.day, length=2, byteorder='little') data[-16] = year_bytes[0] data[-15] = year_bytes[1] data[-14] = month_bytes[0] data[-13] = month_bytes[1] data[-12] = day_bytes[0] data[-11] = day_bytes[1] encrypted_patched_data = win32crypt.CryptProtectData(data) winreg.SetValueEx(reg_key, DEFAULT_REG_KEY_NAME, 0, winreg.REG_BINARY, encrypted_patched_data)
def save_password(name, password): r"""Save password to user's private registry (encrypted). *name* is used to save a password on this machine and can be any string that complies with Windows's registry naming rules. *password* is the plain text password associated with *name*. Set *password* to None, to delete value from the registry. **TIP** I recommend you use the certificate expiration date as the name. Remebering when a cert will expire is a maintenance headache, and using this as the name will help with this chore. Example use:: >>> from signet.command.sign_code import * >>> save_password('Cert-1-Expires-2014-11', 'abc123') >>> get_saved_password('Cert-1-Expires-2014-11') 'abc123' """ if password is None: _winreg.DeleteKey(_winreg.HKEY_CURRENT_USER, "SOFTWARE\\signet\\%s" % name) return try: # Only import pywin32 dependency if user creates a project # that requires encrypted password. import win32crypt except ImportError: raise DistutilsModuleError("system missing required win32api " "module. You can download from " "http://sourceforge.net/projects/pywin32") # encrypt password using DPAPI (CRYPTPROECT_LOCAL_MACHINE) enc = win32crypt.CryptProtectData(password, name, None, None, None, 4) enc = base64.b64encode(enc) # create any missing subkeys key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "SOFTWARE\\signet") # save password _winreg.SetValue(key, name, _winreg.REG_SZ, enc)
def Save(self, profile_name): """Saves a profile""" content = pickle.dumps(self) if CurrentShell.CategoryName == "Windows": import win32crypt content = win32crypt.CryptProtectData(content, '', None, None, None, 0) with open( CurrentShell.CreateDataFilename(profile_name, suffix=self.PROFILE_EXTENSION), 'wb', ) as f: f.write(content)
def protect(plain_text: str) -> str: """Protects a sensitive string, such as a password, for persistence. Currently only available if in certain environments. Check protect.PROTECT_ENABLED for availability.""" if not PROTECT_ENABLED: raise ProtectDisabledException() description = 'win32crypto.py' reserved_field = None prompt_struct = None flags = CRYPTPROTECT_UI_FORBIDDEN | CRYPTPROTECT_LOCAL_MACHINE cipher_text = win32crypt.CryptProtectData(plain_text.encode(), description, __entropy, reserved_field, prompt_struct, flags) return base64.b64encode(cipher_text).decode()
def add_password(service, username, password): """ This func gets parameters for the file and add it. :param service: The wanted service, ex: 'GMAIL' :param username: :param password: Password in plain text, it will decrypt before saving. :return: Nothing """ date = str(datetime.date.today()) password = win32crypt.CryptProtectData(password).encode("hex") insert_query = "INSERT INTO auth(service, username, password, insert_date)" \ "VALUES('{}','{}','{}','{}')".format(service, username, password, date) conn = sqlite3.connect(PASSWORD_MANAGER_DB_PATH) cursor = conn.cursor() cursor.execute(insert_query) conn.commit() cursor.close() conn.close()
def Rdp(username, passwd, rdpFileName, pos): print("login: {0} , pos: {1}".format(username, pos)) pwdHash = win32crypt.CryptProtectData(passwd, u'psw', None, None, None, 0) # 算出密码Hash值 pwdHash_ok = binascii.hexlify(pwdHash) # print("加密后的密码:" + str(pwdHash_ok)) # 这个逻辑好像有误,注释掉了 # str(pwdHash_ok).split("'")[1] # 转换为字符串并使用切割法去掉内容前面的'b',保留数据本体内容 str1 = str(pwdHash_ok) rdpFileStr = u'''screen mode id:i:1 desktopwidth:i:1440 desktopheight:i:900 session bpp:i:24 winposstr:s:1,1,{pos_ok} full address:s:10.1.2.199:3389 compression:i:1 keyboardhook:i:2 audiomode:i:0 redirectdrives:i:0 redirectprinters:i:0 redirectcomports:i:0 redirectsmartcards:i:1 displayconnectionbar:i:0 autoreconnection enabled:i:1 username:s:{username_ok} domain:s:MyDomain shell working directory:s: password 51:b:{pwdHash_ok} disable wallpaper:i:1 disable full window drag:i:1 disable menu anims:i:1 disable themes:i:0 disable cursor setting:i:0 bitmapcachepersistenable:i:1 '''.format(pos_ok=pos, username_ok=username, pwdHash_ok=str1) with io.open(rdpFileName, 'w', encoding='utf-16-le') as f: f.write(rdpFileStr)
fs = forward(remote=(sp['tunHost'], int(sp['tunPort'])), ticket=sp['ticket'], timeout=sp['tunWait'], check_certificate=sp['tunChk']) # type: ignore # Check that tunnel works.. if fs.check() is False: raise Exception( '<p>Could not connect to tunnel server.</p><p>Please, check your network settings.</p>' ) thePass = six.binary_type(sp['password'].encode('UTF-16LE')) # type: ignore try: password = codecs.encode( win32crypt.CryptProtectData(thePass, None, None, None, None, 0x01), 'hex').decode() except Exception: # Cannot encrypt for user, trying for machine password = codecs.encode( win32crypt.CryptProtectData(thePass, None, None, None, None, 0x05), 'hex').decode() # The password must be encoded, to be included in a .rdp file, as 'UTF-16LE' before protecting (CtrpyProtectData) it in order to work with mstsc theFile = sp['as_file'].format( # type: ignore password=password, address='127.0.0.1:{}'.format(fs.server_address[1])) filename = tools.saveTempFile(theFile) executable = tools.findApp('mstsc.exe') if executable is None:
def _encryptPassword(self, password): hash = win32crypt.CryptProtectData(password.decode('utf-8'), u'psw', None, None, None, 0) password = binascii.hexlify(hash) password = password.upper() return password
def CryptRDPPass(ClearPass): pwdHash = win32crypt.CryptProtectData(unicode(ClearPass), 'pwd', None, None, None, 0) return binascii.hexlify(pwdHash)
import os, sqlite3, shutil, win32crypt banco = os.getenv("LOCALAPPDATA") + \ "\\Google\\Chrome\\User Data\\Default\\Cookies" banco2 = banco + "2" shutil.copyfile(banco,banco2) conexao = sqlite3.connect(banco) consulta = conexao.cursor() comando = "SELECT name, encrypted_value FROM cookies WHERE host_key='.facebook.com' \ AND (name='datr' OR name='c_user' OR name='xs')" consulta.execute(comando) for nome, valor in consulta.fetchall(): valor = win32crypt.CryptProtectData(valor) print nome + "=" + valor[1].decode("ISO-8859-1") + "\n" conexao.close() os.remove(banco2)
def _update_file(cls, filepath, plain_data, meta_data): # type: (str, dict) -> None with open(filepath, "wb") as fp: data = plain_data.copy().update(meta_data) data[cls._UPDATE_TIME] = time.time() fp.write(win32crypt.CryptProtectData(pickle.dumps(data)))
# Saved as .py for easier editing from __future__ import unicode_literals # pylint: disable=import-error, no-name-in-module import win32crypt # @UnresolvedImport import os import subprocess from uds.log import logger # @UnresolvedImport from uds import tools # @UnresolvedImport import six try: thePass = six.binary_type('{m.password}'.encode('UTF-16LE')) password = win32crypt.CryptProtectData(thePass, None, None, None, None, 0x01).encode('hex') except Exception: logger.info('Cannot encrypt for user, trying for machine') password = win32crypt.CryptProtectData(thePass, None, None, None, None, 0x05).encode('hex') # The password must be encoded, to be included in a .rdp file, as 'UTF-16LE' before protecting (CtrpyProtectData) it in order to work with mstsc theFile = '''{m.r.as_file}'''.format(password=password) filename = tools.saveTempFile(theFile) executable = tools.findApp('mstsc.exe') subprocess.Popen([executable, filename]) tools.addFileToUnlink(filename) # QtGui.QMessageBox.critical(parent, 'Notice', filename + ", " + executable, QtGui.QMessageBox.Ok)
""" __author__ = 'LiTian' # -*- coding:utf-8 -*- import wx import wx.lib.analogclock as ac import wx.lib.agw.aquabutton as AB import wx.gizmos as gizmos import time import random, os, sys import binascii import win32crypt, cmd u_pwd = unicode('123456') # 密码 pwdHash = win32crypt.CryptProtectData(u_pwd, u'', None, None, None, 0) pwd = 'password 51:b:' + binascii.hexlify(pwdHash).upper() # 密码加密 uname = 'username:s:' # RDP文件的用户名前缀(他就这么用的、、、) keys = ['IE6', 'IE7', 'IE8', 'IE9', 'IE10', 'win32IE11', 'win64IE11'] for mname in keys: if not os.path.exists('./rdp/' + mname + '.rdp'): model = open('./model/' + mname + '.txt') mdate = model.read() new = open('./rdp/' + mname + '.rdp', 'w') new.write(mdate) new.write(uname + "admin") new.write("\n") new.write(pwd) new.close()
# This is a template # Saved as .py for easier editing from __future__ import unicode_literals # pylint: disable=import-error, no-name-in-module from PyQt4 import QtCore, QtGui import win32crypt # @UnresolvedImport import os import subprocess from uds import tools # @UnresolvedImport import six # The password must be encoded, to be included in a .rdp file, as 'UTF-16LE' before protecting (CtrpyProtectData) it in order to work with mstsc theFile = '''{m.r.as_file}'''.format(password=win32crypt.CryptProtectData(six.binary_type('{m.password}'.encode('UTF-16LE')), None, None, None, None, 0x01).encode('hex')) filename = tools.saveTempFile(theFile) executable = tools.findApp('mstsc.exe') subprocess.call([executable, filename]) tools.addFileToUnlink(filename) # QtGui.QMessageBox.critical(parent, 'Notice', filename + ", " + executable, QtGui.QMessageBox.Ok)
try: # Cleanup the json files to make them easier for humans to evaluate later. data = json.load(open(filename,'r')) open(filename,'w').write(json.dumps(data, indent=1)) except: print(" [-] Error loading json %s" % filename) return data # This is sparse right now, but we'll be adding more browsers ASAP... # Ok, we're going to add Firefox and that's probably it. :-) if __name__ == "__main__": for d in __doc__.splitlines(keepends=False): if len(d): print(d) else: break print() print("[+] User: "******"thequickbrownfoxjumpedoverthelazydog" cyphertext = win32crypt.CryptProtectData(plaintext) if not plaintext == win32crypt.CryptUnprotectData(cyphertext)[1]: print("Windows DPAPI not working. Is this a logged in user?") sys.exit(0) b = ChromiumScanner() browsers = b.enum_browsers()
Programming Language: Python :: 2.7 Topic: Utilities """ from base64 import b64encode import win32crypt pDataIn = "My test data" # the plaintext to be encrypted. # A string with a readable description of the data to be encrypted. # This description string is included with the encrypted data. This parameter is optional and can be set to None. szDataDescr = "My description" pOptionalEntropy = None pvReserved = None pPromptStruct = None dwFlags = 0 # CRYPTPROTECT_LOCAL_MACHINE # https://docs.microsoft.com/en-us/previous-versions/aa922939(v=msdn.10)?redirectedfrom=MSDN#remarks # Only a user with logon credentials matching those of the encrypter can decrypt the data. # In addition, decryption usually can only be done on the computer where the data was encrypted. pDataOut = win32crypt.CryptProtectData(pDataIn, szDataDescr, pOptionalEntropy, pvReserved, pPromptStruct, dwFlags) print(pDataOut) print(b64encode(pDataOut)) pDescrOut, pDataOut = win32crypt.CryptUnprotectData(pDataOut, pOptionalEntropy, pvReserved, pPromptStruct, dwFlags) print(pDescrOut, pDataOut)
def get_argu(index: int, name: str =""): try: return sys.argv[index] except: print(f"ERROR: missing {name if len(name) > 1 else index}") sys.exit() server_ip = get_argu(1, "ip") rdpUser = get_argu(2, "username") password = get_argu(3, "password") base_path = "" try: base_path = sys._MEIPASS except: pass pwdHash = win32crypt.CryptProtectData(password.encode("utf8"),'psw',None,None,None,0) rdpPwd = str(binascii.hexlify(pwdHash).decode("utf8")).upper() rdpTemp = open(os.path.join(base_path, "rdp.txt")).read() rdpTemp += f"\nusername:s:{rdpUser}" rdpTemp += f"\npassword 51:b:{rdpPwd}" rdpTemp += f"\nfull address:s:{server_ip}" theRdp_path = os.path.join(base_path, 'theRdp.rdp') theRdpFile = open(theRdp_path, 'w', encoding="utf8") theRdpFile.write(rdpTemp) theRdpFile.close() os.system(f"mstsc {theRdp_path} /f")