javascript translation, encode in php decode in javascript - php
Hi I'm trying to encode a string in PHP then output in javascript because otherwise Javascript gives me error.
I tried this http://pastebin.com/7RmjDcJY:
<?php
echo "<script type=\"text/javascript\">
function lang(translate){
var translations = new Array();";
foreach($languageTranslations AS $key=>$value):
echo "translations[\"".$key."\"] = \"". base64_encode($value)."\";";
endforeach;
echo "return (typeof translations[translate]!='undefined') ? $.base64.decode(translations[translate]) : translate;
}
</script>";?>
But förnamn -> Förnamn
Any idea? I've utf-8 in my document, but I guess bas64 can't convert utf-8 properly?
I can't just output the value, because some contains characters that breaks my javascript.
Or should I do a replace first? Like replace " with \" and stuff?
EDIT:
Now I got:
//urlencode in PHP and:
decodeURIComponent(translations[translate]).replace('+',' ')
But that doesn't feel like the right thing. What if I had an + sign in my text?
for send data from php to JavaScript you can base64 data and if you have more than one data to send use json_encode for send multi data,then in javaScript use json decode for get value and decode base64 by this code
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
sample:
alert(Base64._utf8_decode(2LTYs9uM2YTYqNi02LPbjNio2YLYq9in24zYqNmE2LDYs9uM2KjYsQ==));
this code compatible with utf-8
Related
Convert VB6 code to PHP
I want to convert Visual Basic 6 Code to PHP Code. I am new to PHP please help me to convert my VB6 Code to PHP. So far I tried to convert this into php code when I tried the code there is an error in the " CryptRC4 = CryptRC4 & Chr$((pvCryptXor(baS((CLng(baS(li)) + baS(lJ)) Mod 256), Asc(Mid$(sText, lIdx, 1))))); part and also I don't know how to proceed to the sub functions. Please see the codes below. The vb code is used to encrypt strings. I want to convert it to php format. PHP Code <?php function CryptRC4($sText,$sKey){ $baS = array(0,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,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79, 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95, 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111, 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255); $baK = array(0,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,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79, 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95, 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111, 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255); $bytSwap = 0; $li = 0; $lJ = 0; $lIdx = 0; for( $lIdx = 0; $lIdx < 256; $lIdx++){ $baS[$lIdx] = $lIdx; $baK[$lIdx] = ord(substr($sKey, 1 + ($lIdx % strlen($sKey)), 1)); } for($li = 0; $li < 256; $li++){ $lJ = ($baS[$li] + $baK[$li]) % 256; $bytSwap = $baS[$li]; $baS[$li] = $baS[$lJ]; $baS[$lJ] = $bytSwap; } $li = 0; $lJ = 0; $data_str = ""; for($lIdx = 0; $lIdx < strlen($sText); $lIdx++){ $li = ($li + 1) % 256; $lJ = ($lJ + $baS[$li]) % 256; $bytSwap = $baS[$li]; $baS[$li] = $baS[$lJ]; $baS[$lJ] = $bytSwap; #echo chr((pvCryptXor($baS[(round(($baS[$li]) + $baS[$lJ])) % 256], ord(substr($sText, $lIdx, 1))))); $data_str .= chr((pvCryptXor($baS[(round(($baS[$li]) + $baS[$lJ])) % 256], ord(substr($sText, $lIdx, 1))))); } echo $data_str; } function pvCryptXor($li, $lJ){ if($li = $lJ){ $pcx = $lJ; } else { $pcx = $li Xor $lJ; } return $pcx; } unction ToHexDump($sText) { $lIdx; for($lIdx = 1; $lIdx < strlen($sText); $lIdx++){ $thd .= Right$("0" & Hex(Asc(Mid(sText, lIdx, 1))), 2) echo $thd; } return $thd; } FromHexDump("events"); function FromHexDump($sText) { $fhd = ""; for($lIdx = 0; $lIdx < strlen($sText); $lIdx++){ $fhd .= chr(CLng("&H" & Mid(sText, lIdx, 2))); } return $fhd; } ?> VB Code: Public Function CryptRC4(sText As String, sKey As String) As String On Error Resume Next Dim baS(0 To 255) As Byte Dim baK(0 To 255) As Byte Dim bytSwap As Byte Dim li As Long Dim lJ As Long Dim lIdx As Long For lIdx = 0 To 255 baS(lIdx) = lIdx baK(lIdx) = Asc(Mid$(sKey, 1 + (lIdx Mod Len(sKey)), 1)) Next For li = 0 To 255 lJ = (lJ + baS(li) + baK(li)) Mod 256 bytSwap = baS(li) baS(li) = baS(lJ) baS(lJ) = bytSwap Next li = 0 lJ = 0 For lIdx = 1 To Len(sText) li = (li + 1) Mod 256 lJ = (lJ + baS(li)) Mod 256 bytSwap = baS(li) baS(li) = baS(lJ) baS(lJ) = bytSwap CryptRC4 = CryptRC4 & Chr$((pvCryptXor(baS((CLng(baS(li)) + baS(lJ)) Mod 256), Asc(Mid$(sText, lIdx, 1))))) Next End Function Private Function pvCryptXor(ByVal li As Long, ByVal lJ As Long) As Long On Error Resume Next If li = lJ Then pvCryptXor = lJ Else pvCryptXor = li Xor lJ End If End Function Public Function ToHexDump(sText As String) As String On Error Resume Next Dim lIdx As Long For lIdx = 1 To Len(sText) ToHexDump = ToHexDump & Right$("0" & Hex(Asc(Mid(sText, lIdx, 1))), 2) Next End Function Public Function FromHexDump(sText As String) As String On Error Resume Next Dim lIdx As Long For lIdx = 1 To Len(sText) Step 2 FromHexDump = FromHexDump & Chr$(CLng("&H" & Mid(sText, lIdx, 2))) Next End Function
I revised your updated code and it seems you only had a few minor errors in it, look and my changes: I guess you can use the build in PHP function hex2bin and bin2hex instead fo you own hex conversion. function CryptRC4($sText,$sKey){ $baS = range(0, 255); // you can use range instead of your manual arrays $baK = range(0, 255); $bytSwap = 0; $li = 0; $lJ = 0; $lIdx = 0; for( $lIdx = 0; $lIdx < 256; $lIdx++){ $baS[$lIdx] = $lIdx; $baK[$lIdx] = ord(substr($sKey, 1 + ($lIdx % strlen($sKey)), 1)); } for($li = 0; $li < 256; $li++){ $lJ = ($baS[$li] + $baK[$li]) % 256; $bytSwap = $baS[$li]; $baS[$li] = $baS[$lJ]; $baS[$lJ] = $bytSwap; } $li = 0; $lJ = 0; $data_str = ""; for($lIdx = 0; $lIdx < strlen($sText); $lIdx++){ $li = ($li + 1) % 256; $lJ = ($lJ + $baS[$li]) % 256; $bytSwap = $baS[$li]; $baS[$li] = $baS[$lJ]; $baS[$lJ] = $bytSwap; #echo chr((pvCryptXor($baS[(round(($baS[$li]) + $baS[$lJ])) % 256], ord(substr($sText, $lIdx, 1))))); $data_str .= chr((pvCryptXor($baS[(round(($baS[$li]) + $baS[$lJ])) % 256], ord(substr($sText, $lIdx, 1))))); } return $data_str; // changed from echo to return } function pvCryptXor($li, $lJ){ if($li == $lJ){ // you had an error here, use == to compare instead of a single = $pcx = $lJ; } else { $pcx = $li ^ $lJ; // XOR function in PHP is the ^ operator } return $pcx; } $str_hex = bin2hex("events"); $str_enc = CryptRC4($str_hex,"password"); $str_dec = hex2bin(CryptRC4($str_enc,"password")); echo $str_hex . PHP_EOL . $str_enc . PHP_EOL . $str_dec; OUTPUT: 6576656e7473 '�����~i�� events So it seems to me as it's actually encoding and decoding correctly!?
It seems the original VB6 implementation of CryptRC4 function is from my answer to "VB6 encrypt text using password" question on SO. So let me try answering your Q with this short php implementation of all public functions in the VB6 snippet: function CryptRC4($text, $key) { return openssl_encrypt($text, "RC4-40", $key, 1 | 2); } function ToHexDump($text) { return strtoupper(bin2hex($text)); } function FromHexDump($text) { return hex2bin($text); } You can excercise these one-liners with something like this: $text = "a message here"; $password = "password"; $encr = ToHexDump(CryptRC4($text, $password)); $decr = CryptRC4(FromHexDump($encr), $password); echo $text . PHP_EOL . $encr . PHP_EOL . $decr;
As it's intended for passwords, you can save yourself a lot of hassle. PHP has got built in functions (version 5.5 and newer) that are designed for dealing with the hashing of passwords and for verifying hashed passwords against the password submitted by a user. Have a read through the PHP relevant PHP manual pages http://php.net/manual/en/book.password.php
Converting JavaScript RSA Function into a PHP one
I've got a Problem with converting a JS-based RSA File into PHP. JavaScript: Main File: var RSAPublicKey = function($modulus_hex, $encryptionExponent_hex) { this.modulus = new BigInteger( $modulus_hex, 16); this.encryptionExponent = new BigInteger( $encryptionExponent_hex, 16); } var Base64 = { base64: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function($input) { if (!$input) { return false; } var $output = ""; var $chr1, $chr2, $chr3; var $enc1, $enc2, $enc3, $enc4; var $i = 0; do { $chr1 = $input.charCodeAt($i++); $chr2 = $input.charCodeAt($i++); $chr3 = $input.charCodeAt($i++); $enc1 = $chr1 >> 2; $enc2 = (($chr1 & 3) << 4) | ($chr2 >> 4); $enc3 = (($chr2 & 15) << 2) | ($chr3 >> 6); $enc4 = $chr3 & 63; if (isNaN($chr2)) $enc3 = $enc4 = 64; else if (isNaN($chr3)) $enc4 = 64; $output += this.base64.charAt($enc1) + this.base64.charAt($enc2) + this.base64.charAt($enc3) + this.base64.charAt($enc4); } while ($i < $input.length); return $output; }, decode: function($input) { if(!$input) return false; $input = $input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); var $output = ""; var $enc1, $enc2, $enc3, $enc4; var $i = 0; do { $enc1 = this.base64.indexOf($input.charAt($i++)); $enc2 = this.base64.indexOf($input.charAt($i++)); $enc3 = this.base64.indexOf($input.charAt($i++)); $enc4 = this.base64.indexOf($input.charAt($i++)); $output += String.fromCharCode(($enc1 << 2) | ($enc2 >> 4)); if ($enc3 != 64) $output += String.fromCharCode((($enc2 & 15) << 4) | ($enc3 >> 2)); if ($enc4 != 64) $output += String.fromCharCode((($enc3 & 3) << 6) | $enc4); } while ($i < $input.length); return $output; } }; var Hex = { hex: "0123456789abcdef", encode: function($input) { if(!$input) return false; var $output = ""; var $k; var $i = 0; do { $k = $input.charCodeAt($i++); $output += this.hex.charAt(($k >> 4) &0xf) + this.hex.charAt($k & 0xf); } while ($i < $input.length); return $output; }, decode: function($input) { if(!$input) return false; $input = $input.replace(/[^0-9abcdef]/g, ""); var $output = ""; var $i = 0; do { $output += String.fromCharCode(((this.hex.indexOf($input.charAt($i++)) << 4) & 0xf0) | (this.hex.indexOf($input.charAt($i++)) & 0xf)); } while ($i < $input.length); return $output; } }; var RSA = { getPublicKey: function( $modulus_hex, $exponent_hex ) { return new RSAPublicKey( $modulus_hex, $exponent_hex ); }, encrypt: function($data, $pubkey) { if (!$pubkey) return false; $data = this.pkcs1pad2($data,($pubkey.modulus.bitLength()+7)>>3); if(!$data) return false; $data = $data.modPowInt($pubkey.encryptionExponent, $pubkey.modulus); if(!$data) return false; $data = $data.toString(16); return Base64.encode(Hex.decode($data)); }, pkcs1pad2: function($data, $keysize) { if($keysize < $data.length + 11) return null; var $buffer = []; var $i = $data.length - 1; while($i >= 0 && $keysize > 0) $buffer[--$keysize] = $data.charCodeAt($i--); $buffer[--$keysize] = 0; while($keysize > 2) $buffer[--$keysize] = Math.floor(Math.random()*254) + 1; $buffer[--$keysize] = 2; $buffer[--$keysize] = 0; return new BigInteger($buffer); } } How I use it: var pubKey = RSA.getPublicKey( results.publickey_mod, results.publickey_exp ); var encryptedPassword = RSA.encrypt( form.elements['password'].value, pubKey ); Now I want to convert this into PHP, thing I have tried so far: $pkey = $json["publickey_mod"]; $rsa = new Crypt_RSA(); $rsa->loadKey($pkey); $rsa->exponent = $json["publickey_exp"]; echo ($rsa->setPublicKey($pkey))?"success":"fail"; $plain = "text"; echo $rsa->encrypt($plain); But it always prints a "fail", what's wrong with it? How the Key looks like: CD5D11DFC04D457B864421AA483118EEA3A96C97E01ABFA4BAD356EC3CE6CA7E3F61665BAA1322D1D6C763D4463C1B41D69397281538D22302D8817CC10AEBDA96970DA4BA46BA79808E3B7BC3D38C1C2FD746E73EA5907F07C9588A1AF2C337FED1B7C8BB29304035420FB7EDE92511D1B07A63E21A5C36F132B556EE879113E88395ACCE9B987E478F8EA11B34634BCDA863DE7045EA9D7AB3240F406C572F36FDE1DB1534F92022B91DFBE23F980D0190D69953037EF9F38F98DA1A8028BE009CE82B979E8E427305802330111A78737D8E11C9CB132170CB34618941FA2AC2C754338886BFEE7DAD779036B292F9711DD9C765F37D42B6C0DC0BCCC83765
I know this is a bit old lol but it looks like you're using PKCS#1 padding. phpseclib uses OAEP padding by default. Try doing this: $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
Converting javascript code to PHP charCodeAt() issue
I have a javascript function which I wants in PHP, Here is my JavaScript function: <script type="text/javascript"> str = '242357de5b105346ea2059795682443'; str_overral = str; str_overral = str_overral.replace(/[^a-z0-9]/gi, '').toLowerCase(); str_res=''; for (i=0; i<str_overral.length; i++) { l=str_overral.substr(i,1); d=l.charCodeAt(0); if ( Math.floor(d/2) == d/2 ) { str_res+=l; } else { str_res=l+str_res; } } document.write('<in'); document.write('put type="hidden" name="myInput" value="'+str_res+'" />'); </script> and above JavaScript function generates this string for myInput: 359795ae3515e753242db0462068244 And this I tried with PHP: $str = '242357de5b105346ea2059795682443'; $str_overral = preg_replace('/[^a-z0-9]/i', '',$str); $str_overral = strtolower($str_overral); $str_res=''; for ($i=0; $i<strlen($str_overral); $i++) { $l= substr($str_overral,$i,1); // PHP does not have charCodeAt() function so i used uniord() $d = uniord($l); if((floor($d)/2) == ($d/2)) $str_res.=$l; else $str_res.= $l.$str_res; } echo $str_res; function uniord($c) { $h = ord($c{0}); if ($h <= 0x7F) { return $h; } else if ($h < 0xC2) { return false; } else if ($h <= 0xDF) { return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F); } else if ($h <= 0xEF) { return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F); } else if ($h <= 0xF4) { return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F); } else { return false; } } and above PHP code generates this string: 242357de5b105346ea2059795682443 so basically PHP just return $string as is. As PHP does not have charCodeAt() function I found a solution here UTF-8 Safe Equivelant of ord or charCodeAt() in PHP , But that does not work for me, I even tried solution posted by 'hakre' in same thread. Thank you for any kind of help. UPDATE SOLUTION: Here was fix: if($d%2 == 0) $str_res.=$l; else $str_res = $l.$str_res;
if((floor($d)/2) == ($d/2)) You have a ) in the wrong place. It should be after the first /2, not before it. It could be made more efficient with if($d%2 == 0)
converting c method that uses bitwise to php
I'm trying to convert an APR (apache runtime) method to PHP, but I can't quite figure it out. The method creates a string that is a directory path and file - so example output would be A/B/C/[a-fA-F0-9_#]. It's using bitwise operations on a binary string returned from md5($string,true); When I run the php below, I get: array ( 0 => 'A', 1 => '/', 2 => 'A', 3 => '/', 4 => 'A', 5 => '/', 6 => 'AAAAAAAAAAAAAAAAAAA', ) What am I doing wrong? Is this not possible due to how PHP internally represents char arrays? Here is the c method: static void cache_hash(const char *it, char *val, int ndepth, int nlength) { apr_md5_ctx_t context; unsigned char digest[16]; char tmp[22]; int i, k, d; unsigned int x; static const char enc_table[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_#"; apr_md5_init(&context); apr_md5_update(&context, (const unsigned char *) it, strlen(it)); apr_md5_final(digest, &context); /* encode 128 bits as 22 characters, using a modified uuencoding * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters */ for (i = 0, k = 0; i < 15; i += 3) { x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2]; tmp[k++] = enc_table[x >> 18]; tmp[k++] = enc_table[(x >> 12) & 0x3f]; tmp[k++] = enc_table[(x >> 6) & 0x3f]; tmp[k++] = enc_table[x & 0x3f]; } /* one byte left */ x = digest[15]; tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */ tmp[k++] = enc_table[(x << 4) & 0x3f]; /* now split into directory levels */ for (i = k = d = 0; d < ndepth; ++d) { memcpy(&val[i], &tmp[k], nlength); k += nlength; val[i + nlength] = '/'; i += nlength + 1; } memcpy(&val[i], &tmp[k], 22 - k); val[i + 22 - k] = '\0'; } Here is my attempt at converting to PHP: $URL = 'thumbnail.php?u=http%3A%2F%2Fwww.google.com%2Flogos%2Fclassicplus.png&w=200'; cache_hash($URL, $theFile); function cache_hash($URL, &$theFile, $dirlevels = 3, $dirlength = 1) { $enc_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_#"; $md5URL = md5($URL,true); // echo "MD5URL: ".var_export($md5URL,true); //$md5URL = digest $tmp = '0000000000000000000000'; //22 chars for ($i = 0; $i < 22; $i++) { $tmp[$i] = 0x0; } var_export(unpack('S',$md5URL)); p(ord($md5URL[0])); p(ord($md5URL[1])); /* encode 128 bits as 22 characters, using a modified uuencoding * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters */ for ($i = 0, $k = 0; $i < 15; $i += 3) { // p($md5URL[$i] << 16); // p($md5URL[$i + 1] << 8); // p($md5URL[$i + 2]); $x = ($md5URL[$i] << 16) | ($md5URL[$i + 1] << 8) | $md5URL[$i + 2]; // p($x); p($x >> 18); $tmp[$k++] = $enc_table[$x >> 18]; $tmp[$k++] = $enc_table[($x >> 12) & 0x3f]; $tmp[$k++] = $enc_table[($x >> 6) & 0x3f]; $tmp[$k++] = $enc_table[$x & 0x3f]; } /* one byte left */ $x = $md5URL[15]; $tmp[$k++] = $enc_table[$x >> 2]; /* use up 6 bits */ $tmp[$k++] = $enc_table[($x << 4) & 0x3f]; /* now split into directory levels */ for ($i = $k = $d = 0; $d < $dirlevels; ++$d) { var_export($tmp); $theFile[$i] = substr($tmp,$k,$dirlength); $k += $dirlength; $theFile[$i + $dirlength] = '/'; $i += $dirlength + 1; } $theFile[$i] = substr($tmp,$k,22 - $k); var_export($theFile); } function p($val) { echo " Dec:\n"; printf(' val= %d', ord($val)); echo "\nBinary:\n"; printf(' val= %b', ord($val)); echo "\n"; }
change the two lines, it should work I believe $x = (ord($md5URL[$i]) << 16) | (ord($md5URL[$i + 1]) << 8) | ord($md5URL[$i + 2]); $x = ord($md5URL[15]); I think you have to change this line too: $md5URL = md5($URL, false);
Converting a hexadecimal string into binary in Objective-C
What's an equivalent of the PHP function pack: pack('H*', '01234567989abcdef' ); in Objective-C?
Assuming that you want the results as an NSData, you can use a function similar to this: NSData *CreateDataWithHexString(NSString *inputString) { NSUInteger inLength = [inputString length]; unichar *inCharacters = alloca(sizeof(unichar) * inLength); [inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)]; UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1)); NSInteger i, o = 0; UInt8 outByte = 0; for (i = 0; i < inLength; i++) { UInt8 c = inCharacters[i]; SInt8 value = -1; if (c >= '0' && c <= '9') value = (c - '0'); else if (c >= 'A' && c <= 'F') value = 10 + (c - 'A'); else if (c >= 'a' && c <= 'f') value = 10 + (c - 'a'); if (value >= 0) { if (i % 2 == 1) { outBytes[o++] = (outByte << 4) | value; outByte = 0; } else if (i == (inLength - 1)) { outBytes[o++] = value << 4; } else { outByte = value; } } else { if (o != 0) break; } } return [[NSData alloc] initWithBytesNoCopy:outBytes length:o freeWhenDone:YES]; }
See the -scanHex... methods of NSScanner.