본문 바로가기

TroubleShooting/Python

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 4: invalid start byte 해결

728x90
D:\download>certutil -hashfile python-3.10.11-amd64.exe
SHA1의 python-3.10.11-amd64.exe 해시:
bd8b24ec02138327f70f6a3179f6991cfc007a6f
CertUtil: -hashfile 명령이 성공적으로 완료되었습니다.

D:\download>

 

Windows 내 명령어인 certutil.exe 의 결과값 중에서 해시값을 이용할 일이 있어서 python 코드를 작성해 보았다.

import os
import sys
import subprocess

filepath = 'python-3.10.11-amd64.exe'
cmd = 'certutil.exe -hashfile '
command = cmd + filepath
result = subprocess.check_output(command)
# print(result)
hash_value = result.split('\r\n')[1]
print(hash_value)

 

certutil.exe 외부 명령어를 실행해서 결과 데이터중에서 원하는 값을 구할려고 subprocess.check_output() 을 사용했는데, 오류가 발생해서 result 값을 출력해보니 byte array 로 변환이 된거 같다.

b'SHA1\xc0\xc7 python-3.10.11-amd64.exe \xc7\xd8\xbd\xc3:\r\nbd8b24ec02138327f70f6a3179f6991cfc007a6f\r\nCertUtil: -hashfile \xb8\xed\xb7\xc9\xc0\xcc \xbc\xba\xb0\xf8\xc0\xfb\xc0\xb8\xb7\xce \xbf\xcf\xb7\xe1\xb5\xc7\xbe\xfa\xbd\xc0\xb4\xcf\xb4\xd9.\r\n'

 

구글에 해당 오류로 찾았을때, 디코딩하라는 얘기가 많아서 utf-8 로 했는데도 오류가 발생했다.

Traceback (most recent call last):
  File "D:\download\app.py", line 10, in <module>
    hash_value = result.decode('utf-8').split('\r\n')[1]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 4: invalid start byte

 

그런데, Windows 는 default character set 이 'cp949' 라서 result.decode('cp949') 로 해야하는 게 맞다.

 

 

 

참고

https://github.com/davidbombal/red-python-scripts/issues/4