PHP数据加密,解密猛砸其 [英] PHP Encrypt Data, Bash Decrypt it

查看:167
本文介绍了PHP数据加密,解密猛砸其的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图想出一个办法来让PHP加密文件。我以前只使用一个PHP系统调用来运行一个脚本,连接codeD文件:

I am trying to come up with a way to have PHP encrypt a file. I used to just use a PHP system call to run a script that encoded the file:

#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -salt -k $1 -in $2

参数1是要使用的密码和参数2是数据。然后,我在计算机上使用第二个脚本去隐窝文件。

Argument 1 was the password to use and argument 2 is the data. I then use a second script on a computer to de-crypt the file.

#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -d -salt -k $1 -in $2

作为PHP系统调用被禁用加密的这个方法不会在生产主机上运行。我还要preFER不会改变去code函数,如果在所有可能的。

This method of encrypting will not work on a production host as the PHP system call is disabled. I also would prefer not the change the decode function if at all possible.

有没有办法只使用PHP来复制上面的加密功能?

Is there a way to replicate the above encrypt function using only PHP?

推荐答案

如上评论指出填充是必要的,使这项工作。下面的功能将可以在命令行中解密这样的文件:

As stated above in the comments padding is necessary to make this work. The function below will make a file that can be decrypted on the command line like this:

openssl enc -d -aes-256-cbc -a -salt -in test.txt

的test.txt文件是从以下ssl_encrypt函数的输出创建的。

The test.txt file is created from the output of the ssl_encrypt function below.

function ssl_encrypt($pass, $data)
{
    // Set a random salt
    $salt = substr(md5(mt_rand(), true), 8);

    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $pad = $block - (strlen($data) % $block);

    $data = $data . str_repeat(chr($pad), $pad);

    // Setup encryption parameters
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");


    $key_len =  mcrypt_enc_get_key_size($td);
    $iv_len =  mcrypt_enc_get_iv_size($td);

    $total_len = $key_len + $iv_len;
    $salted = '';
    $dx = '';
    // Salt the key and iv
    while (strlen($salted) < $total_len)
    {
        $dx = md5($dx.$pass.$salt, true);
        $salted .= $dx;
    }
    $key = substr($salted,0,$key_len);
    $iv = substr($salted,$key_len,$iv_len);


    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $data);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);


    return chunk_split(base64_encode('Salted__' . $salt . $encrypted_data),32,"\r\n");
}

示例用法:

$plainText = "Secret Message";
$password = "SecretPassword";
$test = ssl_encrypt($password, $plainText);
$file = fopen('test.txt', 'wb');
// Write the Base64 encrypted output to a file.
fwrite($file, $test);
fclose($file);
// Show the output on the screen
echo $test;

参考: HTTP://juan.boxfi .COM / 2010/03/16 /写的OpenSSL文件 - 在PHP /

这篇关于PHP数据加密,解密猛砸其的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