2016-03-10 3 views
-2

Я использую эту функцию php для шифрования некоторых строк.PHP Где сохранить ключ шифрования OpenSSL?

openssl_encrypt(); 

Для генерации ключа шифрования Я использую

$encryption_key = openssl_random_pseudo_bytes(32); 

Я также знаю, что этот ключ шифрования должен быть где-то хранить.
Проблема в том, что я не хочу хранить его в своей базе данных, потому что он может быть доступен для хакеров.

Где я могу хранить свои ключи безопасно?

P.S. Имеет смысл хранить зашифрованные данные и использованные ключи в одной и той же базе данных.

+2

Ваша база данных не должна быть «доступной для хакеров». Вы должны быть в состоянии доверять ему, как и любое другое место хранения. Ничто не является полностью защищенным от хакеров. – rmirabelle

+1

@rmirabelle Нет смысла хранить зашифрованные данные и использовать ключи в одной базе данных –

+0

Я храню сам ключ, закодированный в файл PHP. Это по крайней мере ставит ключ и зашифрованные значения в отдельных местах, что является хорошей стратегией, как вы предлагаете. – rmirabelle

ответ

-1

Вот пример класса шифрования, который я создал на PHP. Ключ шифрования хранится в этом классе, который затем может использоваться для дешифрования зашифрованных значений БД. Надеюсь это поможет.

/** 
* Provides basic encryption and decryption of strings and objects. 
* Reasonable protection is provided, but you are still responsible 
* for sanitizing the source strings or objects prior to use. 
*/ 

class Encrypter { 

    /** 
    * This is the global encryption key for the site. 
    * The longer you make this key, the more secure the encryption 
    */ 
    const MASTER_KEY = 'my_amazing_key_of_death'; 

    private $key; 
    private $cipher; 
    private $mode; 
    private $iv; 
    private $iv_size; 
    private $key_size; 
    private $block_size; 

    public function __construct() { 

     $this->key   = self::MASTER_KEY 
     $this->cipher  = MCRYPT_BLOWFISH; 
     $this->mode   = MCRYPT_MODE_CBC; 
     $this->block_size = mcrypt_get_block_size($this->cipher); 
     $this->iv_size  = mcrypt_get_iv_size($this->cipher, $this->mode); 
     $this->key_size  = mcrypt_get_key_size($this->cipher, $this->mode); 
     $this->iv   = mcrypt_create_iv($this->iv_size, MCRYPT_RAND); 

     /** 
     * if the calculated keysize is shorter than 
     * they key provided, trim the provided key 
     * to match its length 
     */ 
     if (strlen($this->key) > $this->key_size) { 
      $this->key = substr($this->key, 0, $this->key_size); 
     } 
    } 

    /** 
    * Static method alias for string encryption 
    * @param string $string The string to encrypt 
    * @return string The encrypted string 
    */ 
    public static function enc($string) { 
     $e = new self; 
     return $e->encrypt_string($string); 
    } 

    /** 
    * Static method alias for string decryption 
    * @param string $enc_string The previously encrypted string 
    * @return string The decrypted/original string 
    */ 
    public static function dec($enc_string) { 
     $e = new self; 
     return $e->decrypt_string($enc_string); 
    } 

    /** 
    * Encrypt a string 
    * @param string $string - string to encrypt 
    * @return string - encrypted string 
    */ 
    function encrypt_string($string) { 
     $enc = mcrypt_encrypt(
      $this->cipher, 
      $this->key, 
      $string, 
      $this->mode, 
      $this->iv 
     ); 

     $enc = base64_encode($this->iv . $enc); 
     /** 
     * replace potentially illegal chars 
     */ 
     $enc = strtr($enc, '+/=', '-_,'); 

     /** 
     * remove unnecessary and ugly trailing commas 
     */ 
     $enc = strrev($enc); 
     if(substr($enc,0,1) == ',') $enc = substr($enc,1); 
     if(substr($enc,0,1) == ',') $enc = substr($enc,1); 
     $enc = strrev($enc); 

     return $enc; 
    } 

    /** 
    * Decrypt an encrypted string and return the original 
    * @param string $s The string previously encrypted with this class 
    * @return string The original unencrypted string 
    */ 
    function decrypt_string($s) { 

     $s = strtr($s, '-_,', '+/='); 
     $s = base64_decode($s); 
     $this->iv_size = mcrypt_get_iv_size($this->cipher, $this->mode); 
     $this->iv = substr($s, 0, $this->iv_size); 
     $data = substr($s, $this->iv_size); 
     /** 
     * supress warnings because they happen every time 
     * IV parameter must be as long as the block size 
     * yet this still works perfectly 
     */ 
     $decrypted = @mcrypt_decrypt($this->cipher, $this->key, $data, $this->mode, $this->iv); 

     return trim($decrypted); 
    } 

    /** 
    * Serialize an object into an encrypted string 
    * @throws Exception 
    * @param object $object 
    * @return string 
    */ 
    function encrypt_object($object) { 
     if(is_resource($object)) throw new Exception("Cannot encrypt objects of type 'resource'"); 
     $ser = serialize($object); 
     $enc = base64_encode($ser); 
     return $this->encrypt_string($enc); 
    } 

    /** 
    * Unserialize an encrypted string back into an object 
    * @param string $enc 
    * @return object 
    */ 
    function decrypt_object($enc) { 
     $dec = $this->decrypt_string($enc); 
     $unenc = base64_decode($dec); 
     return unserialize($unenc); 
    } 
} 
+2

Unserialize + unauthenticated encryption + using substr() с двоичными данными + blowfish + с использованием пароля в качестве ключа шифрования. Это швейцарский армейский нож с уязвимостями безопасности. –

+0

@ScottArciszewski. Чтобы быть справедливым, Blowfish не является слабостью в плане безопасности. Да, это 64-битный блочный шифр, который больше не рекомендуется автору, и имеет практическое ограничение на шифрование 32 ГБ, но в Blowfish нет известных уязвимостей, которые делают возможным нарушение его зашифрованных текстов. :) –

+0

@AaronToponce Это абсолютно справедливо. –

Смежные вопросы