php rc4 实现

#最近公司更改加解密方式为rc4 为测试同学通过php实现 翻译为java 实现--
<?php function RC4($key, $pt) { $s = array(); for ($i=0; $i<256; $i++) { $s[$i] = $i; } $j = 0; $key_len = strlen($key); for ($i=0; $i<256; $i++) { $j = ($j + $s[$i] + ord($key[$i % $key_len])) % 256; //swap $x = $s[$i]; $s[$i] = $s[$j]; $s[$j] = $x; } $i = 0; $j = 0; $ct = ''; $data_len = strlen($pt); for ($y=0; $y< $data_len; $y++) { $i = ($i + 1) % 256; $j = ($j + $s[$i]) % 256; //swap $x = $s[$i]; $s[$i] = $s[$j]; $s[$j] = $x; $ct .= $pt[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]); } return $ct; } $text = 'This is a test string.'; $md5 = md5('password'); echo $md5 . "\n"; $key = pack('H*', $md5); //嫌的话,让 $key = 'testkey'; 试试 print bin2hex(RC4($key, $text)); echo "\n"; echo bin2hex(openssl_encrypt($text, "RC4", $key, true)); echo "\n";

  

//同等java 实现
public
static byte[] rc4(byte[] key, byte[] data) { int[] s = new int[256]; for(int i=0;i<256;i++) s[i] = i; for(int i=0,j=0;i<256;i++) { j = (j + s[i] + (key[i%key.length] & 0xff)) % 256; int tmp = s[i]; s[i] = s[j]; s[j] = tmp; } int i = 0; int j = 0; int x = 0; int y = 0; int data_len = data.length; byte[] results = new byte[data_len]; for (y = 0; y< data_len; y++) { i = (i + 1) % 256; j = (j + s[i]) % 256; //swap x = s[i]; s[i] = s[j]; s[j] = x; results[y] = (byte) (data[y] ^ (s[(s[i] + s[j]) % 256])); } return results; }

 

posted @ 2020-11-20 16:35  fly不起来啊!  阅读(252)  评论(0编辑  收藏  举报