php 16字符加密,如何用PHP加密和解密65535个字符以上的字符串

把它分块,

这就是我所做的(使用PHPSecLib2)

/**

* AES encrypt large files using streams and chunking

*

* @param resource $stream

* @param resource $outputStream

* @param string $key

* @throws SecExecption

*/

function streamSymEncode($stream, &$outputStream, $key, $chunkSize = 10240){

if(!is_resource($stream)) throw new Execption('Resource expected[input]');

rewind($stream); //make sure the stream is rewound

if(!is_resource($outputStream)) throw new Execption('Resource expected[output]');

$Cipher = new AES(AES::MODE_CBC);

$Cipher->setKey($key);

//create the IV

$iv = Random::string($Cipher->getBlockLength() >> 3);

$Cipher->setIV($iv);

if(strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) throw new Execption('IV lenght check fail');

fwrite($outputStream, $iv_base64.'$'); //add the IV for later use when we decrypt

while(!feof($stream)){

$chunk = fread($stream, $chunkSize);

fwrite($outputStream, rtrim(base64_encode($Cipher->encrypt($chunk)),'=').':');

}

$stat = fstat($outputStream);

ftruncate($outputStream, $stat['size'] - 1); //trim off the last character, hanging ':'

}

/**

* AES decrypt large files that were previously encrypted using streams and chunking

*

* @param resource $stream

* @param resource $outputStream

* @param string $key

* @throws SecExecption

*/

function streamSymDecode($stream, &$outputStream, $key){

if(!is_resource($stream)) throw new Execption('Resource expected[input]');

rewind($stream); //make sure the stream is rewound

if(!is_resource($outputStream)) throw new Execption('Resource expected[output]');

$Cipher = new AES(AES::MODE_CBC);

$Cipher->setKey($key);

$iv = base64_decode(fread($stream, 22) . '==');

$Cipher->setIV($iv);

fread($stream, 1); //advance 1 for the $

$readLine = function(&$stream){

$line = '';

while(false !== ($char = fgetc($stream))){

if($char == ':') break;

$line .= $char;

}

return $line;

};

while(!feof($stream)){

$chunk = $readLine($stream);

$decrypted = $Cipher->decrypt(base64_decode($chunk.'=='));

if(!$decrypted) throw new Execption('Failed to decode!');

fwrite($outputStream, $decrypted);

}

}

fopen

还有一把钥匙。然后它使用相同的加密,但将文件分块到

$chunkSize

:

当它解码的时候,它会把它分解成块,然后重新组装所有的东西。

就这样结束了(例如)

IV$firstChunk:secondChunk:thirdChunk

干杯。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值