20 protected function key($key){
21 return sha1($key . $this->
key,
true) . $key . $this->key;
29 $iv = openssl_random_pseudo_bytes($length = openssl_cipher_iv_length($this->_method),$strong);
30 if(!$strong) $this->
component(
'log')->warning(
"Generated initialization vector for method '{$this->_method}' not cryptographically strong",__FILE__,__LINE__);
39 public function str($str,$key = null){
41 return $this->_method .
':' . $iv . openssl_encrypt($str,$this->_method,$this->
key($key),OPENSSL_RAW_DATA,$iv);
49 public function decrypt($data,$key = null){
50 $length = openssl_cipher_iv_length($method = substr($data,0,$i = strpos($data,
':')));
51 return openssl_decrypt(substr($data,$i + 1 + $length),$method,$this->
key($key),OPENSSL_RAW_DATA,substr($data,$i + 1,$length));
61 public function file($source,$target,$key = null){
62 $key = $this->
key($key);
63 $source = fopen($source,
'r');
64 $target = fopen($target,
'w');
66 $result = fwrite($target,pack(
'n',strlen($config)) . $config . ($iv = $this->
initVector($length)));
67 while(!feof($source)){
68 $result += fwrite($target,$data = openssl_encrypt(fread($source,$this->_blockSize),$this->_method,$key,OPENSSL_RAW_DATA,$iv));
69 $iv = substr($data,0,$length);
83 $key = $this->
key($key);
84 $source = fopen($source,
'r');
85 $target = fopen($target,
'w');
86 list($method,$size) = explode(
':',fread($source,unpack(
'n',fread($source,2))[1]));
87 $iv = fread($source,$length = openssl_cipher_iv_length($method));
89 while(!feof($source)){
90 $result += fwrite($target,openssl_decrypt($data = fread($source,$size),$method,$key,OPENSSL_RAW_DATA,$iv));
91 $iv = substr($data,0,$length);
99 if(!$this->_key && !($this->_key = $this->
config(
'key'))){
100 if(!$this->_keyFile)
throw new Exception(
'No master key (file)');
101 if(is_file($this->_keyFile)) $this->_key = file_get_contents($this->_keyFile);
103 \Rsi\File::write($this->_keyFile,$this->_key = \
Rsi\Str::random(256),0444);
104 $this->
component(
'log')->warning(
'Generated an encryption master key',__FILE__,__LINE__,[
'key' => $this->_key]);
config($key, $default=null)
Retrieve a config value.
$_key
Master key (used for padding).
$_blockSize
File encryption block size.
$_method
Encryption method (see openssl_get_cipher_methods()).
key($key)
Generate an encryption key.
str($str, $key=null)
Encrypt a string.
Encryption (and decryption) component.
file($source, $target, $key=null)
Encrypt a file.
$_keyFile
File where master key is stored. If the file does not exist, a key is generated and saved...
decrypt($data, $key=null)
Decrypt an encrypted string.
decryptFile($source, $target, $key=null)
Decrypt an encrypted file.
initVector(&$length=null)
Generate an initialization vector.
component($name)
Get a component (local or default).