首页 > 解决方案 > GoLang 中的 HMAC 验证

问题描述

我在 PHP 中有一个 HMAC 验证代码,就像

$calculatedHmac = base64_encode(hash_hmac('sha256', json_encode($input), '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', true));
if($calculatedHmac === $this->app['request']->header('X-Shopify-Hmac-Sha256')) 
{
    echo "Correct HMAC";
}

现在,我正在尝试在 GoLang 中进行相同的验证。对应代码:

hash := hmac.New(sha256.New, []byte('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'))
inputData, _ := json.Marshal(input)
fmt.Println(string(inputData))
hash.Write(inputData)
base64EncodedStr := base64.StdEncoding.EncodeToString(hash.Sum(nil))
hexEncodedStr := hex.EncodeToString(hash.Sum(nil))
if requestHmac == base64EncodedStr {
    logger.GetEntryWithContext(ctx).Infow("JsonMarshal.Base64 worked", nil)
} else if hexEncodedStr == requestHmac {
    logger.GetEntryWithContext(ctx).Infow("JsonMarshal.Hex Encoding worked", nil)
}

有什么我做错了吗???

输入数据: 实际 HMAC:EUF2feuOuaQzh0bhSE8eCaI23BM0Qh+yBtmxNWyt8JQ=

JSON 输入:

{"address1":"Ghar ka Address","address2":null,"auto_configure_tax_inclusivity":null,"checkout_api_supported":false,"city":"Bangalore ","cookie_consent_level":"implicit","country":"IN","country_code":"IN","country_name":"India","county_taxes":true,"created_at":"2021-03-06T11:54:22+05:30","currency":"INR","customer_email":"amit.vickey@razorpay.com","domain":"rzp-sample-store.myshopify.com","eligible_for_card_reader_giveaway":false,"eligible_for_payments":false,"email":"amit.vickey@razorpay.com","enabled_presentment_currencies":["INR"],"finances":true,"force_ssl":true,"google_apps_domain":null,"google_apps_login_enabled":null,"has_discounts":false,"has_gift_cards":false,"has_storefront":true,"iana_timezone":"Asia/Calcutta","id":55091921055,"latitude":12.9142148,"longitude":77.61210129999999,"money_format":"Rs. {{amount}}","money_in_emails_format":"Rs. {{amount}}","money_with_currency_format":"Rs. {{amount}}","money_with_currency_in_emails_format":"Rs. {{amount}}","multi_location_enabled":true,"myshopify_domain":"rzp-sample-store.myshopify.com","name":"RZP Sample Store","password_enabled":true,"phone":"","plan_display_name":"Developer Preview","plan_name":"partner_test","pre_launch_enabled":false,"primary_locale":"en","primary_location_id":61106618527,"province":"Karnataka","province_code":"KA","requires_extra_payments_agreement":false,"setup_required":false,"shop_owner":"Amit Vickey","source":null,"tax_shipping":null,"taxes_included":false,"timezone":"(GMT+05:30) Asia/Calcutta","updated_at":"2021-03-06T12:06:18+05:30","visitor_tracking_consent_preference":"allow_all","weight_unit":"kg","zip":"560076"}

标签: gosha256hmac

解决方案


推荐阅读