raubvogel
raubvogel

Reputation: 146

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 ) );

Upvotes: 2

Views: 550

Answers (2)

SoyVillareal
SoyVillareal

Reputation: 1

You can try this

function amp_generate_script_hash( $script ) {
    $script = preg_replace('/\s+/g', '', $script); // Remove blank spaces

    $sha384 = hash( 'sha384', $script, true );
    if ( false === $sha384 ) {
        return null;
    }
    $hash = str_replace(
        [ '+', '/', '=' ],
        [ '-', '_', '.' ],
        base64_encode( $sha384 )
    );
    return 'sha384-' . $hash;
}

Upvotes: 0

Milind More
Milind More

Reputation: 317

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

Upvotes: 1

Related Questions