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

41 thoughts on “How to Calculating the JavaScript Hash for AMP in PHP?”

Leave a Comment