Last active
August 29, 2015 14:21
-
-
Save SyuTingSong/d00a37728457bfc338c1 to your computer and use it in GitHub Desktop.
AES-256-CFB Stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by IntelliJ IDEA. | |
* User: xts | |
* Date: 15/5/20 | |
* Time: 10:05PM | |
*/ | |
namespace xts; | |
class AESStreamFilter { | |
private $key; | |
private $iv; | |
private $tail = ''; | |
private $isDecrypt; | |
public function __construct($key, $iv, $isDecrypt=false) { | |
$this->key = $key; | |
$this->iv = $iv; | |
$this->isDecrypt = $isDecrypt; | |
} | |
public function filter($data) { | |
if (strlen($data) == 0) | |
return ''; | |
$tl = strlen($this->tail); | |
if ($tl) | |
$data = $this->tail . $data; | |
if ($this->isDecrypt) | |
$b = openssl_decrypt($data, 'aes-256-cfb', $this->key, OPENSSL_RAW_DATA, $this->iv); | |
else | |
$b = openssl_encrypt($data, 'aes-256-cfb', $this->key, OPENSSL_RAW_DATA, $this->iv); | |
$result = substr($b, $tl); | |
$dataLength = strlen($data); | |
$mod16 = $dataLength%16; | |
if ($dataLength >= 16) { | |
$iPos = -($mod16 + 16); | |
if ($this->isDecrypt) | |
$this->iv = substr($data, $iPos, 16); | |
else | |
$this->iv = substr($b, $iPos, 16); | |
} | |
$this->tail = $mod16!=0 ? substr($data, -$mod16):''; | |
return $result; | |
} | |
} | |
// Example | |
$dataToEncrypt = array( | |
'Shadowsocks is ', | |
'a secure socks5 proxy, designed to protect your Internet traffic. ', | |
'Aa ', | |
'我是中文汉字', | |
'bB ', | |
); | |
$key = openssl_random_pseudo_bytes(32); // 256bit Key Length | |
$iv = openssl_random_pseudo_bytes(16); // 128bit AES Block Length | |
$enc = new AESStreamFilter($key, $iv); | |
$crypto = ''; | |
foreach ($dataToEncrypt as $data) { | |
$crypto .= $enc->filter($data); | |
} | |
echo openssl_decrypt($crypto, 'aes-256-cfb', $key, OPENSSL_RAW_DATA, $iv), "\n"; | |
$text = 'This is a test for my aes-256-cfb stream program with some 中文字符.'; | |
$crypto = openssl_encrypt($text, 'aes-256-cfb', $key, OPENSSL_RAW_DATA, $iv); | |
$parts[] = substr($crypto, 0, 7); | |
$parts[] = substr($crypto, 7, 8); | |
$parts[] = substr($crypto, 15, 17); | |
$parts[] = substr($crypto, 32, 2); | |
$parts[] = substr($crypto, 34, 12); | |
$parts[] = substr($crypto, 46); | |
$dec = new AESStreamFilter($key, $iv, true); | |
$text = ''; | |
foreach ($parts as $part) { | |
$text .= $dec->filter($part); | |
} | |
echo $text, "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment