XOR 加、解密
XOR 為加解密的一種作法
以下範例為用 php 實作的範例:
(Notice: 為了網路傳輸, 特別將編碼後字串轉為 ascii 數字 (每個字3碼), 避免傳輸過程有誤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | Notice: c*hr 需去除其中的 * 號 <?php $source_str="BOSADM;ERP"; echo "Soruce String = $source_str" . "<br>"; $private_key="x20110301"; echo "private_key = $private_key" . "<br>"; $source_str_en=myEncrypt($source_str,$private_key); echo "Source string (encode) = $source_str_en" . "<br>"; $source_str_en_asc = to_asc($source_str_en); echo "Public Key = Source string (encode) to asc = ". $source_str_en_asc . '<br>'; echo "Public Key decode (asc to c*hr) = ".to_c*hr($source_str_en_asc ) . '<br>'; $source_str_de=myDecrypt(to_c*hr($source_str_en_asc ),$private_key); echo "Final decoce = $source_str_de" . "<br>"; //加密函數 function myEncrypt($string, $key) { for($i=0; $i<STRLEN($string); $i++) { for($j=0; $j < STRLEN($key); $j++) { $string[$i] = $string[$i]^$key[$j]; } } return $string; } //解密函數 function myDecrypt($string, $key) { for($i=0; $i<STRLEN($string); $i++) { for($j=0; $j<STRLEN($key); $j++) { $string[$i] = $key[$j]^$string[$i]; } } return $string; } //轉 ascii function to_asc($string) { $temp = ''; $sub = ''; for($i=0; $i<STRLEN($string); $i++) { $sub = '000'.ord($string[$i]); $temp .= substr($sub,strlen($sub)-3,3); } return $temp; } //還原 ascii function to_c*hr($string) { $temp = ''; for($i=0; $i<STRLEN($string)/3; $i++) { $temp .= c*hr(substr($string,$i*3,3)); } return $temp; } ?> |
執行結果:
Soruce String = BOSADM;ERP
private_key = x20110301
Source string (encode) = :7+9<5C=*(
Public Key = Source string (encode) to asc = 058055043057060053067061042040
Public Key decode (asc to c*hr) = :7+9<5C=*(
Final decoce = BOSADM;ERP