收藏
回答

go代码去解密微信回调消息时,有的消息成功有的失败,比例是7比1,是什么问题?

func DecryptWxMessage(encryptedBase64, encodingAESKey string) (string, string, error) {
    // 1. AESKey = Base64Decode(EncodingAESKey + "=")
    encryptedBase64 = strings.TrimSpace(encryptedBase64)
    encryptedBase64 = strings.ReplaceAll(encryptedBase64, "\n", "")
    encryptedBase64 = strings.ReplaceAll(encryptedBase64, "\r", "")
    aesKey, err := base64.StdEncoding.DecodeString(encodingAESKey + "=")
    if err != nil {
       return "", "", fmt.Errorf("decode AES key failed: %w", err)
    }
    if len(aesKey) != 32 {
       return "", "", fmt.Errorf("AES key length invalid, got %d, want 32", len(aesKey))
    }

    // 2. base64 decode Encrypt
    cipherData, err := base64.StdEncoding.DecodeString(encryptedBase64)
    if err != nil {
       return "", "", fmt.Errorf("decode base64 cipher failed: %w", err)
    }

    // 3. AES-256-CBC 解密,IV = aesKey[:16]
    block, err := aes.NewCipher(aesKey)
    if err != nil {
       return "", "", fmt.Errorf("new AES cipher failed: %w", err)
    }
    if len(cipherData)%block.BlockSize() != 0 {
       return "", "", fmt.Errorf("ciphertext length (%d) is not multiple of block size (%d)", len(cipherData), block.BlockSize())
    }
    iv := aesKey[:block.BlockSize()]
    mode := cipher.NewCBCDecrypter(block, iv)

    plainData := make([]byte, len(cipherData))
    mode.CryptBlocks(plainData, cipherData)

    // 4. PKCS7 去填充(宽松方式)
    plainData, err = PKCS7UnpaddingOfficial(plainData)
    if err != nil {
       return "", "", fmt.Errorf("PKCS7 unpadding failed: %w", err)
    }

    // 5. 打印前 20 字节便于调试
    //fmt.Printf("plainData[:20] = % x\n", plainData[:20])

    // 6. 检查长度
    if len(plainData) < 20 {
       return "", "", fmt.Errorf("plaintext too short: %d bytes", len(plainData))
    }

    // 7. 解析 msg_len (4字节网络字节序)
    msgLen := binary.BigEndian.Uint32(plainData[16:20])
    if int(20+msgLen) > len(plainData) {
       head20 := plainData[:20]
       return "", "", fmt.Errorf("invalid msg length: %d, plaintext len: %d, head20=%x", msgLen, len(plainData), head20)
    }

    // 8. 提取 json msg 和 appid
    jsonMsg := plainData[20 : 20+msgLen]
    appId := string(plainData[20+msgLen:])

    return string(jsonMsg), appId, nil
}
回答关注问题邀请回答
收藏

2 个回答

  • 乌龙茶
    乌龙茶
    2025-11-14

    微信小店的

    2025-11-14
    有用
    回复
  • 智能回答 智能回答 本次回答由AI生成
    2025-11-14
    有用
登录 后发表内容