Skip Navigation
HMAC connecPHP Crypto sha256 Implementation.
Answer ID 11883   |   Last Review Date 05/13/2021

How do I setup  CPHP Crypto API's sha256 with a secretkey?


Connect for PHP (CPHP), Custom Process Model (CPM), Custom Scripts


How to create SHA256 Hashing Algorithm with a Secret Key


The Crypto APIs sha256 has no Secret Key implemented by default, in order to garner the same functionality as PHP's HASH_HMAC; This code example demonstrates how to replicate the same functionality.

function hmac is
        key:        Bytes    // Array on bytes
        message:    Bytes    // Array of bytes to be hashed
        hash:       Function // The hash function to use (e.g. SHA-1)
        blockSize:  Integer  // The block size of the hash function (e.g. 64 bytes for SHA-1)
        outputSize: Integer  // The output size of the hash function (e.g. 20 bytes for SHA-1)

    // Keys longer than blockSize are shortened by hashing them
    if (length(key) > blockSize) then
        key ← hash(key) // key is outputSize bytes long

    // Keys shorter than blockSize are padded to blockSize by padding with zeros on the right
    if (length(key) < blockSize) then
        key ← Pad(key, blockSize) // Pad key with zeros to make it blockSize bytes long

    o_key_pad ← key xor [0x5c  blockSize]   // Outer padded key
    i_key_pad ← key xor [0x36  blockSize]   // Inner padded key

    return  hash(o_key_pad ∥ hash(i_key_pad ∥ message))

This functionality can be replicated in PHP using this code here:

// Implemented SHA256 Crypto API function.
function standard_crypt($msg){
     $md = new Crypto\MessageDigest();
     $md->Algorithm->ID = 3; //SHA256
     $md->Text = $msg;
     $hashed_text = $md->HashText;
     return ($hashed_text);
  } catch (Exception $err ){
       echo $err->getMessage();
// Create Signature Hash
function custom_hmac($algo, $data, $key)
    $size = 64;
    $pack = chr(0x00);
    if (strlen($key) > $size) {
        $key = $algo($key);
    } else {
        $key = $key . str_repeat(chr(0x00), $size - strlen($key));
    // Outter and Inner pad
    $opad = str_repeat(chr(0x5C), $size);
    $ipad = str_repeat(chr(0x36), $size);

    $k_ipad = $ipad ^ $key;
    $k_opad = $opad ^ $key;

    return $algo($k_opad.$algo($k_ipad.$data));

$data = "Protected stuff here thats procted";
$secret "Secret";
$bin_hash = custom_hmac('standard_crypt', $data, $secret, false);
echo "HASH: ".bin2hex($bin_hash);


The connectPHP Crypto APIs sha256 implementation does not have a secret key implemented.



File Attachment
Notify Me
The page will refresh upon submission. Any pending input will be lost.