【问题标题】:Handling JSON POST request using PHP and SHA1使用 PHP 和 SHA1 处理 JSON POST 请求
【发布时间】:2012-03-14 09:31:40
【问题描述】:

所以我使用的是 REST API,其中 API 以 JSON 格式向我的服务器发出 POST 请求。以下是它发送的信息:

info: {
id: "9890dsds8",
number: 5,
amount: 33
},
sig: "8jhjbhb78979899h"

sig 是信息的 SHA1 签名,这应该用于验证帖子。例如,我们可以使用(如他们的示例中给出的)验​​证 Ruby 中的信息:

require 'json'
require 'cgi'
require 'digest/sha1'

key = "some_key"
params = CGI::parse(post_body)
digest = Digest::SHA1.hexdigest(params["info"]+key)

if digest == params["sig"]
# Valid signature
info = JSON.parse(params["info"])
# Respond with status code 200 and some unique_id
else
# Invalid signature. You should response with a non-200 response code.
end

unique_id 必须是长度不超过 50 个字符的 UTF8 字符串,并且应该是响应正文的唯一内容。

虽然我完全能够理解正在发生的事情,但我并不能完全弄清楚所有事情。大多数情况下,可能是因为它在 Ruby 中。

有人可以帮助我如何在 PHP 中执行此操作吗?我无法在 PHP 中处理这个 JSON POST 请求。非常感谢 sn-p 的 PHP 转换版本。我也不确定,如何处理 PHP 中的 SHA1 方面,需要任何特殊知识吗?

非常感谢!!

【问题讨论】:

    标签: php ruby json post sha1


    【解决方案1】:

    我假设 API 将填充 POST 数组中的“响应”变量。

    然后:

    //Get the JSON string
    $json_string = $_POST['response'];
    
    //Decode JSON string to array
    $decoded = json_decode($json_string);
    
    //Calculate SHA1 (I am not sure how ruby is concatenating a string with an array, so I will just convert the array to string using implode).
    $key = 'somekey';
    $hash = sha1(implode("",$decoded['info']) . $key);
    
    if($hash == $decoded['sig']){
     //OK!
    }else{
     //Not OK!
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多