PyF2使用二进制解密

2024-10-02 14:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在编程一个脚本,通过使用字典(在python上)为学校解密pdf。我使用的是PyPDF2库,但是我在解密PDF文件时遇到了问题,因为它是用拉丁语1编码的,而且PyPDF2似乎无法处理这个编码的文件。我已经在其他PDF文件(非拉丁语1编码)上检查了我的脚本,并且它可以工作,所以我需要在UTF-8上对PDF文件进行编码,或者让PyPDF2在latin-1上工作。在

我的剧本是这样的:

import PyPDF2
import os

probadas = []           # Lista gobal con todas las claves probadas
errores = []            # Lista global de palabras que dieron fallo


def ejecuta():
    res = "Clave no encontrada en ningun diccionario."
    dir = './diccionarios/ingles'
    for file in os.listdir(dir):
        if file.endswith(".txt"):
            if diccionario(file):
                res = "Clave encontrada en el diccionario: " + file
                return res
    return res


def reglas(texto):
    vocales = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    res = True
    text = texto[:1].lower() + texto[1:]
    for i in text:
        res = res and (i in vocales)
    return res  



def diccionario(diccionario):
    pdf = PyPDF2.PdfFileReader(open('apuntes.pdf', 'rb'))      # Abre el archivo pdf a desencriptar             
    file = open('./diccionarios/ingles/' + diccionario, "r", encoding="utf8", errors='ignore')    # Abre el diccionario especificado
    temp = file.read().splitlines()                                    # Separa las palabras por lineas, evitando que aparezca '\n' al final de las palabras

    global probadas                                                # Lista de claves ya probadas.
    global errores                                                 # Lista de claves que dan fallo

    res = False                                                        # Clave no encontrada
    palabra = ''
    cont = 0

    print("\n--- Probando las combinaciones de: " + diccionario)

    for palabra in temp:
        i = palabra.rstrip() 
        cont += 1
        if len(i) < 5 or not reglas(i) or i in probadas:
            pass
        else:
            if cont % 10000 == 0 and cont != 0:
                print(" Probadas " + str(cont) + " combinaciones. Actual: " + i)            
            try:
                if pdf.decrypt(i.lower()):                      #i.lower().encode('latin-1')                   # Si se desencripta termina el programa y muestra la contrasena
                    print("\n La contrasena es: " + i)  
                    res = True                  
                    break
                    return res
                else:
                    probadas.append(i)  
            except UnicodeEncodeError as error:
                print("Error: " + i + " Info: " + str(error))
                errores.append(i)
                pass
            palabra = i 
    print("\nProbadas todas las "+ str(cont) + " combinaciones del diccionario: " + diccionario + ".  Total claves probadas: " + str(len(probadas)) + ".  Ultima clave probada: " + palabra)
    if not res:
        print("Clave no encontrada.")   
    return res      




# EJECUCION DEL SCRIPT

ejecuta()


input("\nPress enter to exit. ")

所以我想解密文件“apuntes.pdf“使用“/diccionarios/ingles/”目录中的字典,错误就出现在命令:pdf=PyPDF2.PdfFileReader(open('apuntes.pdf','rb'))如果pdf.解密(i.lower()): 当我试图用任何单词解密时,它会返回以下消息:**

--Probando las combinaciones de:0_diccionarioungles1.txt

错误:aahed Info:“latin-1”编解码器无法对位置0中的字符“\u015e”进行编码:序号不在范围内(256)

那么我该怎么做才能让我的脚本在PDF上工作呢?在

谢谢


Tags: 文件in编码returnifpdfderes