Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encoding from Node and openssl library produce different output

Why do the following produce different outputs?

  1. OpenSSL command line
echo Chris | openssl base64
# Q2hyaXMK
  1. Node.js
new Buffer('Chris').toString('base64')
// Q2hyaXM=

I'm trying to use the passport-http library for Basic authentication, and it appears to be expecting encoded data in the format of #1. This is a problem for me as all my tests rely on Node for generating encoded data (mocha, supertest).

like image 502
user2840450 Avatar asked Oct 30 '25 21:10

user2840450


1 Answers

The difference is that the echo command appends a newline character (\n) at the end of its output.

In other words, the Base64 encoding for Chris is indeed Q2hyaXM=, but the representation of Chris\n (where \n is just a newline character) is Q2hyaXMK.

You might want to compare with:

new Buffer('Chris\n')

... or better yet, we can find in the manual entry for echo that:

Options:
  -n    do not append a newline

So, simply using:

echo -n Chris | openssl base64
#    ^^

Would output Q2hyaXM= as expected!

like image 93
ccjmne Avatar answered Nov 02 '25 12:11

ccjmne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!