Python3/Python3 language

[Python3] Exception has occurred: TypeError argument should be integer or bytes-like object, not 'str'

Razelo 2022. 6. 26. 08:20

최근 새롭게 만들고 있는 프로젝트에서 암호화와 관련된 작업을 하는 와중에 Exception has occurred: TypeError argument should be integer or bytes-like object, not 'str'

라는 예외를 만날 수 있었다. 

 

간단하게 해결할 수 있는 에러이다. 

 

파이썬에서 bytes와 str은 아래와 같은 관계가 성립한다. 

 

str -> 디코딩 -> bytes

bytes -> 인코딩 -> str 

 

그러므로 encode를 해주던, decode를 해주던 utf-8로 해주면 된다는 소리다. 

 

나 같은 경우는 RSA 키로 만든 public key와 private key가 결과물이 bytes 로 나왔는데 그걸 슬라이싱하려다가 발생한 오류였다. 

 

아래 코드를 보면 알겠지만 export_key() 에 이어서 decode 를 해주고 있다. 즉 지금은 해결된 상태이다. 하지만 이전 코드에서는 decode 를 쓰지 않았고 제목과 같은 에러를 만났다. 

 

from Crypto.PublicKey import RSA

key = RSA.generate(2048)
private_key = key.export_key().decode('utf-8')
public_key = key.publickey().export_key().decode('utf-8')
print(private_key)
print()
print(public_key)

 

 

반응형