试图在Elixir(从Python代码转换)中创建sha256密钥和哈希
问题描述:
我正在创建使用Google云端存储的Elixir项目。我们的一些客户要求决定每个客户使用他们自己的单独加密密钥。试图在Elixir(从Python代码转换)中创建sha256密钥和哈希
我可以使用手动提供的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()))
我以为我把一些药剂代码做的伎俩:
key = 32 |> :crypto.strong_rand_bytes |> Base.encode64
hash = :sha256 |> :crypto.hash(key) |> Base.encode64
IO.puts "Key: #{key}\nSHA256 hash: #{hash}"
然而,当我尝试使用我的仙丹生成的密钥和哈希谷歌抱怨的所以:
{
"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}"
帕特里克,感谢您轻松没收。我不敢相信我没有注意到......太长时间了!就是这样。 –