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

Python生成的HMACSHA256与JavaScript结果不符,求问题排查

Python与JavaScript HMACSHA256哈希不一致问题排查

问题描述

分别使用Python和JavaScript通过HMACSHA256生成加密字符串,目标哈希值为"d345464ec3f314c822e653065214ab5ed491c1ce0c0c56b685efb5f197b5f693",JavaScript已成功生成该值,但Python生成结果不符。

原Python代码

import hmac
import hashlib
import json

secret = 'abcdefghijklm'

payload =  {"created_time":"2023-03-01T13:46:58+0530","event_id":"880617000000018013","event_type":"subscription_cancelled","data":{"subscription":{"cancelled_at":"2023-03-01","invoice_notes":"Thanks for your business.","updated_time":"2023-03-01T13:46:58+0530","notes":[],"zcrm_potential_id":"","reference_id":"","trial_extended_count":0,"addons":[],"taxes":[],"discount":0,"source":"user","coupon_duration":"","subscription_id":"880617000000015059","last_modified_by_id":"880617000000014001","end_of_term":False,"product_id":"880617000000014233","plan":{"setup_fee":0,"quantity":1,"discount_amount":0,"tax_name":"","setup_fee_tax_percentage":"","plan_code":"abcd","description":"","discount":0,"item_custom_fields":[],"tax_id":"","tags":[],"setup_fee_tax_id":"","total":1,"unit":"plan","setup_fee_tax_name":"","tax_type":"tax","price":1,"name":"Test","tax_percentage":0,"setup_fee_tax_type":"","discount_formatted":"Rs.0.00","pricing_scheme":"unit","plan_id":"880617000000015046"},"pricebook_id":"","created_time":"2023-02-24T17:53:29+0530","shipping_interval_unit":"months","exchange_rate":1,"is_inclusive_tax":False,"orders_remaining":0,"custom_fields":[],"last_shipment_at":"","auto_apply_credits":[],"product_name":"Test","can_invoice_prorated_amount":True,"apply_changes_on":"","activated_at":"2023-02-24","previous_attribute":{"total":0,"quantity":1,"plan_code":"abcd","plan_id":"880617000000015046","plan_name":"Test","status":"live"},"bcy_amount":1,"is_metered_billing":False,"name":"Test-Test","zcrm_potential_name":"","interval":1,"created_by_id":"880617000000014001","discount_percent":0,"crm_owner_id":"","status":"cancelled","items_associated":[],"discount_total":0,"billing_mode":"prepaid","is_discount_before_tax":True,"channel_reference_id":"","created_at":"2023-02-24","shipping_interval":1,"payment_terms":0,"last_billing_at":"2023-02-24","currency_code":"INR","can_prorate":True,"expires_at":"","interval_unit":"months","can_add_bank_account":False,"custom_field_hash":{},"is_advance_invoice_present":False,"last_shipment_day":"","tax_rounding":"entity_level","start_date":"2023-02-24","payment_gateways":[{"payment_gateway":"test_gateway"}],"bcy_discount_total":0,"amount":1,"remaining_billing_cycles":-1,"discount_applied_on_amount":0,"subscription_number":"SUB-00001","currency_symbol":"Rs.","current_term_starts_at":"2023-02-24","reactivate_date":"","current_term_ends_at":"2023-03-24","total_orders":0,"discount_type":"item_level","salesperson_name":"","pending_addons":[],"salesperson_id":"","child_invoice_id":"880617000000015076","cancel_reason":"","contactpersons":[{"zcrm_contact_id":"","phone":"","mobile":"","last_name":"","first_name":"Test","email":"test123@mailinator.com","contactperson_id":"880617000000015019"}],"auto_collect":False,"channel_source":"app","sub_total":1,"created_date":"2023-02-24","allow_partial_payments":False,"is_scheduled_update":False,"orders_created":0,"customer_id":"880617000000015017","payment_terms_label":"Due on Receipt","customer":{"website":"","zcrm_account_id":"","custom_fields":[],"channel_reference_id":"","last_name":"","billing_address":{"zip":"","country":"India","city":"","phone":"","street":"","attention":"","street2":"","state":"","fax":""},"ip_address":"103.16.70.190","display_name":"Mr. Test","payment_terms":0,"channel_customer_id":"","tags":[],"zcrm_contact_id":"","company_name":"","custom_field_hash":{},"salutation":"Mr.","shipping_address":{"zip":"","country":"India","city":"","phone":"","street":"","attention":"","street2":"","state":"","fax":""},"customer_id":"880617000000015017","first_name":"Test","email":"test123@mailinator.com","payment_terms_label":"Due on Receipt"}}},"event_time_formatted":"01/03/2023","event_source":"user","event_time":"2023-03-01"}

