为何两段相似的SHA512转Base64代码执行结果不同?
Hey Josh, let's dig into why these two snippets are giving mismatched results—this is a super common pitfall with hashing and encoding workflows, so you're not alone here! Here are the most likely culprits:
Character Encoding Discrepancies
The first and most frequent issue is how each snippet converts the input string to a byte array before hashing. Standard practice (and what online tools use) is to use UTF-8 encoding, but if one snippet uses a different encoding (like UTF-16, ISO-8859-1, or your system's default encoding), it'll generate completely different raw bytes for the same string. For example, the string"test"in UTF-8 is 4 bytes, but in UTF-16 it's 8 bytes—so the SHA512 hash will be totally unrelated.Extra Hex Conversion Step
I've seen this a lot: one snippet directly converts the SHA512 byte array to Base64, while the other first converts the hash bytes to a hexadecimal string, then converts that hex string back to bytes, and finally encodes to Base64. That extra detour changes the data entirely. Let's visualize:- Correct flow:
Input String → UTF-8 Bytes → SHA512 Bytes → Base64 String - Broken flow:
Input String → UTF-8 Bytes → SHA512 Bytes → Hex String → UTF-8 Bytes of Hex → Base64 String
Online tools use the first flow, so the second will never match.
- Correct flow:
Non-Standard Base64 Variants
Not all Base64 implementations are identical. Some snippets might use URL-safe Base64 (which replaces+with-and/with_, and omits padding=), while others use the standard RFC 4648 Base64. If your two snippets use different variants, their output strings will differ even if the underlying hash is the same.Unaccounted-For Whitespace
If one snippet trims leading/trailing whitespace from the input string (with something liketrim()) and the other doesn't, you're effectively hashing two different strings. Even a single space at the start or end will make the SHA512 hash unrecognizable.
How to Debug This
To pinpoint the exact issue, run both snippets with a simple test string (like "hello world") and print out each intermediate step:
- The raw byte array of the input string (displayed in hex)
- The SHA512 hash byte array (displayed in hex)
- The final Base64 string
Compare these outputs step by step—whichever step differs first is your root cause.
内容的提问来源于stack exchange,提问作者Josh

