Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plus sign in Base64.encode64 output?

Tags:

python

ruby

I am using Base64.encode64 to create a hash from HMAC used in an API request (an API that I did not develop). The generated hashes sometimes included a "+". The requests that included the "+" fail. Requests without succeed.

The same kind of script in Python, for example, never has a "+" in the Base64 encoded hash.

Below are the two snippets. Again, the Python never has a "+", the Ruby sometimes does.

Any ideas what is going on? How can I keep Ruby's base64 encoding from using "+" characters?

Ruby:

hmac = OpenSSL::HMAC.digest('sha256', hmackey, request_string)
signature = URI::encode(Base64.encode64(hmac))

Python:

hmac = hmac.new(self.hmackey, urltosign, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(hmac)
like image 830
Matt Fordham Avatar asked Mar 01 '14 00:03

Matt Fordham


People also ask

Does Base64 have plus sign?

Base64 encoding takes three bytes of binary data and encodes it into four bytes of printable ASCII, which includes the letters A through Z (both upper- and lowercase), the numbers 0 through 9, and the plus sign and forward slash characters.

What does == mean in Base64?

When decoding Base64 text, four characters are typically converted back to three bytes. The only exceptions are when padding characters exist. A single = indicates that the four characters will decode to only two bytes, while == indicates that the four characters will decode to only a single byte.

What does Base64 b64encode return?

b64encode(): Encodes the bytes-like object using Base64 and return the encoded bytes. base64. b64decode(): Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.

What symbols are in Base64?

Base64 only contains A–Z , a–z , 0–9 , + , / and = . So the list of characters not to be used is: all possible characters minus the ones mentioned above. For special purposes . and _ are possible, too.


1 Answers

Python uses the RFC 3548 for the base64 conversion. Other languages like Ruby, Java(Possibly RFC 2045) they may be using different RFC for the conversion. So you may find few are using / and few are using + on their encoded string.

So if you then you need to match with them, just replace the characters with equivalent one after the encoding.

like image 196
Sabuj Hassan Avatar answered Sep 18 '22 15:09

Sabuj Hassan