payload_str = json.dumps(payload)

signature = hmac.new(secret.encode('utf-8'), payload_str.encode('utf-8'), hashlib.sha256).hexdigest()
print(signature) # b4570cf634c04915e4b6a1c0c73cc3095dc78312e11d65846cb763c1c6938c28

原JavaScript代码

var message = {"created_time":"2023-03-01T13:46:58+0530","event_id":"880617000000018013","event_type":"subscription_cancelled","data":{"subscription":{"cancelled_at":"2023-03-01","invoice_notes":"Thanks for your business.","updated_time":"2023-03-01T13:46:58+0530","notes":[],"zcrm_potential_id":"","reference_id":"","trial_extended_count":0,"addons":[],"taxes":[],"discount":0,"source":"user","coupon_duration":"","subscription_id":"880617000000015059","last_modified_by_id":"880617000000014001","end_of_term":false,"product_id":"880617000000014233","plan":{"setup_fee":0,"quantity":1,"discount_amount":0,"tax_name":"","setup_fee_tax_percentage":"","plan_code":"abcd","description":"","discount":0,"item_custom_fields":[],"tax_id":"","tags":[],"setup_fee_tax_id":"","total":1,"unit":"plan","setup_fee_tax_name":"","tax_type":"tax","price":1,"name":"Test","tax_percentage":0,"setup_fee_tax_type":"","discount_formatted":"Rs.0.00","pricing_scheme":"unit","plan_id":"880617000000015046"},"pricebook_id":"","created_time":"2023-02-24T17:53:29+0530","shipping_interval_unit":"months","exchange_rate":1,"is_inclusive_tax":false,"orders_remaining":0,"custom_fields":[],"last_shipment_at":"","auto_apply_credits":[],"product_name":"Test","can_invoice_prorated_amount":true,"apply_changes_on":"","activated_at":"2023-02-24","previous_attribute":{"total":0,"quantity":1,"plan_code":"abcd","plan_id":"880617000000015046","plan_name":"Test","status":"live"},"bcy_amount":1,"is_metered_billing":false,"name":"Test-Test","zcrm_potential_name":"","interval":1,"created_by_id":"880617000000014001","discount_percent":0,"crm_owner_id":"","status":"cancelled","items_associated":[],"discount_total":0,"billing_mode":"prepaid","is_discount_before_tax":true,"channel_reference_id":"","created_at":"2023-02-24","shipping_interval":1,"payment_terms":0,"last_billing_at":"2023-02-24","currency_code":"INR","can_prorate":true,"expires_at":"","interval_unit":"months","can_add_bank_account":false,"custom_field_hash":{},"is_advance_invoice_present":false,"last_shipment_day":"","tax_rounding":"entity_level","start_date":"2023-02-24","payment_gateways":[{"payment_gateway":"test_gateway"}],"bcy_discount_total":0,"amount":1,"remaining_billing_cycles":-1,"discount_applied_on_amount":0,"subscription_number":"SUB-00001","currency_symbol":"Rs.","current_term_starts_at":"2023-02-24","reactivate_date":"","current_term_ends_at":"2023-03-24","total_orders":0,"discount_type":"item_level","salesperson_name":"","pending_addons":[],"salesperson_id":"","child_invoice_id":"880617000000015076","cancel_reason":"","contactpersons":[{"zcrm_contact_id":"","phone":"","mobile":"","last_name":"","first_name":"Test","email":"test123@mailinator.com","contactperson_id":"880617000000015019"}],"auto_collect":false,"channel_source":"app","sub_total":1,"created_date":"2023-02-24","allow_partial_payments":false,"is_scheduled_update":false,"orders_created":0,"customer_id":"880617000000015017","payment_terms_label":"Due on Receipt","customer":{"website":"","zcrm_account_id":"","custom_fields":[],"channel_reference_id":"","last_name":"","billing_address":{"zip":"","country":"India","city":"","phone":"","street":"","attention":"","street2":"","state":"","fax":""},"ip_address":"103.16.70.190","display_name":"Mr. Test","payment_terms":0,"channel_customer_id":"","tags":[],"zcrm_contact_id":"","company_name":"","custom_field_hash":{},"salutation":"Mr.","shipping_address":{"zip":"","country":"India","city":"","phone":"","street":"","attention":"","street2":"","state":"","fax":""},"customer_id":"880617000000015017","first_name":"Test","email":"test123@mailinator.com","payment_terms_label":"Due on Receipt"}}},"event_time_formatted":"01/03/2023","event_source":"user","event_time":"2023-03-01"}
var secret = "abcdefghijklm"
var m = JSON.stringify(message);
var hash = CryptoJS.HmacSHA256(m, secret);
console.log(hash.toString())

