function encrypt_decrypt($action, $string) { /* ================================================= * ENCRYPTION-DECRYPTION * ================================================= * ENCRYPTION: encrypt_decrypt('encrypt', $string); * DECRYPTION: encrypt_decrypt('decrypt', $string) ; */ $output = false; $encrypt_method = "AES-256-CBC"; $secret_key = 'WS-SERVICE-KEY'; $secret_iv = 'WS-SERVICE-VALUE'; // hash $key = hash('sha256', $secret_key); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ($action == 'encrypt') { $output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv)); } else { if ($action == 'decrypt') { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } } return $output; }
/** * * @param string $data * @param string $iv * @param string $key * @return string|false */ public function encrypt($data, $iv, $key) { // Max. 2^32 blocks with a same key (not realistic in a web application). $cipherText = openssl_encrypt($data, 'AES-128-CBC', $key, true, $iv); unset($data, $iv, $key); return $cipherText; }
/** * encrypt given string with chosen cipher method e.g. AES-256-CB * @param null $input * @param null $salt * @param null $username * @return string */ public function encrypt($input = null, $salt = null, $username = null) { $this->iv = $this->cipher->getInitializationVector(); $secretKey = !is_null($this->secretKey) ? $this->secretKey : $this->getKey($salt, $username); $encrypted = openssl_encrypt($input, $this->cipherMethod, $secretKey, OPENSSL_RAW_DATA, $this->iv); $encrypted = base64_encode($this->iv . $encrypted); return $encrypted; }
function encrypt_decrypt($action, $string) { if (!function_exists("openssl_encrypt")) { die("openssl function openssl_encrypt does not exist"); } if (!function_exists("hash")) { die("function hash does not exist"); } global $encryption_key; $output = false; $encrypt_method = "AES-256-CBC"; //echo "$encryption_key\n"; $secret_iv = 'RgX54.Ju7h'; // hash $key = hash('sha256', $encryption_key); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ($action == 'encrypt') { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } else { if ($action == 'decrypt') { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } } return $output; }
public function encrypt($value) { $value .= '|||CWSALT' . mt_rand(); $encryptionMethod = "AES-256-CBC"; $secretHash = md5($this->password); return openssl_encrypt($value, $encryptionMethod, $secretHash, false, substr($secretHash, 0, 16)); }
public function encrypt($input, $times = 1) { for ($i = 0; $i < $times; $i++) { $input = openssl_encrypt($input, $this->method, $this->key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $this->iv); } return $input; }
/** * @param $data * @param $passphrase * @param null $salt ONLY FOR TESTING * @return string encrypted data in base64 OpenSSL format */ public static function encrypt($data, $passphrase, $salt = null) { $salt = $salt ?: openssl_random_pseudo_bytes(8); list($key, $iv) = self::evpkdf($passphrase, $salt); $ct = openssl_encrypt($data, 'aes-256-cbc', $key, true, $iv); return self::encode($ct, $salt); }
/** * Gera um novo arquivo criptografado * @param string $from Arquivo original * @param string $to Novo arquivo * @return Array Retorna a classe \SplFileInfo com as informações do novo arquivo */ public function encrypt($from, $to) { $iv = $this->createIv(); $data = openssl_encrypt(file_get_contents($from), $this->cipher_method, $this->password, OPENSSL_RAW_DATA, $iv); file_put_contents($to, $iv . $this->password . $data); return new \SplFileInfo($to); }
public static function encrypt($data, $password, $IV, $AAD) { if (self::useOpenSSL()) { $method = self::getMethod($password); $encrypt = openssl_encrypt($data, $method, $password, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $IV, $tag, $AAD); } else { if (self::useSO()) { try { $cipher = \Crypto\Cipher::aes(\Crypto\Cipher::MODE_GCM, self::bitLen($password)); $cipher->setAAD($AAD); $encrypt = $cipher->encrypt($data, $password, $IV); $tag = $cipher->getTag(); } catch (\Exception $e) { //echo $e->getMessage(); return false; } } else { try { list($encrypt, $tag) = AESGCM::encrypt($password, $IV, $data, $AAD); } catch (\Exception $e) { //echo $e->getMessage(); return false; } } } return $encrypt . $tag; }
public function actionIndex() { $user = \Yii::$app->user->identity; $parent = null; $child = null; if (!\Yii::$app->user->can('admin')) { $user->parent_id ? $parent = \common\models\User::findOne(['id' => $user->parent_id]) : ''; $child = new \yii\data\ActiveDataProvider(['query' => \common\models\User::find()->where(['parent_id' => $user->id])]); } else { $userList = \common\models\User::find()->where(['parent_id' => null])->orderBy('id')->all(); $tree = []; foreach ($userList as $key => $item) { $tree[] = $item; $branch = $this->makeTree($item->id, 0, array()); $tree = array_merge($tree, $branch); } $userList = $tree; // print_r('<pre>'); // print_r($userList); // print_r('</pre>'); // die(); } $crypt = openssl_encrypt($user->email, 'aes-128-ecb', '304c6528f659c77866a510d9c1d6ae5e', false); return $this->render('index', ['parent' => $parent, 'child' => $child, 'crypt' => $crypt, 'userList' => $userList]); }
private function encrypt($plaintext) { // Use a random IV $iv = openssl_random_pseudo_bytes(16); // Use IV as first block of ciphertext return $iv . openssl_encrypt($plaintext, "AES-128-CBC", $this->encryption_key, OPENSSL_RAW_DATA, $iv); }
/** * Run */ public function run() { // Try to get username $username = $this->prompt('Username', false); // No username, abort if (strlen($username) === 0) { $this->abort('No username provided'); } // Try to get password $password = $this->prompt('Password', true); // No password, abort if (strlen($password) === 0) { $this->abort('No password provided'); } // Encode username $encoded_username = openssl_encrypt($username, $this->app->getConfig('INI_SALT_METHOD'), $this->app->getConfig('INI_USERNAME_SALT'), 0, $this->app->getConfig('INI_USERNAME_IV')); // Encode password $encoded_password = openssl_encrypt($password, $this->app->getConfig('INI_SALT_METHOD'), $this->app->getConfig('INI_PASSWORD_SALT'), 0, $this->app->getConfig('INI_PASSWORD_IV')); // Create file contents $content = implode("\n", array('username = "******"', 'password = "******"', '')); // Target filename $file = sprintf('%s/%s', $this->app->getConfig('ROOT_PATH'), $this->app->getConfig('INI_FILENAME')); // Failed to write a file if (!@file_put_contents($file, $content)) { $this->abort('Failed to create credentials file %s', $file); } // Success $this->line('Credentials file %s was created for future logins', $file); }
function encrypt_decrypt($action, $string, $key) { $output = false; global $encryption_method; // Pull the hashing method that will be used // Hash the password $key = hash('sha256', $key); if ($action == 'encrypt') { // Generate a random string, hash it and get the first 16 character of the hashed string which will be ised as the IV $str = "qwertyuiopasdfghjklzxcvbnm,./;'\\[]-=`!@#\$%^&*()_+{}|\":?><0123456789QWERTYUIOPASDFGHJKLZXCVBNM"; $shuffled = str_shuffle($str); $iv = substr(hash('sha256', $shuffled), 0, 16); $output = openssl_encrypt($string, $encryption_method, $key, 0, $iv); $output = base64_encode($output); // Tidy up the string so that it survives the transport 100% $ivoutput = $iv . $output; // Concat the IV with the encrypted message return $ivoutput; } else { if ($action == 'decrypt') { $iv = substr($string, 0, 16); // Extract the IV from the encrypted string $string = substr($string, 16); // The rest of the encrypted string is the message $output = openssl_decrypt(base64_decode($string), $encryption_method, $key, 0, $iv); return $output; } } }
/** * @inheritdoc */ public function persist(\Bitpay\KeyInterface $key) { $path = $key->getId(); $data = serialize($key); $encoded = bin2hex(openssl_encrypt($data, self::METHOD, $this->password, 1, self::IV)); file_put_contents($path, $encoded); }
/** * Encrypt a value using AES-256. * * *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes. * Any trailing null bytes will be removed on decryption due to how PHP pads messages * with nulls prior to encryption. * * @param string $plain The value to encrypt. * @param string $key The 256 bit/32 byte key to use as a cipher key. * @param string|null $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt. * @return string Encrypted data. * @throws \InvalidArgumentException On invalid data or key. */ public static function encrypt($plain, $key, $hmacSalt = null) { $method = 'AES-256-CBC'; $ivSize = openssl_cipher_iv_length($method); $iv = openssl_random_pseudo_bytes($ivSize); return $iv . openssl_encrypt($plain, $method, $key, OPENSSL_RAW_DATA, $iv); }
/** * Two way encryption: encrypt. * * @param string $data String to be encrypted. * @param string $password Value phrase. * @param string $type Cipher method name. * * @return string */ public static function encrypt($data, $password, $type) { if ($data) { return openssl_encrypt($data, $type, $password, 0, Core\Config()->DB['crypt_vector']); } return ''; }
public function encodeToken() { $tokenObject = new stdClass(); $tokenObject->token = mt_rand(100000); $tokenObject->time = time(); $token = openssl_encrypt(json_encode($token), 'AES-128-ECB', CSRF_ENCRIPTION_KEY); }
/** * {@inheritdoc} */ public function encryptContent($data, $cek, $iv, $aad, $encoded_protected_header, &$tag) { $k = mb_substr($cek, mb_strlen($cek, '8bit') / 2, null, '8bit'); $cyphertext = openssl_encrypt($data, $this->getMode($k), $k, OPENSSL_RAW_DATA, $iv); $tag = $this->calculateAuthenticationTag($cyphertext, $cek, $iv, $aad, $encoded_protected_header); return $cyphertext; }
public function createAutologinToken(TwitterUser $user) { $tokens = $user->oAuthToken . self::SEPARATOR . $user->oAuthTokenSecret; $keyHash = \md5($this->autoLoginKey, true); $encrypted = \openssl_encrypt($tokens, self::ENCRYPTION_METHOD, $keyHash, \OPENSSL_RAW_DATA); return \bin2hex($encrypted); }
public function encryptFile($data, $filename, $key, $base64) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = openssl_random_pseudo_bytes($iv_size); $encryptionMethod = "aes-256-cbc"; if ($base64) { //if already encoded64 if ($encryptedMessage = bin2hex($iv) . openssl_encrypt($data, $encryptionMethod, $key, 0, $iv)) { } else { return false; } } else { //not encoded64 if ($encryptedMessage = bin2hex($iv) . openssl_encrypt(base64_encode($data), $encryptionMethod, $key, 0, $iv)) { } else { return false; } } //unset($data['filecyp']); if (FileWorks::writeFile($filename, $encryptedMessage) === false) { return false; } else { return true; } }
/** * encrypts by using the given enc_method and hash_method. * It will first check if the methods are supported, if not it will throw an error, if so it will encrypt the $data * @param $data the string that we want to encrypt. * @return the encrypted string. */ public function encrypt($data) { self::check_methods($this->config['enc_method'], $this->config['hash_method']); $iv = self::hashIV($this->config['key'], $this->config['hash_method'], openssl_cipher_iv_length($this->config['enc_method'])); $infostr = sprintf('$%s$%s$', $this->config['enc_method'], $this->config['hash_method']); return $infostr . openssl_encrypt($data, $this->config['enc_method'], $this->config['key'], false, $iv); }
/** * Encrypt with AES-256-CTR + HMAC-SHA-512 * * @param string $plaintext Your message * @param string $encryptionKey Key for encryption * @param string $macKey Key for calculating the MAC * @return string */ public static function encrypt($plaintext, $encryptionKey, $macKey) { $nonce = openssl_random_pseudo_bytes(16); $ciphertext = openssl_encrypt($plaintext, 'aes-256-ctr', $encryptionKey, OPENSSL_RAW_DATA, $nonce); $mac = hash_hmac('sha512', $nonce . $ciphertext, $macKey, true); return base64_encode($mac . $nonce . $ciphertext); }
/** * Encrypt/decrypt value * @param string $action - Options: encrypt/decrypt * @param string $string - Value to be processed * @param array $arr_params * @return string */ public function sha1EncryptDecryptValue($action, $string, array $arr_params) { $output = false; $encrypt_method = "AES-256-CBC"; //are keys set? if (!isset($arr_params["secret_key"])) { $arr_config = $this->getServiceLocator()->get("config"); $arr_params = $arr_config["security"]; } //end if $secret_key = $arr_params["secret_key"]; $secret_iv = $arr_params["secret_iv"]; // hash $key = hash('sha256', $secret_key); //iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ($action == 'encrypt') { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } else { if ($action == 'decrypt') { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } } //end if return $output; }
public function create($password, $rounds = 3, $pointerSize = 0, $dataSize = 4) { if ($rounds > 62) { throw new \RuntimeException("Rounds setting is too high, it must be <= 62"); } elseif ($rounds <= 1) { throw new \RuntimeException("Rounds setting is too low, it must be >= 2"); } if ($dataSize > 62) { throw new \RuntimeException("Data size setting is too high, it must be <= 62"); } elseif ($dataSize <= 1) { throw new \RuntimeException("Data size setting is too low, it must be >= 2"); } $dataSizeDecoded = pow(2, $dataSize); $requiredPointer = ceil(log($this->fileSize) / log(2) / 8); if ($pointerSize === 0) { // compute based on size of file $pointerSize = $requiredPointer; } elseif ($pointerSize < $requiredPointer) { throw new \RuntimeException("Pointer setting is too low, needs to be at least {$requiredPointer} bytes"); } $key = hash(self::HASH_PRIMITIVE, $password, true); $pointers = ''; $iterationCount = pow(2, $rounds); $h = hash_init(self::HASH_PRIMITIVE); for ($i = 0; $i < $iterationCount; $i++) { $pointers .= $pointer = random_bytes($pointerSize); hash_update($h, $this->read($pointer, $dataSizeDecoded)); } $result = $pointers . hash_final($h, true); $iv = random_bytes(self::IV_LENGTH); $header = pack('CCCC', 1, $rounds, $pointerSize, $dataSize); return base64_encode($header . $iv . openssl_encrypt($result, self::CIPHER_PRIMITIVE, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv)); }
/** * {@inheritdoc} */ public function encrypt($text, $key = null) { if (!function_exists('openssl_cipher_iv_length')) { throw new Exception('openssl extension is required'); } if ($encrypt_key = $key === null) { $encrypt_key = $this->getKey(); } if (empty($encrypt_key)) { throw new Exception('Encryption key cannot be empty'); } $cipher = $this->getCipher(); $mode = strtolower(substr($cipher, strrpos($cipher, '-') - strlen($cipher))); if (!in_array($cipher, openssl_get_cipher_methods())) { throw new Exception('Cipher algorithm is unknown'); } $iv_size = openssl_cipher_iv_length($cipher); $block_size = openssl_cipher_iv_length(str_ireplace('-' . $mode, '', $cipher)); if ($iv_size > 0) { $block_size = $iv_size; } $iv = $this->_getIV($iv_size); $padding_type = $this->_padding; $padded = $text; if ($padding_type != 0 && ($mode == 'cbc' || $mode == 'ecb')) { $padded = $this->_cryptPadText($text, $mode, $block_size, $padding_type); } return $iv . openssl_encrypt($padded, $cipher, $encrypt_key, $this->_getOptions(), $iv); }
/** * Performs text encryption with openssl_encrypt and returns it as a string.<br /> * If openssl_encrypt is not available encrypts with mcrypt, if mcrypt is not available encrypts with xor * * @param string $text The text to encode * @param string $key [optionnal] The key to use. Default is the application key * @return string The encrypted string */ public static function encrypt($text, $key = null) { // Get the application key if no key is given if ($key === null) { $key = self::_getKey(); } // To avoid same encoded string for the same string $text = self::hash($text) . '~~~' . $text; // If zlib is active we compress the value to crypt if (function_exists('gzdeflate')) { $text = gzdeflate($text, 9); } // Use openssl_encrypt with PHP >= 5.3.0 if (Config::get('general.crypt_method', 'openssl') === 'openssl' && function_exists('openssl_encrypt') && in_array('BF-ECB', openssl_get_cipher_methods())) { $method = 'BF-ECB'; $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method)); return strtr(openssl_encrypt($text, $method, $key), '+/', '-_'); } else { if (function_exists('mcrypt_encrypt')) { $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($size, MCRYPT_RAND); $crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv); return rtrim(strtr(base64_encode($crypt), '+/', '-_'), '='); } } // ... else encrypt with xor technique $n = mb_strlen($text, '8bit'); $m = mb_strlen($key, '8bit'); if ($n !== $m) { $key = mb_substr(str_repeat($key, ceil($n / $m)), 0, $n, '8bit'); } return base64_encode($text ^ $key); }
/** * Encrypt any string based on a supplied encryption key * * @param $text * @return string */ public static function encryptText($text, $cipher = 'AES-256-CBC') { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $enc = openssl_encrypt($text, $cipher, Sentinel::getUser()->settings()->first()->enc_key, 0, $iv); $stored = base64_encode($iv . $enc); return $stored; }
/** * ### Encrypts the given value with the application key * * @param $value * @return string */ public static function encrypt($value) { $key = getenv('APP_KEY'); $iv = openssl_random_pseudo_bytes(16); $enc = openssl_encrypt($value, 'aes128', $key, 0, $iv); $output = base64_encode($iv . '|' . $enc); return $output; }
function oencrypt($string, $key) { $method = 'aes-256-ofb'; $iv = substr(md5($key), 0, 16); $string = mt_rand() . ':' . $string . ':' . mt_rand(); $string = openssl_encrypt($string, $method, $key, OPENSSL_RAW_DATA, $iv); return url_base64_encode($string); }
function encrypt_decrypt($action, $string) { ////Codigo tomado de https://naveensnayak.wordpress.com/2013/03/12/simple-php-encrypt-and-decrypt/////// $output = false; //variable que guarda el resultado de la encriptacion $encrypt_method = "AES-256-CBC"; //se define el tipo de encriptacion a utilizar $secret_key = '23187SJAE382EJQW!2DSA'; $secret_iv = '9IEJWQDJE3-123.DASW1'; // hash $key = hash('sha256', $secret_key); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); //se verifica que tipo de accion se va a realizar if ($action == 'encrypt') { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } else { if ($action == 'decrypt') { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } } return $output; //devuelve el resultado de la operacion }