Roco20099
Roco20099

Reputation: 33

Python: Decode base64 multiple strings in a file

I'm new to python and I have a file like this:

cw==ZA==YQ==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==dA==ZQ==cw==dA==

It's an keybord input, coded with base64, and new I want to decode it I try this by the code is stoping at first character decoded.

import base64

file = "my_file.txt"
fin = open(file, "rb")
binary_data = fin.read()
fin.close()
b64_data = base64.b64decode(binary_data)
b64_fname = "original_b64.txt"
fout = open(b64_fname, "w")
fout.write(b64_data)
fout.close

Any help is welcome. thanks

Upvotes: 2

Views: 1571

Answers (1)

BioGeek
BioGeek

Reputation: 22887

I assume that you created your test input string yourself.

If I split your test input string in blocks of 4 characters and decode each one apart, I get the following:

>>> import base64
>>> s = 'cw==ZA==YQ==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==dA==ZQ==cw==dA=='
>>> ''.join(base64.b64decode(s[i:i+4]) for i in range(0, len(s), 4))

'sdadasdasdasdasdtest'

However, the correct base64 encoding of your test string sdadasdasdasdasdtest is:

>>> base64.b64encode('sdadasdasdasdasdtest')
'c2RhZGFzZGFzZGFzZGFzZHRlc3Q='

If you place this string in my_file.txt (and rewriting your code to be a bit more concise) then it all works.

import base64

with open("my_file.txt") as f, open("original_b64.txt", 'w') as g:
    encoded = f.read()
    decoded = base64.b64decode(encoded)
    g.write(decoded)

Upvotes: 1

Related Questions