javascriptphphashamp-html

How to Calculating the JavaScript Hash for AMP in PHP?


At Calculating the script hash we can see how to calculate the JavaScript hash in case of AMP:

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, '_')
  );
}

How can I do the same in PHP? The following seems not work:

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

Solution

  • The code is a reference from the WordPress AMP plugin

    /**
     * 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;
    }