What does it mean to compute a SHA-256 hash in the form of a byte array?
What part are you struggling with?
A byte array is literally a sequence of bytes in memory… basically what every data structure ever finally boils down to.
Generally, the SHA-256 hash we see in the wild is a base 16 encoded string of raw bytes.
If you need to get the string representation, try:
:crypto.hash(:sha256, "hello,world.") |> Base.encode16(case: :lower)
# "b14ffeca6ce84ea431f4f6bb30eaeea4c784921db91324d7860089afa5c7ab9f"
The following sample payload from Cybersource is an example:
%{
clientReferenceInformation: %{
code: "cybs_test",
partner: %{
developerId: "7891234",
solutionId: "89012345"
}
},
paymentInformation: %{
card: %{
type: "001",
expirationMonth: "12",
expirationYear: "2025",
number: "4000000000000101"
}
}
}
Result:
02ch2iBcHFkXxbWg/rr2aGHFSr2Oqhlhcu2r4uOWGYw=
Using :crypto.hash with :sha256, and encoding the resulting byte array in base64, does not give the result above, hence my question…
Because of the trailing char of above string is a =
, I suspect this hash is encoded by base32 or base64.
You can try Base.encode32
or Base.encode64
.
Because the sample payload is not well formatted, I can’t help to test that.
Base64 did not work.
Trying out base32 to see.
it still didn’t work.
I have formatted the payload properly.
It’s supposed to be json encoded before generating the hash.
It’s difficult to say for sure without seeing the code, but I suspect the JSON that’s being hashed doesn’t match what the example expects. The example you showed was written as Elixir maps, which don’t maintain any particular ordering of their keys.
The JSON {"first":"value1","second":"value2"}
and {"second":"value2","first":"value1"}
are equivalent for most purposes, and encoding %{"first"=>"value1", "second" => "value2"}
may give you either one.
However, the one purpose those two JSON strings aren’t equivalent for is hashing. I don’t see any mention in the Cybersource docs of a required sorting-order for keys, so their API would presumably be fine with either JSON form as long as the hash matches.
Thank you @al2o3cr