TypeError를 수정하는 방법:해싱하기 전에 유니코드 객체를 인코딩해야 하는가?
다음과 같은 오류가 있다.
Traceback (most recent call last):
File "python_md5_cracker.py", line 27, in <module>
m.update(line)
TypeError: Unicode-objects must be encoded before hashing
Python 3.2.2에서 이 코드를 실행하려고 할 때:
import hashlib, sys
m = hashlib.md5()
hash = ""
hash_file = input("What is the file name in which the hash resides? ")
wordlist = input("What is your wordlist? (Enter the file name) ")
try:
hashdocument = open(hash_file, "r")
except IOError:
print("Invalid file.")
raw_input()
sys.exit()
else:
hash = hashdocument.readline()
hash = hash.replace("\n", "")
try:
wordlistfile = open(wordlist, "r")
except IOError:
print("Invalid file.")
raw_input()
sys.exit()
else:
pass
for line in wordlistfile:
# Flush the buffer (this caused a massive problem when placed
# at the beginning of the script, because the buffer kept getting
# overwritten, thus comparing incorrect hashes)
m = hashlib.md5()
line = line.replace("\n", "")
m.update(line)
word_hash = m.hexdigest()
if word_hash == hash:
print("Collision! The word corresponding to the given hash is", line)
input()
sys.exit()
print("The hash given does not correspond to any supplied word in the wordlist.")
input()
sys.exit()
아마도 다음에서 문자 인코딩을 찾고 있을 것이다.wordlistfile
.
wordlistfile = open(wordlist,"r",encoding='utf-8')
또는 라인별로 작업하는 경우:
line.encode('utf-8')
편집
아래 코멘트 및 이 대답에 따라.
위의 답변은 원하는 출력이str
처음부터wordlist
만약 당신이 일하는 것이 편하다면bytes
, 그러면 당신은 사용하는 것이 더 낫다.open(wordlist, "rb")
하지만 기억해야 할 것은 당신의hashfile
사용해서는 안 된다rb
만약 당신이 그것을 의 산출물과 비교한다면hexdigest
.hashlib.md5(value).hashdigest()
a를 출력하다.str
바이트 개체와 직접 비교할 수 없는 경우:'abc' != b'abc'
. (이 주제에는 더 많은 것이 있지만, 나는 ATM 시간이 없다.)
또한 이 선은 다음과 같은 점에 유의해야 한다.
line.replace("\n", "")
아마 그럴 것이다.
line.strip()
그것은 바이트와 스트라스 둘 다에 효과가 있을 것이다.하지만 만약 당신이 단순히 로 변환하기로 결정한다면bytes
, 그런 다음 행을 다음으로 변경할 수 있다.
line.replace(b"\n", b"")
정의해야 한다.encoding format
맘에 들다utf-8
쉬운 방법을 써봐
이 예제는 SHA256 알고리즘을 사용하여 무작위 번호를 생성한다.
>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'
import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())
오류는 이미 네가 해야 할 일을 말해준다.MD5는 바이트로 작동하므로 유니코드 문자열을 인코딩하여bytes
, 예:line.encode('utf-8')
.
암호(PY3)를 저장하려면:
import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'
hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()
이 줄을 인코딩해서 고쳐줬어.
m.update(line.encode('utf-8'))
그 대답을 먼저 보십시오.
이제 오류 메시지가 명확해졌다. Python 문자열(이전에는 무엇이었는지)이 아니라 바이트만 사용할 수 있다.unicode
파이톤 < 3)에서는 원하는 인코딩으로 문자열을 인코딩해야 한다.utf-32
,utf-16
,utf-8
또는 제한된 8비트 인코딩(일부에서는 코드 페이지라고 부를 수도 있음) 중 하나일 수도 있다.
당신이 파일에서 읽을 때 당신의 워드리스트 파일의 바이트는 파이썬 3에 의해 유니코드로 자동 디코딩된다.다음 사항을 따르십시오.
m.update(line.encode(wordlistfile.encoding))
md5 알고리즘에 푸시된 인코딩 데이터가 기본 파일과 정확히 인코딩되도록 한다.
파일을 이진 모드로 열 수 있음:
import hashlib
with open(hash_file) as file:
control_hash = file.readline().rstrip("\n")
wordlistfile = open(wordlist, "rb")
# ...
for line in wordlistfile:
if hashlib.md5(line.rstrip(b'\n\r')).hexdigest() == control_hash:
# collision
단일 줄 문자열인 경우 b 또는 B로 포장하십시오.
variable = b"This is a variable"
또는
variable2 = B"This is also a variable"
이 프로그램은 해시 암호 목록이 포함된 파일을 읽고 영어 사전 단어 목록에서 해시 단어와 대조하여 확인하는 위 MD5 크래커의 버그가 없고 향상된 버전이다.도움이 되길 바란다.
나는 영어사전을 아래 링크 https://github.com/dwyl/english-words에서 다운받았다.
# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words
import hashlib, sys
hash_file = 'exercise\hashed.txt'
wordlist = 'data_sets\english_dictionary\words.txt'
try:
hashdocument = open(hash_file,'r')
except IOError:
print('Invalid file.')
sys.exit()
else:
count = 0
for hash in hashdocument:
hash = hash.rstrip('\n')
print(hash)
i = 0
with open(wordlist,'r') as wordlistfile:
for word in wordlistfile:
m = hashlib.md5()
word = word.rstrip('\n')
m.update(word.encode('utf-8'))
word_hash = m.hexdigest()
if word_hash==hash:
print('The word, hash combination is ' + word + ',' + hash)
count += 1
break
i += 1
print('Itiration is ' + str(i))
if count == 0:
print('The hash given does not correspond to any supplied word in the wordlist.')
else:
print('Total passwords identified is: ' + str(count))
sys.exit()
'programing' 카테고리의 다른 글
해시/앵커가 있는 페이지에 대한 nuxt 링크 탐색 문제 (0) | 2022.04.06 |
---|---|
Python 3으로 pip을 설치하는 방법? (0) | 2022.04.06 |
Vue.Js 2 입력 형식 번호 (0) | 2022.04.06 |
reactive native로 Android Wear 앱을 만들 수 있는가? (0) | 2022.04.06 |
Vue 앱(Vuetify.js 포함)에서 검증이 포함된 간단한 양식을 구현하는 방법 (0) | 2022.04.06 |