Read part 1: RC5 block cipher implement in PHP and Javascript
Application of this block cipher method for stream cipher:
There are many methods, but we can provide the method below:
Split your string into many block with 64 bits (8 characters), then use this block cipher method. We can use the method Null-padding for the case the string length is odd.
The key must have 16 characters (128 bits), so, we must use one Key-scheduling algorithm (KSA) to convert the key to the new key 128 bits.
PHP:
private static function _nullpadding($str,$length=16){ if(strlen($str)%$length != 0){ $str .= str_repeat(chr(0),$length-strlen($str)%$length); } return $str; } private static function key($key){ for ($s = array(), $i = 0; $i < 256; $i++) $s[$i] = $i; for ($j = 0, $i = 0; $i < 256; $i++) { $j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256; $x = $s[$i]; $s[$i] = $s[$j]; $s[$j] = $x; } return $s; } // convert 32bits interger to 4characters string private static function _32bits2str($block){ return pack('N',$block & 0xffffffff); } // convert 4characters string to 32bits interger private static function _str232bits($block){ return unpack('N*',$block)[1]; } //Stream cipher encrypt use RC5 public static function RC5enc($str,$key,$mode='ECB'){ $str = self::_nullpadding($str, 8);//var_dump($str);die(); $enc = ''; $k = self::key($key); //var_dump($k);die(); self::rc5_init($k); for($i=0;$i<strlen($str)/8;$i++){ $block = substr($str,$i*8,8); $chr = array(self::_str232bits(substr($block,0,4)),self::_str232bits(substr($block,4,4))); $e = self::rc5_encrypt($chr); $enc .= self::_32bits2str($e[0]).self::_32bits2str($e[1]); } return $enc; } //Stream cipher decrypt use RC5 public static function RC5dec($str,$key,$mode='ECB'){ $enc = ''; $k = self::key($key); self::rc5_init($k); for($i=0;$i<strlen($str)/8;$i++){ $block = substr($str,$i*8,8); $chr = array(self::_str232bits(substr($block,0,4)),self::_str232bits(substr($block,4,4))); $e = self::rc5_decrypt($chr); $enc .= self::_32bits2str($e[0]).self::_32bits2str($e[1]); } return rtrim($enc,chr(0)); }
Here, we use ECB mode, you can use CBC, PCBC, CFB, OFB, CTR mode.
Javascript:
Example:
1 Comment
RC5 block cipher implement in PHP and Javascript | Free Online Tutorials
(February 12, 2017 - 2:01 pm)[…] Part 2: RC5 block cipher implement in PHP and Javascript – part 2 […]