尝试在 Elixir 中创建一个 sha256 密钥和散列(从 python 代码转换)

Trying to create a sha256 key and hash in Elixir (converting from python code)

我正在创建一个使用 Google 云存储的 Elixir 项目。我们的一些客户要求要求每个客户使用他们自己的单独加密密钥。

我可以使用手动提供的 Google 代码来创建它们,但是我想知道如何将其自动化(主要是出于我的好奇心)。 python 代码 provided by Google 是:

import base64
import hashlib
import os
key = os.urandom(32)
print "Key: %sSHA256 hash: %s" % (base64.encodestring(key), base64.encodestring(hashlib.sha256(key).digest()))

我以为我整理了一些 Elixir 代码来完成这个技巧:

key = 32 |> :crypto.strong_rand_bytes |> Base.encode64
hash = :sha256 |> :crypto.hash(key) |> Base.encode64
IO.puts "Key: #{key}\nSHA256 hash: #{hash}"

然而,当我尝试使用我的 Elixir 生成的密钥和散列时 Google 会这样抱怨:

{
  "domain": "global",
  "extendedHelp": "https://cloud.google.com/storage/docs/encryption#customer-supplied_encryption_keys",
  "message": "Missing a SHA256 hash of the encryption key, or it is not base64 encoded, or it does not match the encryption key.",
  "reason": "customerEncryptionKeySha256IsInvalid"
}

自然地,Python 代码有效,所以这里似乎有些不同。

有人知道这是为什么吗?谢谢!

似乎在 elixir 中,您正在散列 base64 编码的密钥,而原始 python 实现散列密钥的原始字节。

以下应该有效:

key = :crypto.strong_rand_bytes(32)
base64_key = Base.encode64(key)
base64_hash = :sha256 |> :crypto.hash(key) |> Base.encode64
IO.puts "Key: #{base64_key}\nSHA256 hash: #{base64_hash}"