PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/jcryption.php

https://github.com/madhavvyas/jCryption
PHP | 669 lines | 392 code | 74 blank | 203 comment | 98 complexity | 28353fd7392d9688af4904e0699eeffd MD5 | raw file
  1. <?php
  2. /**
  3. * jCryption
  4. *
  5. * PHP version 5.3
  6. *
  7. * LICENSE: This source file is subject to version 3.0 of the PHP license
  8. * that is available through the world-wide-web at the following URI:
  9. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  10. * the PHP License and are unable to obtain it through the web, please
  11. * send a note to license@php.net so we can mail you a copy immediately.
  12. *
  13. * Many of the functions in this class are from the PEAR Crypt_RSA package ...
  14. * So most of the credits goes to the original creator of this package Alexander Valyalkin
  15. * you can get the package under http://pear.php.net/package/Crypt_RSA
  16. *
  17. * I just changed, added, removed and improved some functions to fit the needs of jCryption
  18. *
  19. * @author Daniel Griesser <daniel.griesser@jcryption.org>
  20. * @copyright 2011 Daniel Griesser
  21. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  22. * @version 1.2
  23. * @link http://jcryption.org/
  24. */
  25. class jCryption {
  26. private $_key_len;
  27. private $_e;
  28. public function __construct($e="\x01\x00\x01") {
  29. $this->_e = $e;
  30. }
  31. /**
  32. * Generates the Keypair with the given keyLength the encryption key e ist set staticlly
  33. * set to 65537 for faster encryption.
  34. *
  35. * @param int $keyLength
  36. * @return array
  37. */
  38. public function generateKeypair($keyLength) {
  39. $this->_key_len = intval($keyLength);
  40. if ($this->_key_len < 8) {
  41. $this->_key_len = 8;
  42. }
  43. // set [e] to 0x10001 (65537)
  44. $e = $this->_bin2int($this->_e);
  45. // generate [p], [q] and [n]
  46. $p_len = intval(($this->_key_len + 1) / 2);
  47. $q_len = $this->_key_len - $p_len;
  48. $p1 = $q1 = 0;
  49. do {
  50. // generate prime number [$p] with length [$p_len] with the following condition:
  51. // GCD($e, $p - 1) = 1
  52. do {
  53. $p = $this->getPrime($p_len);
  54. $p1 = bcsub($p, '1');
  55. $tmp = $this->_gcd($e, $p1);
  56. } while (bccomp($tmp, '1'));
  57. // generate prime number [$q] with length [$q_len] with the following conditions:
  58. // GCD($e, $q - 1) = 1
  59. // $q != $p
  60. do {
  61. $q = $this->getPrime($q_len);
  62. $q1 = bcsub($q, '1');
  63. $tmp = $this->_gcd($e, $q1);
  64. } while (bccomp($tmp, '1') && !bccomp($q, $p));
  65. // if (p < q), then exchange them
  66. if (bccomp($p, $q) < 0) {
  67. $tmp = $p;
  68. $p = $q;
  69. $q = $tmp;
  70. $tmp = $p1;
  71. $p1 = $q1;
  72. $q1 = $tmp;
  73. }
  74. // calculate n = p * q
  75. $n = bcmul($p, $q);
  76. } while ($this->_bitLen($n) != $this->_key_len);
  77. // calculate d = 1/e mod (p - 1) * (q - 1)
  78. $pq = bcmul($p1, $q1);
  79. $d = $this->_invmod($e, $pq);
  80. // store RSA keypair attributes
  81. return array('n' => $n, 'e' => $e, 'd' => $d, 'p' => $p, 'q' => $q);
  82. }
  83. /**
  84. * Finds greatest common divider (GCD) of $num1 and $num2
  85. *
  86. * @param string $num1
  87. * @param string $num2
  88. * @return string
  89. */
  90. private function _gcd($num1, $num2) {
  91. do {
  92. $tmp = bcmod($num1, $num2);
  93. $num1 = $num2;
  94. $num2 = $tmp;
  95. } while (bccomp($num2, '0'));
  96. return $num1;
  97. }
  98. /**
  99. * Transforms binary representation of large integer into its native form.
  100. *
  101. * Example of transformation:
  102. * $str = "\x12\x34\x56\x78\x90";
  103. * $num = 0x9078563412;
  104. *
  105. * @param string $str
  106. * @return string
  107. * @access public
  108. */
  109. private function _bin2int($str) {
  110. $result = '0';
  111. $n = strlen($str);
  112. do {
  113. $result = bcadd(bcmul($result, '256'), ord($str {--$n} ));
  114. } while ($n > 0);
  115. return $result;
  116. }
  117. /**
  118. * Transforms large integer into binary representation.
  119. *
  120. * Example of transformation:
  121. * $num = 0x9078563412;
  122. * $str = "\x12\x34\x56\x78\x90";
  123. *
  124. * @param string $num
  125. * @return string
  126. * @access public
  127. */
  128. private function _int2bin($num) {
  129. $result = '';
  130. do {
  131. $result .= chr(bcmod($num, '256'));
  132. $num = bcdiv($num, '256');
  133. } while (bccomp($num, '0'));
  134. return $result;
  135. }
  136. /**
  137. * Generates prime number with length $bits_cnt
  138. *
  139. * @param int $bits_cnt
  140. */
  141. public function getPrime($bits_cnt) {
  142. $bytes_n = intval($bits_cnt / 8);
  143. do {
  144. $str = '';
  145. $str = openssl_random_pseudo_bytes($bytes_n);
  146. $num = $this->_bin2int($str);
  147. $num = gmp_strval(gmp_nextprime($num));
  148. } while ($this->_bitLen($num) != $bits_cnt);
  149. return $num;
  150. }
  151. /**
  152. * Finds inverse number $inv for $num by modulus $mod, such as:
  153. * $inv * $num = 1 (mod $mod)
  154. *
  155. * @param string $num
  156. * @param string $mod
  157. * @return string
  158. */
  159. private function _invmod($num, $mod) {
  160. $x = '1';
  161. $y = '0';
  162. $num1 = $mod;
  163. do {
  164. $tmp = bcmod($num, $num1);
  165. $q = bcdiv($num, $num1);
  166. $num = $num1;
  167. $num1 = $tmp;
  168. $tmp = bcsub($x, bcmul($y, $q));
  169. $x = $y;
  170. $y = $tmp;
  171. } while (bccomp($num1, '0'));
  172. if (bccomp($x, '0') < 0) {
  173. $x = bcadd($x, $mod);
  174. }
  175. return $x;
  176. }
  177. /**
  178. * Returns bit length of number $num
  179. *
  180. * @param string $num
  181. * @return int
  182. */
  183. private function _bitLen($num) {
  184. $tmp = $this->_int2bin($num);
  185. $bit_len = strlen($tmp) * 8;
  186. $tmp = ord($tmp {strlen($tmp) - 1} );
  187. if (!$tmp) {
  188. $bit_len -= 8;
  189. } else {
  190. while (!($tmp & 0x80)) {
  191. $bit_len--;
  192. $tmp <<= 1;
  193. }
  194. }
  195. return $bit_len;
  196. }
  197. /**
  198. * Converts a hex string to bigint string
  199. *
  200. * @param string $hex
  201. * @return string
  202. */
  203. private function _hex2bint($hex) {
  204. $result = '0';
  205. for ($i=0; $i < strlen($hex); $i++) {
  206. $result = bcmul($result, '16');
  207. if ($hex[$i] >= '0' && $hex[$i] <= '9') {
  208. $result = bcadd($result, $hex[$i]);
  209. } else if ($hex[$i] >= 'a' && $hex[$i] <= 'f') {
  210. $result = bcadd($result, '1' . ('0' + (ord($hex[$i]) - ord('a'))));
  211. } else if ($hex[$i] >= 'A' && $hex[$i] <= 'F') {
  212. $result = bcadd($result, '1' . ('0' + (ord($hex[$i]) - ord('A'))));
  213. }
  214. }
  215. return $result;
  216. }
  217. /**
  218. * Converts a hex string to int
  219. *
  220. * @param string $hex
  221. * @return int
  222. * @access public
  223. */
  224. private function _hex2int($hex) {
  225. $result = 0;
  226. for ($i=0; $i < strlen($hex); $i++) {
  227. $result *= 16;
  228. if ($hex[$i] >= '0' && $hex[$i] <= '9') {
  229. $result += ord($hex[$i]) - ord('0');
  230. } else if ($hex[$i] >= 'a' && $hex[$i] <= 'f') {
  231. $result += 10 + (ord($hex[$i]) - ord('a'));
  232. } else if ($hex[$i] >= 'A' && $hex[$i] <= 'F') {
  233. $result += 10 + (ord($hex[$i]) - ord('A'));
  234. }
  235. }
  236. return $result;
  237. }
  238. /**
  239. * Converts a bigint string to the ascii code
  240. *
  241. * @param string $bigint
  242. * @return string
  243. */
  244. private function _bint2char($bigint) {
  245. $message = '';
  246. while (bccomp($bigint, '0') != 0) {
  247. $ascii = bcmod($bigint, '256');
  248. $bigint = bcdiv($bigint, '256', 0);
  249. $message .= chr($ascii);
  250. }
  251. return $message;
  252. }
  253. /**
  254. * Removes the redundacy in den encrypted string
  255. *
  256. * @param string $string
  257. * @return mixed
  258. */
  259. private function _redundacyCheck($string) {
  260. $r1 = substr($string, 0, 2);
  261. $r2 = substr($string, 2);
  262. $check = $this->_hex2int($r1);
  263. $value = $r2;
  264. $sum = 0;
  265. for ($i=0; $i < strlen($value); $i++) {
  266. $sum += ord($value[$i]);
  267. }
  268. if ($check == ($sum & 0xFF)) {
  269. return $value;
  270. } else {
  271. return NULL;
  272. }
  273. }
  274. /**
  275. * Decrypts a given string with the $dec_key and the $enc_mod
  276. *
  277. * @param string $encrypted
  278. * @param int $dec_key
  279. * @param int $enc_mod
  280. * @return string
  281. */
  282. public function decrypt($encrypted, $dec_key, $enc_mod) {
  283. //replaced split with explode
  284. $blocks = explode(' ', $encrypted);
  285. $result = "";
  286. $max = count($blocks);
  287. for ($i=0; $i < $max; $i++) {
  288. $dec = $this->_hex2bint($blocks[$i]);
  289. if (function_exists('gmp_strval') && function_exists('gmp_powm')){
  290. $dec = gmp_strval(gmp_powm($dec, $dec_key, $enc_mod));
  291. } else {
  292. $dec = bcpowmod($dec, $dec_key, $enc_mod);
  293. }
  294. $ascii = $this->_bint2char($dec);
  295. $result .= $ascii;
  296. }
  297. return $this->_redundacyCheck($result);
  298. }
  299. /**
  300. * Converts a given decimal string to any base between 2 and 36
  301. *
  302. * @param string $decimal
  303. * @param int $base
  304. * @return string
  305. */
  306. public function dec2string($decimal, $base) {
  307. $string = null;
  308. $base = (int) $base;
  309. if ($base < 2 | $base > 36 | $base == 10) {
  310. echo 'BASE must be in the range 2-9 or 11-36';
  311. exit;
  312. }
  313. $charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  314. $charset = substr($charset, 0, $base);
  315. do {
  316. $remainder = bcmod($decimal, $base);
  317. $char = substr($charset, $remainder, 1);
  318. $string = $char . $string;
  319. $decimal = bcdiv(bcsub($decimal, $remainder), $base);
  320. } while ($decimal > 0);
  321. return strtolower($string);
  322. }
  323. }
  324. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  325. /* AES implementation in PHP (c) Chris Veness 2005-2011. Right of free use is granted for all */
  326. /* commercial or non-commercial use under CC-BY licence. No warranty of any form is offered. */
  327. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  328. class Aes {
  329. /**
  330. * AES Cipher function: encrypt 'input' with Rijndael algorithm
  331. *
  332. * @param input message as byte-array (16 bytes)
  333. * @param w key schedule as 2D byte-array (Nr+1 x Nb bytes) -
  334. * generated from the cipher key by keyExpansion()
  335. * @return ciphertext as byte-array (16 bytes)
  336. */
  337. public static function cipher($input, $w) { // main cipher function [§5.1]
  338. $Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
  339. $Nr = count($w)/$Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
  340. $state = array(); // initialise 4xNb byte-array 'state' with input [§3.4]
  341. for ($i=0; $i<4*$Nb; $i++) $state[$i%4][floor($i/4)] = $input[$i];
  342. $state = self::addRoundKey($state, $w, 0, $Nb);
  343. for ($round=1; $round<$Nr; $round++) { // apply Nr rounds
  344. $state = self::subBytes($state, $Nb);
  345. $state = self::shiftRows($state, $Nb);
  346. $state = self::mixColumns($state, $Nb);
  347. $state = self::addRoundKey($state, $w, $round, $Nb);
  348. }
  349. $state = self::subBytes($state, $Nb);
  350. $state = self::shiftRows($state, $Nb);
  351. $state = self::addRoundKey($state, $w, $Nr, $Nb);
  352. $output = array(4*$Nb); // convert state to 1-d array before returning [§3.4]
  353. for ($i=0; $i<4*$Nb; $i++) $output[$i] = $state[$i%4][floor($i/4)];
  354. return $output;
  355. }
  356. private static function addRoundKey($state, $w, $rnd, $Nb) { // xor Round Key into state S [§5.1.4]
  357. for ($r=0; $r<4; $r++) {
  358. for ($c=0; $c<$Nb; $c++) $state[$r][$c] ^= $w[$rnd*4+$c][$r];
  359. }
  360. return $state;
  361. }
  362. private static function subBytes($s, $Nb) { // apply SBox to state S [§5.1.1]
  363. for ($r=0; $r<4; $r++) {
  364. for ($c=0; $c<$Nb; $c++) $s[$r][$c] = self::$sBox[$s[$r][$c]];
  365. }
  366. return $s;
  367. }
  368. private static function shiftRows($s, $Nb) { // shift row r of state S left by r bytes [§5.1.2]
  369. $t = array(4);
  370. for ($r=1; $r<4; $r++) {
  371. for ($c=0; $c<4; $c++) $t[$c] = $s[$r][($c+$r)%$Nb]; // shift into temp copy
  372. for ($c=0; $c<4; $c++) $s[$r][$c] = $t[$c]; // and copy back
  373. } // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
  374. return $s; // see fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
  375. }
  376. private static function mixColumns($s, $Nb) { // combine bytes of each col of state S [§5.1.3]
  377. for ($c=0; $c<4; $c++) {
  378. $a = array(4); // 'a' is a copy of the current column from 's'
  379. $b = array(4); // 'b' is a•{02} in GF(2^8)
  380. for ($i=0; $i<4; $i++) {
  381. $a[$i] = $s[$i][$c];
  382. $b[$i] = $s[$i][$c]&0x80 ? $s[$i][$c]<<1 ^ 0x011b : $s[$i][$c]<<1;
  383. }
  384. // a[n] ^ b[n] is a•{03} in GF(2^8)
  385. $s[0][$c] = $b[0] ^ $a[1] ^ $b[1] ^ $a[2] ^ $a[3]; // 2*a0 + 3*a1 + a2 + a3
  386. $s[1][$c] = $a[0] ^ $b[1] ^ $a[2] ^ $b[2] ^ $a[3]; // a0 * 2*a1 + 3*a2 + a3
  387. $s[2][$c] = $a[0] ^ $a[1] ^ $b[2] ^ $a[3] ^ $b[3]; // a0 + a1 + 2*a2 + 3*a3
  388. $s[3][$c] = $a[0] ^ $b[0] ^ $a[1] ^ $a[2] ^ $b[3]; // 3*a0 + a1 + a2 + 2*a3
  389. }
  390. return $s;
  391. }
  392. /**
  393. * Key expansion for Rijndael cipher(): performs key expansion on cipher key
  394. * to generate a key schedule
  395. *
  396. * @param key cipher key byte-array (16 bytes)
  397. * @return key schedule as 2D byte-array (Nr+1 x Nb bytes)
  398. */
  399. public static function keyExpansion($key) { // generate Key Schedule from Cipher Key [§5.2]
  400. $Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
  401. $Nk = count($key)/4; // key length (in words): 4/6/8 for 128/192/256-bit keys
  402. $Nr = $Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
  403. $w = array();
  404. $temp = array();
  405. for ($i=0; $i<$Nk; $i++) {
  406. $r = array($key[4*$i], $key[4*$i+1], $key[4*$i+2], $key[4*$i+3]);
  407. $w[$i] = $r;
  408. }
  409. for ($i=$Nk; $i<($Nb*($Nr+1)); $i++) {
  410. $w[$i] = array();
  411. for ($t=0; $t<4; $t++) $temp[$t] = $w[$i-1][$t];
  412. if ($i % $Nk == 0) {
  413. $temp = self::subWord(self::rotWord($temp));
  414. for ($t=0; $t<4; $t++) $temp[$t] ^= self::$rCon[$i/$Nk][$t];
  415. } else if ($Nk > 6 && $i%$Nk == 4) {
  416. $temp = self::subWord($temp);
  417. }
  418. for ($t=0; $t<4; $t++) $w[$i][$t] = $w[$i-$Nk][$t] ^ $temp[$t];
  419. }
  420. return $w;
  421. }
  422. private static function subWord($w) { // apply SBox to 4-byte word w
  423. for ($i=0; $i<4; $i++) $w[$i] = self::$sBox[$w[$i]];
  424. return $w;
  425. }
  426. private static function rotWord($w) { // rotate 4-byte word w left by one byte
  427. $tmp = $w[0];
  428. for ($i=0; $i<3; $i++) $w[$i] = $w[$i+1];
  429. $w[3] = $tmp;
  430. return $w;
  431. }
  432. // sBox is pre-computed multiplicative inverse in GF(2^8) used in subBytes and keyExpansion [§5.1.1]
  433. private static $sBox = array(
  434. 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
  435. 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
  436. 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
  437. 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
  438. 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
  439. 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
  440. 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
  441. 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
  442. 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
  443. 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
  444. 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
  445. 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
  446. 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
  447. 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
  448. 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
  449. 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16);
  450. // rCon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
  451. private static $rCon = array(
  452. array(0x00, 0x00, 0x00, 0x00),
  453. array(0x01, 0x00, 0x00, 0x00),
  454. array(0x02, 0x00, 0x00, 0x00),
  455. array(0x04, 0x00, 0x00, 0x00),
  456. array(0x08, 0x00, 0x00, 0x00),
  457. array(0x10, 0x00, 0x00, 0x00),
  458. array(0x20, 0x00, 0x00, 0x00),
  459. array(0x40, 0x00, 0x00, 0x00),
  460. array(0x80, 0x00, 0x00, 0x00),
  461. array(0x1b, 0x00, 0x00, 0x00),
  462. array(0x36, 0x00, 0x00, 0x00) );
  463. }
  464. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  465. /* AES counter (CTR) mode implementation in PHP (c) Chris Veness 2005-2011. Right of free use is */
  466. /* granted for all commercial or non-commercial use under CC-BY licence. No warranty of any */
  467. /* form is offered. */
  468. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  469. class AesCtr extends Aes {
  470. /**
  471. * Encrypt a text using AES encryption in Counter mode of operation
  472. * - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  473. *
  474. * Unicode multi-byte character safe
  475. *
  476. * @param plaintext source text to be encrypted
  477. * @param password the password to use to generate a key
  478. * @param nBits number of bits to be used in the key (128, 192, or 256)
  479. * @return encrypted text
  480. */
  481. public static function encrypt($plaintext, $password, $nBits) {
  482. $blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
  483. if (!($nBits==128 || $nBits==192 || $nBits==256)) return ''; // standard allows 128/192/256 bit keys
  484. // note PHP (5) gives us plaintext and password in UTF8 encoding!
  485. // use AES itself to encrypt password to get cipher key (using plain password as source for
  486. // key expansion) - gives us well encrypted key
  487. $nBytes = $nBits/8; // no bytes in key
  488. $pwBytes = array();
  489. for ($i=0; $i<$nBytes; $i++) $pwBytes[$i] = ord(substr($password,$i,1)) & 0xff;
  490. $key = Aes::cipher($pwBytes, Aes::keyExpansion($pwBytes));
  491. $key = array_merge($key, array_slice($key, 0, $nBytes-16)); // expand key to 16/24/32 bytes long
  492. // initialise 1st 8 bytes of counter block with nonce (NIST SP800-38A §B.2): [0-1] = millisec,
  493. // [2-3] = random, [4-7] = seconds, giving guaranteed sub-ms uniqueness up to Feb 2106
  494. $counterBlock = array();
  495. $nonce = floor(microtime(true)*1000); // timestamp: milliseconds since 1-Jan-1970
  496. $nonceMs = $nonce%1000;
  497. $nonceSec = floor($nonce/1000);
  498. $nonceRnd = floor(rand(0, 0xffff));
  499. for ($i=0; $i<2; $i++) $counterBlock[$i] = self::urs($nonceMs, $i*8) & 0xff;
  500. for ($i=0; $i<2; $i++) $counterBlock[$i+2] = self::urs($nonceRnd, $i*8) & 0xff;
  501. for ($i=0; $i<4; $i++) $counterBlock[$i+4] = self::urs($nonceSec, $i*8) & 0xff;
  502. // and convert it to a string to go on the front of the ciphertext
  503. $ctrTxt = '';
  504. for ($i=0; $i<8; $i++) $ctrTxt .= chr($counterBlock[$i]);
  505. // generate key schedule - an expansion of the key into distinct Key Rounds for each round
  506. $keySchedule = Aes::keyExpansion($key);
  507. //print_r($keySchedule);
  508. $blockCount = ceil(strlen($plaintext)/$blockSize);
  509. $ciphertxt = array(); // ciphertext as array of strings
  510. for ($b=0; $b<$blockCount; $b++) {
  511. // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
  512. // done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
  513. for ($c=0; $c<4; $c++) $counterBlock[15-$c] = self::urs($b, $c*8) & 0xff;
  514. for ($c=0; $c<4; $c++) $counterBlock[15-$c-4] = self::urs($b/0x100000000, $c*8);
  515. $cipherCntr = Aes::cipher($counterBlock, $keySchedule); // -- encrypt counter block --
  516. // block size is reduced on final block
  517. $blockLength = $b<$blockCount-1 ? $blockSize : (strlen($plaintext)-1)%$blockSize+1;
  518. $cipherByte = array();
  519. for ($i=0; $i<$blockLength; $i++) { // -- xor plaintext with ciphered counter byte-by-byte --
  520. $cipherByte[$i] = $cipherCntr[$i] ^ ord(substr($plaintext, $b*$blockSize+$i, 1));
  521. $cipherByte[$i] = chr($cipherByte[$i]);
  522. }
  523. $ciphertxt[$b] = implode('', $cipherByte); // escape troublesome characters in ciphertext
  524. }
  525. // implode is more efficient than repeated string concatenation
  526. $ciphertext = $ctrTxt . implode('', $ciphertxt);
  527. $ciphertext = base64_encode($ciphertext);
  528. return $ciphertext;
  529. }
  530. /**
  531. * Decrypt a text encrypted by AES in counter mode of operation
  532. *
  533. * @param ciphertext source text to be decrypted
  534. * @param password the password to use to generate a key
  535. * @param nBits number of bits to be used in the key (128, 192, or 256)
  536. * @return decrypted text
  537. */
  538. public static function decrypt($ciphertext, $password, $nBits) {
  539. $blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
  540. if (!($nBits==128 || $nBits==192 || $nBits==256)) return ''; // standard allows 128/192/256 bit keys
  541. $ciphertext = base64_decode($ciphertext);
  542. // use AES to encrypt password (mirroring encrypt routine)
  543. $nBytes = $nBits/8; // no bytes in key
  544. $pwBytes = array();
  545. for ($i=0; $i<$nBytes; $i++) $pwBytes[$i] = ord(substr($password,$i,1)) & 0xff;
  546. $key = Aes::cipher($pwBytes, Aes::keyExpansion($pwBytes));
  547. $key = array_merge($key, array_slice($key, 0, $nBytes-16)); // expand key to 16/24/32 bytes long
  548. // recover nonce from 1st element of ciphertext
  549. $counterBlock = array();
  550. $ctrTxt = substr($ciphertext, 0, 8);
  551. for ($i=0; $i<8; $i++) $counterBlock[$i] = ord(substr($ctrTxt,$i,1));
  552. // generate key schedule
  553. $keySchedule = Aes::keyExpansion($key);
  554. // separate ciphertext into blocks (skipping past initial 8 bytes)
  555. $nBlocks = ceil((strlen($ciphertext)-8) / $blockSize);
  556. $ct = array();
  557. for ($b=0; $b<$nBlocks; $b++) $ct[$b] = substr($ciphertext, 8+$b*$blockSize, 16);
  558. $ciphertext = $ct; // ciphertext is now array of block-length strings
  559. // plaintext will get generated block-by-block into array of block-length strings
  560. $plaintxt = array();
  561. for ($b=0; $b<$nBlocks; $b++) {
  562. // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
  563. for ($c=0; $c<4; $c++) $counterBlock[15-$c] = self::urs($b, $c*8) & 0xff;
  564. for ($c=0; $c<4; $c++) $counterBlock[15-$c-4] = self::urs(($b+1)/0x100000000-1, $c*8) & 0xff;
  565. $cipherCntr = Aes::cipher($counterBlock, $keySchedule); // encrypt counter block
  566. $plaintxtByte = array();
  567. for ($i=0; $i<strlen($ciphertext[$b]); $i++) {
  568. // -- xor plaintext with ciphered counter byte-by-byte --
  569. $plaintxtByte[$i] = $cipherCntr[$i] ^ ord(substr($ciphertext[$b],$i,1));
  570. $plaintxtByte[$i] = chr($plaintxtByte[$i]);
  571. }
  572. $plaintxt[$b] = implode('', $plaintxtByte);
  573. }
  574. // join array of blocks into single plaintext string
  575. $plaintext = implode('',$plaintxt);
  576. return $plaintext;
  577. }
  578. /*
  579. * Unsigned right shift function, since PHP has neither >>> operator nor unsigned ints
  580. *
  581. * @param a number to be shifted (32-bit integer)
  582. * @param b number of bits to shift a to the right (0..31)
  583. * @return a right-shifted and zero-filled by b bits
  584. */
  585. private static function urs($a, $b) {
  586. $a &= 0xffffffff; $b &= 0x1f; // (bounds check)
  587. if ($a&0x80000000 && $b>0) { // if left-most bit set
  588. $a = ($a>>1) & 0x7fffffff; // right-shift one bit & clear left-most bit
  589. $a = $a >> ($b-1); // remaining right-shifts
  590. } else { // otherwise
  591. $a = ($a>>$b); // use normal right-shift
  592. }
  593. return $a;
  594. }
  595. }