You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Python RSA OAEP解密哈希逻辑改写为Golang代码求助

修正RSA OAEP解密及哈希生成的Golang代码

原Python实现逻辑

以下是功能正常的Python代码,核心流程为:

  1. Base64解码加密的Nonce
  2. RSA OAEP解密(哈希算法为SHA256,MGF1也用SHA256,无Label)
  3. 对解密结果计算SHA256哈希
  4. URL安全Base64编码哈希值
  5. 移除编码结果中的/、+、=字符
import hashlib
import base64
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes

nonceHash = hashlib.sha256()
decrypted_nonce = self.privateKey.decrypt(
    base64.b64decode(p["encrypted_nonce"]),
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
nonceHash.update(decrypted_nonce)
nonceHash = base64.urlsafe_b64encode(nonceHash.digest())
nonceHash = nonceHash.decode("utf8")
nonceHash = nonceHash.replace("/", "").replace("+", "").replace("=", "")

原Golang代码的问题

原代码存在两处关键错误:

  • 完全忽略错误处理,导致问题无法排查
  • URL安全Base64后的字符替换逻辑错误(误替换/和+,但实际编码后是-和_)

修正后的Golang代码

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "encoding/base64"
    "strings"
)

// 处理Nonce解密及哈希生成的函数
func processNonce(nonceProof struct{ EncryptedNonce string }, RAC struct{ private_key *rsa.PrivateKey }) (string, error) {
    // 1. Base64解码加密的Nonce
    base64Decoded, err := base64.StdEncoding.DecodeString(nonceProof.EncryptedNonce)
    if err != nil {
        return "", err
    }

    // 2. RSA OAEP解密,参数与Python完全对齐
    decryptedNonce, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, RAC.private_key, base64Decoded, nil)
    if err != nil {
        return "", err
    }

    // 3. 计算解密结果的SHA256哈希
    hash := sha256.New()
    _, err = hash.Write(decryptedNonce)
    if err != nil {
        return "", err
    }
    hashDigest := hash.Sum(nil)

    // 4. URL安全Base64编码
    urlSafeB64 := base64.URLEncoding.EncodeToString(hashDigest)

    // 5. 移除特殊字符,和Python逻辑对齐
    nonceHash := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(urlSafeB64, "-", ""), "_", ""), "=", "")

    return nonceHash, nil
}

关键修正点说明

  1. 添加错误处理:所有可能失败的步骤(解码、解密、哈希写入)都添加了错误返回,便于定位问题
  2. 修正字符替换:Golang的base64.URLEncoding会将+转为-、/转为_,因此需要替换-和_而非原代码中的/和+,确保和Python输出一致
  3. 简化编码操作:使用EncodeToString替代手动分配切片的方式,代码更简洁易读

内容的提问来源于stack exchange,提问作者Nice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:39:24