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)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With