Search code examples
javarubyruby-on-rails-3unpack

To convert ruby unpack equivalent in java


I'm trying to understand this line of ruby code:

token.unpack('m0').first.unpack('H*').first

which is converting

R1YKdH//cZKubZlA09ZIVZQ5/cxInvmokIACnl3MKJ0=

to

47560a747fff7192ae6d9940d3d648559439fdcc489ef9a89080029e5dcc289d

As far as I understand this, it is base64 to hex conversion, but when I try to do the same thing, its not matching with converted one.

I need to implement the same functionality in Java.


Solution

  • So I'm going to break this down. The first step is token.unpack('m0'). According to Idiosyncratic Ruby unpack('m0') will decode base64, similarly to the built-in Base64 libararies Base64.decode64(string) function. But unpack returns an arry here, with only 1 element, the converted base64. So we use token.unpack('m0').first to get the first (and in this case the only) element of the array returned by token.unpack('m0'). If this was all, then you'd be correct to say that it's just base64. But, the unpacked base64 is unpacked again, this time with 'H*', which will convert the characters to hex. And finally, because that will return an array, you use first again to make it only a string.

    So in summary, what is happening is that first your string is being decoded from base64 to a string, then it's being converted to hex.