I am trying to replicate a base32 encoding of a sha256 hash from go in python. I am trying to replicate the logic by which kube-router creates ipset names for namespace-networkpolicies: https://github.com/cloudnativelabs/kube-router/blob/736757d942f173e19566eea0a512dfa819699126/pkg/controllers/netpol/network_policy_controller.go#L1476
I just cannot get python to yield the same base32 output. I am probably doing something obviously wrong. Help!
Go Code:
package main
import (
"fmt"
"crypto/sha256"
"encoding/base32"
)
func main() {
namespace := "my-ns"
policyName := "default-deny"
chksum := sha256.Sum256([]byte(namespace + policyName))
fmt.Printf("%x\n", chksum)
fmt.Println(base32.StdEncoding.EncodeToString(chksum[:]))
fmt.Println(base32.StdEncoding.EncodeToString([]byte("abc")))
}
running this yields:
dd684919ef4a1362b841409f5255ec963bd53d353804114779c4e6d66641eb28
3VUESGPPJIJWFOCBICPVEVPMSY55KPJVHACBCR3ZYTTNMZSB5MUA====
MFRGG===
Python Code:
#!/usr/bin/env python
import hashlib
import base64
namespace = "my-ns"
policyName = "default-deny"
sha256 = hashlib.sha256()
sha256.update(namespace+policyName)
chksum = sha256.hexdigest()
print chksum
print base64.b32encode(chksum)
print base64.b32encode(bytearray("abc"))
running this yields:
dd684919ef4a1362b841409f5255ec963bd53d353804114779c4e6d66641eb28
MRSDMOBUHEYTSZLGGRQTCMZWGJRDQNBRGQYDSZRVGI2TKZLDHE3DGYTEGUZWIMZVGM4DANBRGE2DONZZMM2GKNTEGY3DMNBRMVRDEOA=
MFRGG===
The first lines of output in each agree, which is good. lets me know that the sha256 checksum is being computed the same on each side. The second line on each doesn't agree, I do not understand why -- I have tried many different casts of the chksum in the python code to no avail. The third line in each just suggests that a base32 encoding of a simple string seems to work on both sides.
On the Python side you're getting the SHA256 hash hex-encoded, and then base32 encoding the hexadecimal digits. To fix it, use the following:
sha256 = hashlib.sha256()
sha256.update(namespace+policyName)
chksum = sha256.digest() # Get hash as byte string
print chksum.encode('hex') # Convert byte string to hexadecimal for printing
print base64.b32encode(chksum)
print base64.b32encode(bytearray("abc"))