【问题标题】:How to Calculating the JavaScript Hash for AMP in PHP?如何在 PHP 中计算 AMP 的 JavaScript 哈希?
【发布时间】:2021-04-27 05:09:18
【问题描述】:

Calculating the script hash,我们可以看到如何计算 AMP 情况下的 JavaScript 哈希:

const crypto = require('crypto');
const hash = crypto.createHash('sha384');

function generateCSPHash(script) {
  const data = hash.update(script, 'utf-8');
  return (
    'sha384-' +
    data
      .digest('base64')
      .replace(/=/g, '')
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
  );
}

如何在 PHP 中做同样的事情?以下似乎不起作用:

<?php
$hash = base64_encode( hash( 'SHA384', 'Give me my hash!', true ) );

【问题讨论】:

标签: javascript php hash amp-html


【解决方案1】:

代码是来自WordPress AMP插件的引用

/**
 * Function to generate AMP scrip hash.
 *
 * @param string $script the script as a string to generate the hash.
 *
 * @return string hash generated from the script.
 */
function amp_generate_script_hash( $script ) {
    $sha384 = hash( 'sha384', $script, true );
    if ( false === $sha384 ) {
        return null;
    }
    $hash = str_replace(
        [ '+', '/', '=' ],
        [ '-', '_', '.' ],
        base64_encode( $sha384 )
    );
    return 'sha384-' . $hash;
}

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2016-06-23
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 2016-11-25
    • 2019-05-31
    • 2020-04-28
    • 1970-01-01
    相关资源
    最近更新 更多