krock1516
krock1516

Reputation: 461

How to decode the encoded values in base64 format in a file?

How to decode all the encoded values in base64 format in a file? Below is the File contents where the encoded vaule startswith MTAu i need to decode them.

SN: ols.com.,ptr=dc
PTR: ols.com
oncur: MTAuMTIzLjMzLjQ=
oncur: MTAuMTIzLjM1LjQ=
oncur: MTAuMzMuMzUuMTE0

SN:  pls.com.,ptr=dc
PTR: pls.com
oncur: MTAuMTIzLjMzLjQ=
oncur: MTAuMTIzLjM1LjQ=
oncur: MTAuMzMuMzUuMTE0

SN: qls.com.,ptr=dc
PTR: qls.com
oncur: MTAuMTIzLjMzLjQ=
oncur: MTAuMTIzLjM1LjQ=
oncur: MTAuMzMuMzUuMTE0

What I tried:

import base64

with open('testFile') as f:
    for line in f:
        if "MTAu" in line:
            ln = base64.b64decode(line)
            print(ln)

When i ran the above code it gives the type error:

Traceback (most recent call last):
  File "decod4.py", line 7, in <module>
    ln = base64.b64decode(line)
  File "/usr/lib64/python2.6/base64.py", line 76, in b64decode
    raise TypeError(msg)
TypeError: Incorrect padding

While trying with command line testing it works:

>>> import base64
>>> line="MTAuMTIzLjMzLjQ="
>>> base64.b64decode(line)
b'10.123.33.4'

Desired output:

SN: ols.com.,ptr=dc
PTR: ols.com
oncur: 10.123.33.4
oncur: 10.123.35.4
oncur: 10.123.33.114

SN:  pls.com.,ptr=dc
PTR: pls.com
oncur: 10.123.33.4
oncur: 10.123.35.4
oncur: 10.123.33.114

any help / direction Will be much appreciated.

Upvotes: 2

Views: 157

Answers (1)

salparadise
salparadise

Reputation: 5825

Looks like you need to clean up the line a bit, and you are trying to decode the entire line not just the encoded string. Try this:

with open('testFile') as f:
    for line in f:
        if 'MTAu' in line:
            dec_str, enc_str = line.split(':')
            ln = base64.b64decode(enc_str).decode()
            print('{}: {}'.format(dec_str, ln))
        else:
            print(line.rstrip())

Upvotes: 3

Related Questions