Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

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 ) );
question from:https://stackoverflow.com/questions/65850147/how-to-calculating-the-javascript-hash-for-amp-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...