RumbleFrog

Safer Crypto

Sep 27th, 2016
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.14 KB | None | 0 0
  1. <?php
  2. class UnsafeCrypto
  3. {
  4.     const METHOD = 'aes-256-ctr';
  5.  
  6.     /**
  7.      * Encrypts (but does not authenticate) a message
  8.      *
  9.      * @param string $message - plaintext message
  10.      * @param string $key - encryption key (raw binary expected)
  11.      * @param boolean $encode - set to TRUE to return a base64-encoded
  12.      * @return string (raw binary)
  13.      */
  14.     public static function encrypt($message, $key, $encode = false)
  15.     {
  16.         $nonceSize = openssl_cipher_iv_length(self::METHOD);
  17.         $nonce = openssl_random_pseudo_bytes($nonceSize);
  18.  
  19.         $ciphertext = openssl_encrypt(
  20.             $message,
  21.             self::METHOD,
  22.             $key,
  23.             OPENSSL_RAW_DATA,
  24.             $nonce
  25.         );
  26.  
  27.         // Now let's pack the IV and the ciphertext together
  28.         // Naively, we can just concatenate
  29.         if ($encode) {
  30.             return base64_encode($nonce.$ciphertext);
  31.         }
  32.         return $nonce.$ciphertext;
  33.     }
  34.  
  35.     /**
  36.      * Decrypts (but does not verify) a message
  37.      *
  38.      * @param string $message - ciphertext message
  39.      * @param string $key - encryption key (raw binary expected)
  40.      * @param boolean $encoded - are we expecting an encoded string?
  41.      * @return string
  42.      */
  43.     public static function decrypt($message, $key, $encoded = false)
  44.     {
  45.         if ($encoded) {
  46.             $message = base64_decode($message, true);
  47.             if ($message === false) {
  48.                 throw new Exception('Encryption failure');
  49.             }
  50.         }
  51.  
  52.         $nonceSize = openssl_cipher_iv_length(self::METHOD);
  53.         $nonce = mb_substr($message, 0, $nonceSize, '8bit');
  54.         $ciphertext = mb_substr($message, $nonceSize, null, '8bit');
  55.  
  56.         $plaintext = openssl_decrypt(
  57.             $ciphertext,
  58.             self::METHOD,
  59.             $key,
  60.             OPENSSL_RAW_DATA,
  61.             $nonce
  62.         );
  63.  
  64.         return $plaintext;
  65.     }
  66. }
  67. class SaferCrypto extends UnsafeCrypto
  68. {
  69.     const HASH_ALGO = 'sha256';
  70.  
  71.     /**
  72.      * Encrypts then MACs a message
  73.      *
  74.      * @param string $message - plaintext message
  75.      * @param string $key - encryption key (raw binary expected)
  76.      * @param boolean $encode - set to TRUE to return a base64-encoded string
  77.      * @return string (raw binary)
  78.      */
  79.     public static function encrypt($message, $key, $encode = false)
  80.     {
  81.         list($encKey, $authKey) = self::splitKeys($key);
  82.  
  83.         // Pass to UnsafeCrypto::encrypt
  84.         $ciphertext = parent::encrypt($message, $encKey);
  85.  
  86.         // Calculate a MAC of the IV and ciphertext
  87.         $mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);
  88.  
  89.         if ($encode) {
  90.             return base64_encode($mac.$ciphertext);
  91.         }
  92.         // Prepend MAC to the ciphertext and return to caller
  93.         return $mac.$ciphertext;
  94.     }
  95.  
  96.     /**
  97.      * Decrypts a message (after verifying integrity)
  98.      *
  99.      * @param string $message - ciphertext message
  100.      * @param string $key - encryption key (raw binary expected)
  101.      * @param boolean $encoded - are we expecting an encoded string?
  102.      * @return string (raw binary)
  103.      */
  104.     public static function decrypt($message, $key, $encoded = false)
  105.     {
  106.         list($encKey, $authKey) = self::splitKeys($key);
  107.         if ($encoded) {
  108.             $message = base64_decode($message, true);
  109.             if ($message === false) {
  110.                 throw new Exception('Encryption failure');
  111.             }
  112.         }
  113.  
  114.         // Hash Size -- in case HASH_ALGO is changed
  115.         $hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
  116.         $mac = mb_substr($message, 0, $hs, '8bit');
  117.  
  118.         $ciphertext = mb_substr($message, $hs, null, '8bit');
  119.  
  120.         $calculated = hash_hmac(
  121.             self::HASH_ALGO,
  122.             $ciphertext,
  123.             $authKey,
  124.             true
  125.         );
  126.  
  127.         if (!self::hashEquals($mac, $calculated)) {
  128.             throw new Exception('Encryption failure');
  129.         }
  130.  
  131.         // Pass to UnsafeCrypto::decrypt
  132.         $plaintext = parent::decrypt($ciphertext, $encKey);
  133.  
  134.         return $plaintext;
  135.     }
  136.  
  137.     /**
  138.      * Splits a key into two separate keys; one for encryption
  139.      * and the other for authenticaiton
  140.      *
  141.      * @param string $masterKey (raw binary)
  142.      * @return array (two raw binary strings)
  143.      */
  144.     protected static function splitKeys($masterKey)
  145.     {
  146.         // You really want to implement HKDF here instead!
  147.         return [
  148.             hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true),
  149.             hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true)
  150.         ];
  151.     }
  152.  
  153.     /**
  154.      * Compare two strings without leaking timing information
  155.      *
  156.      * @param string $a
  157.      * @param string $b
  158.      * @ref https://paragonie.com/b/WS1DLx6BnpsdaVQW
  159.      * @return boolean
  160.      */
  161.     protected static function hashEquals($a, $b)
  162.     {
  163.         if (function_exists('hash_equals')) {
  164.             return hash_equals($a, $b);
  165.         }
  166.         $nonce = openssl_random_pseudo_bytes(32);
  167.         return hash_hmac(self::HASH_ALGO, $a, $nonce) === hash_hmac(self::HASH_ALGO, $b, $nonce);
  168.     }
  169. }
Advertisement
Add Comment
Please, Sign In to add comment