'Terraform - SHA256 hash of bytes that have been base64-encoded

Let's say that I have three null bytes, and I base64-encode them:

(Python)

import base64
import hashlib

foo = b'\xd3\x4d\x34'

foo_b64 = base64.b64encode(foo)
print(foo_b64)
# Outputs: 
# 0000

foo_sha256 = hashlib.sha256(foo).hexdigest()
print(foo_sha256)
# Outputs: 
# 0e10e03565f4664a05c3bc63ed35df3e1a9cb2568371db4f12b66c728943f802

Let's say I put that base64 string in a Terraform config:

locals {
  foo_b64 = "0000"
}

In Terraform, I need to find a way to get the SHA256 hash of the raw value of foo, i.e. in Terraform I need to generate that same hash (0e10e03565f4664a05c3bc63ed35df3e1a9cb2568371db4f12b66c728943f802).

I've gone through the Terraform functions and can't seem to find something that works.

  • sha256(local.foo_b64) gives the SHA256 hash of the base64 string, not the raw bytes that it encodes.
  • sha256(base64decode(local.foo_b64)) throws an error: Call to function "base64decode" failed: the result of decoding the provided string is not valid UTF-8.

Is there any way to achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source