0

facebook 开发人员文档中的示例是 PHP 中的。

<?php
define('FACEBOOK_APP_ID', 'your_app_id');
define('FACEBOOK_SECRET', 'your_app_secret');

function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);

if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
}

// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
}

return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}

if ($_REQUEST) {
echo '<p>signed_request contents:</p>';
$response = parse_signed_request($_REQUEST['signed_request'], 
                                   FACEBOOK_SECRET);
echo '<pre>';
print_r($response);
echo '</pre>';
} else {
echo '$_REQUEST is empty';
}
?>

我开始用java做。但我坚持检查signature.:

    String data[] = signed_request.split("\\.");

    Base64 decoder = new Base64(true);
    byte[] decodedBytes = decoder.decode( data[1] );
    String result = new String(decodedBytes);

    byte[] dc = decoder.decode(data[0]);
    String signature = new String (dc);
    System.out.println("signature: " + signature);

    JdomParser parser = new JdomParser();
    JsonRootNode rootNode;
    try {
        rootNode = parser.parse(result);

        String algorithm = rootNode.getStringValue("algorithm");
        if ( ! algorithm.equals("HMAC-SHA256")){
            return INPUT;
        }

        String FBSECRET = "my_app_secret";

        //what would be next?

    } catch (InvalidSyntaxException e) {
        e.printStackTrace();

    }

什么函数相当于hash_hmacjava中的?result现在是JSON格式。但是signature打印时的值会显示奇怪的字符,如���y�'�Κ�D]���D�|~�Σ��7�`。

谢谢。

4

0 回答 0