问题原因

Python和JavaScript的JSON序列化行为存在核心差异:
Python的json.dumps()默认会在键值对的冒号后、逗号后添加空格(如{"key": "value", "foo": true}),而JavaScript的JSON.stringify()默认生成紧凑的无空格字符串(如{"key":"value","foo":true})。这种字符串内容的细微差异直接导致HMACSHA256计算结果完全不同。

修正后的Python代码

import hmac
import hashlib
import json

secret = 'abcdefghijklm'

payload =  {"created_time":"2023-03-01T13:46:58+0530","event_id":"880617000000018013","event_type":"subscription_cancelled","data":{"subscription":{"cancelled_at":"2023-03-01","invoice_notes":"Thanks for your business.","updated_time":"2023-03-01T13:46:58+0530","notes":[],"zcrm_potential_id":"","reference_id":"","trial_extended_count":0,"addons":[],"taxes":[],"discount":0,"source":"user","coupon_duration":"","subscription_id":"880617000000015059","last_modified_by_id":"880617000000014001","end_of_term":False,"product_id":"880617000000014233","plan":{"setup_fee":0,"quantity":1,"discount_amount":0,"tax_name":"","setup_fee_tax_percentage":"","plan_code":"abcd","description":"","discount":0,"item_custom_fields":[],"tax_id":"","tags":[],"setup_fee_tax_id":"","total":1,"unit":"plan","setup_fee_tax_name":"","tax_type":"tax","price":1,"name":"Test","tax_percentage":0,"setup_fee_tax_type":"","discount_formatted":"Rs.0.00","pricing_scheme":"unit","plan_id":"880617000000015046"},"pricebook_id":"","created_time":"2023-02-24T17:53:29+0530","shipping_interval_unit":"months","exchange_rate":1,"is_inclusive_tax":False,"orders_remaining":0,"custom_fields":[],"last_shipment_at":"","auto_apply_credits":[],"product_name":"Test","can_invoice_prorated_amount":True,"apply_changes_on":"","activated_at":"2023-02-24","previous_attribute":{"total":0,"quantity":1,"plan_code":"abcd","plan_id":"880617000000015046","plan_name":"Test","status":"live"},"bcy_amount":1,"is_metered_billing":False,"name":"Test-Test","zcrm_potential_name":"","interval":1,"created_by_id":"880617000000014001","discount_percent":0,"crm_owner_id":"","status":"cancelled","items_associated":[],"discount_total":0,"billing_mode":"prepaid","is_discount_before_tax":True,"channel_reference_id":"","created_at":"2023-02-24","shipping_interval":1,"payment_terms":0,"last_billing_at":"2023-02-24","currency_code":"INR","can_prorate":True,"expires_at":"","interval_unit":"months","can_add_bank_account":False,"custom_field_hash":{},"is_advance_invoice_present":False,"last_shipment_day":"","tax_rounding":"entity_level","start_date":"2023-02-24","payment_gateways":[{"payment_gateway":"test_gateway"}],"bcy_discount_total":0,"amount":1,"remaining_billing_cycles":-1,"discount_applied_on_amount":0,"subscription_number":"SUB-00001","currency_symbol":"Rs.","current_term_starts_at":"2023-02-24","reactivate_date":"","current_term_ends_at":"2023-03-24","total_orders":0,"discount_type":"item_level","salesperson_name":"","pending_addons":[],"salesperson_id":"","child_invoice_id":"880617000000015076","cancel_reason":"","contactpersons":[{"zcrm_contact_id":"","phone":"","mobile":"","last_name":"","first_name":"Test","email":"test123@mailinator.com","contactperson_id":"880617000000015019"}],"auto_collect":False,"channel_source":"app","sub_total":1,"created_date":"2023-02-24","allow_partial_payments":
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:17:09