简体   繁体   中英

Comparing bytes[] and String.getBytes()

I'm debugging my custom implementation of OAuth ( shindig and spring-security-oauth libraries).

Regardless of shindig and spring-security details, I create a hash using sha() and then pass it to spring-security-oauth. I expect the hashes to be equal, but they're not.

shindig

bytes[] shindigHash = sha(someBytes); // docs for sha()

spring-security-oauth

bytes[] b = str.getBytes("UTF-8");` // String str passed in from 

I also tried bytes[] b = str.getBytes(); for the default encoding, but it didn't equal shindigHash when I compared each of b 's and shindigHash 's elements.

EDIT

for j = 0 .. b.length // same as shindigHash length
   print shindigHash[j] ... b[j]
end
visually compare results

getBytes() does not return a hash. It returns the byte representation of a string. So they will never correspond.

One possible representation of a SHA-1 (or some other hash) is a string of hex digits.

"af45deadbeef"

That's a string. Calling getBytes() on it does not return the value of the hash. Why?

Well, consider a trivial hash:

000000000000000

That's a bunch of zero bytes. the byte[] would be { 0, 0, 0, ... } .

However,

"00000000000000".getBytes("utf-8")

will return

 { 30, 30, 30, 30, 30, 30 .... } /* those are hex 30's */

The UTF-8 representation of '0' is 0x30, not 0x00.

So, if the string contains the hex representation of a hash, then you will need to either convert the byte[] to a String containing it's hex representation, or convert the string to a byte[] by converting each pair of characters to a byte .

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