Skip to content

Instantly share code, notes, and snippets.

@kballenegger
Created January 31, 2011 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kballenegger/803568 to your computer and use it in GitHub Desktop.
Save kballenegger/803568 to your computer and use it in GitHub Desktop.
A toy cypher written in PHP. (I have no idea why I wrote this...)
<?php
function xor_cipher($data, $key) {
$data = bitify($data);
$key = bitify($key);
$cipher = array();
$k_i = 0;
for($d_i=0; $d_i<count($data); $d_i++) {
$d = $data[$d_i];
$k = $key[$k_i];
$c = $d ^ $k;
$cipher[] = $c;
$k_i<(count($key)-1)?$k_i++:$k_i=0;
}
return unbitify($cipher);
}
function bitify($data) {
$final = array();
for($i = 0; $i < strlen($data); $i++) {
$char = $data[$i];
$ord = ord($char);
$byte = sprintf('%08b', $ord);
for($j = 0; $j < 8; $j++) {
$bit = $byte[$j];
$final[] = intval($bit);
}
}
return $final;
}
function unbitify($data) {
$final = '';
for($i = 0; $i < count($data); $i+=8) {
$byte = implode(array($data[$i], $data[$i+1], $data[$i+2], $data[$i+3], $data[$i+4], $data[$i+5], $data[$i+6], $data[$i+7]));
$ord = bindec($byte);
$char = chr($ord);
$final .= $char;
}
return $final;
}
function swizz_cipher($data, $key) {
$data = bitify($data);
$key = bitify($key);
$cipher = array();
$k_i = 0;
for($d_i=0; $d_i<count($data); $d_i++) {
$d = $data[$d_i];
$k = $key[$k_i];
$p = $d_i>0?$cipher[$d_i-1]:0;
$t = $k ^ $p;
$c = $d ^ $t;
$cipher[] = $c;
$k_i<(count($key)-1)?$k_i++:$k_i=0;
}
return unbitify($cipher);
}
function swizz_decipher($cipher, $key) {
$cipher = bitify($cipher);
$key = bitify($key);
$f_key = array();
$k_i = 0;
foreach($cipher as $bit) {
$f_key[] = $key[$k_i];
$k_i<(count($key)-1)?$k_i++:$k_i=0;
}
$r_cipher = array_reverse($cipher);
$r_key = array_reverse($f_key);
$data = array();
$k_i = 0;
for($d_i=0; $d_i<count($r_cipher); $d_i++) {
$t = $d_i<(count($r_cipher)-1)?$r_cipher[$d_i+1]:0;
$c = $r_cipher[$d_i];
$k = $r_key[$d_i];
$p = $t ^ $k;
$d = $p ^ $c;
$data[] = $d;
}
$r_data = array_reverse($data);
return unbitify($r_data);
}
$data = "Hello, world!";
$key = "ola";
$cipher = swizz_cipher($data, $key);
$decipher = swizz_decipher($cipher, $key);
var_dump($decipher);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment