1

I'm trying to encode and decode a base64 string. It works fine normally, but if I try to restrict the hash to 6 digits, I get an error on decoding:

from base64 import b64encode
from base64 import b64decode

s="something"

base 64 encode/decode:

# Encode:
hash = b64encode(s)
# Decode:
dehash = b64decode(hash)
print dehash

(works)

6-digit base 64 encode/decode:

# Encode:
hash = b64encode(s)[:6]
# Decode:
dehash = b64decode(hash)
print dehash

TypeError: Incorrect padding

What am I doing wrong?


UPDATE:

Based on Mark's answer, I added padding to the 6-digit hash to make it divisible by 4:

hash = hash += "=="

But now the decode result = "some"

UPDATE 2

Wow that was stupid ..

2
  • 1
    Why does the updated result surprise you? Are you expecting to get the entire original string somehow magically/fractally encoded to 6 bytes? Commented Jan 13, 2012 at 21:02
  • oh man- im an idiot - trying to encode a longer string into a shorter hash... sorry for wasting your guys time Commented Jan 13, 2012 at 21:12

1 Answer 1

4

Base64 by definition requires padding on the input if it does not decode into an integral number of bytes on the output. Every 4 base64 characters gets turned into 3 bytes. Your input length does not divide evenly by 4, thus there's an error.

Wikipedia has a good description of the specifics of Base64.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.