I'm trying to create a php version of this actionscript code because I need to encrypt and decrypt data between flash and php. I got almost halfway through it, but the part about creating 6 bit numbers from 8 bit binary confused me a bit.
Code:
//original Actionscript
String.prototype.sixBitEncode = function () {
var ntexto = "";
var nntexto = "";
var codeKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
var charCode, charCodeBin, charChar;
for (i=0; i< this.length; i++) {
charCode = this.charCodeAt(i) & 255; // char code
charCodeBin = ("00000000" + charCode.toString(2)).substr(-8,8); // char code in binary
ntexto += charCodeBin;
}
for (i=0; i< ntexto.length; i+=6) {
charCodeBin = ntexto.substr(i, 6); // char code in binary, 6 bits
if (charCodeBin.length < 6) charCodeBin = (charCodeBin+"000000").substr(0,6);
charCode = parseInt(charCodeBin, 2);
nntexto += codeKey.substr(charCode, 1);
}
return (nntexto);
}
String.prototype.sixBitDecode = function () {
var ntexto = "";
var nntexto = "";
var codeKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
var charCode, charCodeBin;
for (i=0; i<this.length; i++) {
charCode = codeKey.indexOf(this.substr(i,1)); // char index
charCodeBin = ("000000" + charCode.toString(2)).substr(-6,6); // char index in binary, 6 bits
ntexto += charCodeBin;
}
for (i=0; i< ntexto.length; i+=8) {
charCodeBin = ntexto.substr(i, 8); // char code in binary
charCode = parseInt(charCodeBin, 2);
charChar = String.fromCharCode(charCode);
nntexto += charChar;
}
return (nntexto);
}
PHP:
//my php conversion
function sixBitEncode($msg)
{
$ntexto = '';
$nntexto = '';
$codeKey = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
$charCode;
$charCodeBin;
$charChar;
for ($i=0; $i < strlen($msg); $i++)
{
//Break string into string char codes:
//70 114 233 115 104 105
$charCode = substr($string, $i, 1);
$charCode = ord($charCode);
//Transform this into 8-bit binary numbers:
//01000110 01110010 11101001 01110011 01101000 01101001
$charCodeBin = decbin($charCode);
//Concatenate the values:
//010001100111001011101001011100110110100001101001
$ntexto += $charCodeBin;
}
for ($i=0; $i < strlen(ntexto); $i+=6)
{
//Break it into groups of 6 bits, completing with zeros if needed:
//010001 100111 001011 101001 011100 110110 100001 101001
$charCodeBin = $ntexto.substr($i, 6); // char code in binary, 6 bits
if ($charCodeBin.length < 6) $charCodeBin = ($charCodeBin+"000000").substr(0,6);
//Create new char codes from it:
//17 39 11 41 28 54 33 41
//ord()
$charCode = parseInt($charCodeBin, 2);
//Re-encode it using a defined, internal table, and output it:
//RnLpc2hp
$nntexto += $codeKey.substr($charCode, 1);
}
return ($nntexto);
}
Last edited: