donglu2008 2019-06-08 17:29
浏览 187
已采纳

无法让python遵循base32编码

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
", 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.

  • 写回答

2条回答 默认 最新

  • dqpwdai095465 2019-06-08 19:49
    关注

    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"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程