使用hmac在Elixir和PHP中生成签名

使用hmac在Elixir和PHP中生成签名

本文介绍了使用hmac在Elixir和PHP中生成签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Elixir生成签名,该签名与PHP具有相同的值。



例如,PHP中的代码为

  $ signature = base64_encode(hash_hmac( sha256, abc, def)); 

,输出将为



Mzk3ZjQ2NzM0MWU0ZDc4YzQ3NDg2N2VmMzI2MWNkYjQ2YzBlMTAzNTFlOWE5ODk5NjNlNmNMNiMmRjZTQwZWU1ZA ==

在Ib中应该具有相同的签名。我尝试过类似以下的操作

  iex(9)> :crypto.hmac(:sha256, abc, def)|> Base.encode64│
IOvA8JNERwE081BA9j6pix2OQUISlJ7lxQBCnRXqsIE =

iex(10)> :crypto.hash(:sha256,:crypto.hmac(:sha256, abc, def))|> Base.encode64│
dxGiPN6KqBJrtS2wlC4tnJXwUsWf4u1LPDtDFK + VT5A =

或我切换 abc def

  iex(11)> :crypto.hash(:sha256,:crypto.hmac(:sha256, def, abc))|> Base.encode64│
b + 3P5oHu8e6HIlJe2MzcGhKm7tCcF / NE5wPIbEhrFGU =

iex(12)> :crypto.hmac(:sha256, def, abc)|> Base.encode64│
OX9Gc0Hk14xHSGfvMmHNtGwOEDUempiZY + bLLc5A7l0 =

但是它们都不相同值。有人可以告诉我该怎么做吗?

解决方案

主要问题是 hash_hmac 返回十六进制字符串,而:crypto.hmac 返回二进制。



Elixir中的代码是:

  iex(1)> :crypto.hmac(:sha256, def, abc)|> Base.encode16 |> String.downcase |> Base.encode64 
Mzk3ZjQ2NzM0MWU0ZDc4YzQ3NDg2N2VmMzI2MWNkYjQ2YzBlMTAzNTFlOWE5ODk5NjNlNmNMNiMmRjZTQwZWU1ZA ==
$$$$ $ <$$$ > String.downcase
,因为 Base.encode16 返回一个十六进制字符串,其大写字母为 AF ,而PHP为 hash_hmac 返回小写字母 af


I try to generate a signature using Elixir, which has a same value as PHP does.

For example the code in PHP is

$signature = base64_encode(hash_hmac("sha256", "abc", "def"));

and the output will be

Mzk3ZjQ2NzM0MWU0ZDc4YzQ3NDg2N2VmMzI2MWNkYjQ2YzBlMTAzNTFlOWE5ODk5NjNlNmNiMmRjZTQwZWU1ZA==

How should I generate the signature that has the same value in Elixir. I tried something like below

iex(9)> :crypto.hmac(:sha256, "abc", "def") |> Base.encode64                          │
"IOvA8JNERwE081BA9j6pix2OQUISlJ7lxQBCnRXqsIE="

iex(10)> :crypto.hash(:sha256, :crypto.hmac(:sha256, "abc", "def")) |> Base.encode64  │
"dxGiPN6KqBJrtS2wlC4tnJXwUsWf4u1LPDtDFK+VT5A="

or I switch the position of abc and def

iex(11)> :crypto.hash(:sha256, :crypto.hmac(:sha256, "def", "abc")) |> Base.encode64  │
"b+3P5oHu8e6HIlJe2MzcGhKm7tCcF/NE5wPIbEhrFGU="

iex(12)> :crypto.hmac(:sha256, "def", "abc") |> Base.encode64                         │
"OX9Gc0Hk14xHSGfvMmHNtGwOEDUempiZY+bLLc5A7l0="

But none of them has the same value. Can someone tell me how to do it the right way?

解决方案

The main problem is that hash_hmac returns a hex string, while :crypto.hmac returns a binary.

The equivalent code in Elixir is:

iex(1)> :crypto.hmac(:sha256, "def", "abc") |> Base.encode16 |> String.downcase |> Base.encode64
"Mzk3ZjQ2NzM0MWU0ZDc4YzQ3NDg2N2VmMzI2MWNkYjQ2YzBlMTAzNTFlOWE5ODk5NjNlNmNiMmRjZTQwZWU1ZA=="

We need to use String.downcase because Base.encode16 returns a hex string with capital A-F while PHP's hash_hmac returns lower case a-f.

这篇关于使用hmac在Elixir和PHP中生成签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:02