简体   繁体   中英

Length of the string is different after converting from base64

I have a string which is generated using C# Convert.ToBase64String

But after decoding the same string using ruby base64.decode , length of the string is different, what could be the issue.

C# encoded string:

dABlAHMAdAA=

ruby code

name=decrypt(ARGV[0])
puts "#{name.to_s}"
puts "#{name.to_s.length}"

def decrypt(input)
  return Base64.decode64(input)
end

ruby check_login.rb

dABlAHMAdAA=
test
8

dABlAHMAdAA= (test)

This looks like base64-encoded UTF-16.

dGVzdA==

Seems to be base64-encoded UTF-8 (which, for an ASCII-string like "test" is simply ASCII, since that's a subset of UTF-8 - but not of UTF-16).

So the original characters were encoded in different schemes, and then the actual bytes were base64-encoded.

To decode the String provided by Ruby (so we're adapting C# to Ruby )

  String source = "dABlAHMAdAA=";
  // test
  String result = Encoding.Unicode.GetString(Convert.FromBase64String(source));

To encode (so that Ruby can read it)

  String source = "test";
  // dABlAHMAdAA=
  String result = Convert.ToBase64String(Encoding.Unicode.GetBytes(source));

In both cases note Encoding.Unicode which stands fro UTF-16

Hack that works for ASCII:

Base64.decode64('dABlAHMAdAA=').delete "\u0000"
#⇒ "test"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM