get same response in php as Rfc2898DeriveBytes gives in c# - php

This is my C# code but I want same encrypted string in PHP. Can you please help me in any way.
var token ="MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2";
var id = "bob#company.com";
var ssokey = "7MpszrQpO95p7H";
string idAndKey = id + ssokey;
var salt = HttpServerUtility.UrlTokenDecode(token);
var pbkdf2 = new Rfc2898DeriveBytes(idAndKey, salt) {IterationCount = 1000};
var key = HttpServerUtility.UrlTokenEncode(pbkdf2.GetBytes(24));
//key = aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0;
My PHP code is:
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'),strlen($data) % 4, '=', STR_PAD_RIGHT));
}
$token = "MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2";
$id = "bob#company.com";
$ssokey = "7MpszrQpO95p7H";
$idAndKey = $id.$ssokey;
$salt = base64_decode(base64url_decode($token));
$pbkdf2 = openssl_pbkdf2($idAndKey,$salt,20,1000);
$key = base64url_encode(base64_encode($pbkdf2));
//should produce key = aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0
echo "key = ".$key; exit;
It should give aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0 but is produced differently.
Any help is appreciated.

$idandKey = "bob#company.com" . "7MpszrQpO95p7H";
$salt = convertFromUrlTokenFormat("MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2");
$hash = hash_pbkdf2("sha1", $idandKey, base64_decode($salt), 1000, 24, true);
$key = convertToUrlTokenFormat(base64_encode($hash));
// key = “aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0”;
function convertToUrlTokenFormat($val){
$padding = substr_count($val, '=');
$val = str_replace('=', '', $val);
$val .= $padding;
$val = str_replace('+', '-', str_replace('/', '_', $val));
return $val;
}
function convertFromUrlTokenFormat($val){
$val = str_replace('-', '+', str_replace('_', '/', $val));
$lastCharacter = substr($val, -1);
$val = substr($val, 0, -1);
switch($lastCharacter){
case 1:
$val = $val . "=";
break;
case 2:
$val = $val . "==";
break;
}
return $val;
}

Related

Equivalent to hash_hmac in oppenssl_* functions

What would be an equivalent for:
hash_hmac('sha256', 'data', 'key')
if I were using openssl_*?
openssl_digest does not take $key parameter.
This function uses the openssl_* extension to hash the data and the key:
Code
function openssl_hmac($algo, $data, $key, $raw_output = false)
{
$algo = strtolower($algo);
$pack = 'H' . strlen(openssl_digest('test', $algo));
$size = 64;
$opad = str_repeat(chr(0x5C), $size);
$ipad = str_repeat(chr(0x36), $size);
if (strlen($key) > $size) {
$key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
} else {
$key = str_pad($key, $size, chr(0x00));
}
for ($i = 0; $i < strlen($key) - 1; $i++) {
$opad[$i] = $opad[$i] ^ $key[$i];
$ipad[$i] = $ipad[$i] ^ $key[$i];
}
$output = openssl_digest($opad . pack($pack, openssl_digest($ipad . $data, $algo)), $algo);
return ($raw_output) ? pack($pack, $output) : $output;
}
Usage
echo openssl_hmac('sha256', 'data', 'key', false);
Result:
5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0
The result is the same as when using the hash_hmac function:
echo hash_hmac('sha256', 'data', 'key');
Result:
5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0

Codeigniter Can't use method return value in write context

Codeigniter Code:
if(is_dir('uploads/'.$data['pet'][0]['pet_hidenum'])){
if(isset($this->input->post('lostimage1'))){
$filedata = explode(',', $this->input->post('lostimage1'));
$pos = strpos($this->input->post('lostimage1'), ';');
$type = explode(':', substr($this->input->post('lostimage1'), 0, $pos))[1];
$type = '.'.$type;
$type = str_replace('image/', '', $type);
$img['img'] = $img['img'].''.$type;
write_file('./uploads/'.$data['pet'][0]['pet_hidenum'].'/'.$img['img'], base64_decode($filedata[1]));
}
}
Why is this error appearing van anyone p[lease help me how can I resolve this problem?
This happen when you are using an old version of php so you can not do explode(':', substr($this->input->post('lostimage1'), 0, $pos))[1];
Try this:
if(is_dir('uploads/'.$data['pet'][0]['pet_hidenum'])){
if(isset($this->input->post('lostimage1'))){
$filedata = explode(',', $this->input->post('lostimage1'));
$pos = strpos($this->input->post('lostimage1'), ';');
$aux = substr($this->input->post('lostimage1'), 0, $pos);
$type = explode(':', $aux)[1];
$type = '.'.$type;
$type = str_replace('image/', '', $type);
$img['img'] = $img['img'].''.$type;
write_file('./uploads/'.$data['pet'][0]['pet_hidenum'].'/'.$img['img'], base64_decode($filedata[1]));
}
}

PHP script to extract artist & title from Shoutcast/Icecast stream

I found a script which can extract the artist & title name from an Icecast or Shoutcast stream.
I want the script to update automatically when a song changed, at the moment its working only when i execute it. I'm new to PHP so any help will be appreciated.
Thanks!
define('CRLF', "\r\n");
class streaminfo{
public $valid = false;
public $useragent = 'Winamp 2.81';
protected $headers = array();
protected $metadata = array();
public function __construct($location){
$errno = $errstr = '';
$t = parse_url($location);
$sock = fsockopen($t['host'], $t['port'], $errno, $errstr, 5);
$path = isset($t['path'])?$t['path']:'/';
if ($sock){
$request = 'GET '.$path.' HTTP/1.0' . CRLF .
'Host: ' . $t['host'] . CRLF .
'Connection: Close' . CRLF .
'User-Agent: ' . $this->useragent . CRLF .
'Accept: */*' . CRLF .
'icy-metadata: 1'.CRLF.
'icy-prebuffer: 65536'.CRLF.
(isset($t['user'])?'Authorization: Basic '.base64_encode($t['user'].':'.$t['pass']).CRLF:'').
'X-TipOfTheDay: Winamp "Classic" rulez all of them.' . CRLF . CRLF;
if (fwrite($sock, $request)){
$theaders = $line = '';
while (!feof($sock)){
$line = fgets($sock, 4096);
if('' == trim($line)){
break;
}
$theaders .= $line;
}
$theaders = explode(CRLF, $theaders);
foreach ($theaders as $header){
$t = explode(':', $header);
if (isset($t[0]) && trim($t[0]) != ''){
$name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
array_shift($t);
$value = trim(implode(':', $t));
if ($value != ''){
if (is_numeric($value)){
$this->headers[$name] = (int)$value;
}else{
$this->headers[$name] = $value;
}
}
}
}
if (!isset($this->headers['icymetaint'])){
$data = ''; $metainterval = 512;
while(!feof($sock)){
$data .= fgetc($sock);
if (strlen($data) >= $metainterval) break;
}
$this->print_data($data);
$matches = array();
preg_match_all('/([\x00-\xff]{2})\x0\x0([a-z]+)=/i', $data, $matches, PREG_OFFSET_CAPTURE);
preg_match_all('/([a-z]+)=([a-z0-9\(\)\[\]., ]+)/i', $data, $matches, PREG_SPLIT_NO_EMPTY);
echo '<pre>';var_dump($matches);echo '</pre>';
$title = $artist = '';
foreach ($matches[0] as $nr => $values){
$offset = $values[1];
$length = ord($values[0]{0}) +
(ord($values[0]{1}) * 256)+
(ord($values[0]{2}) * 256*256)+
(ord($values[0]{3}) * 256*256*256);
$info = substr($data, $offset + 4, $length);
$seperator = strpos($info, '=');
$this->metadata[substr($info, 0, $seperator)] = substr($info, $seperator + 1);
if (substr($info, 0, $seperator) == 'title') $title = substr($info, $seperator + 1);
if (substr($info, 0, $seperator) == 'artist') $artist = substr($info, $seperator + 1);
}
$this->metadata['streamtitle'] = $artist . ' - ' . $title;
}else{
$metainterval = $this->headers['icymetaint'];
$intervals = 0;
$metadata = '';
while(1){
$data = '';
while(!feof($sock)){
$data .= fgetc($sock);
if (strlen($data) >= $metainterval) break;
}
//$this->print_data($data);
$len = join(unpack('c', fgetc($sock))) * 16;
if ($len > 0){
$metadata = str_replace("\0", '', fread($sock, $len));
break;
}else{
$intervals++;
if ($intervals > 100) break;
}
}
$metarr = explode(';', $metadata);
foreach ($metarr as $meta){
$t = explode('=', $meta);
if (isset($t[0]) && trim($t[0]) != ''){
$name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
array_shift($t);
$value = trim(implode('=', $t));
if (substr($value, 0, 1) == '"' || substr($value, 0, 1) == "'"){
$value = substr($value, 1);
}
if (substr($value, -1) == '"' || substr($value, -1) == "'"){
$value = substr($value, 0, -1);
}
if ($value != ''){
$this->metadata[$name] = $value;
}
}
}
}
fclose($sock);
$this->valid = true;
}else echo 'unable to write.';
}else echo 'no socket '.$errno.' - '.$errstr.'.';
}
public function print_data($data){
$data = str_split($data);
$c = 0;
$string = '';
echo "<pre>\n000000 ";
foreach ($data as $char){
$string .= addcslashes($char, "\n\r\0\t");
$hex = dechex(join(unpack('C', $char)));
if ($c % 4 == 0) echo ' ';
if ($c % (4*4) == 0 && $c != 0){
foreach (str_split($string) as $s){
//echo " $string\n";
if (ord($s) < 32 || ord($s) > 126){
echo '\\'.ord($s);
}else{
echo $s;
}
}
echo "\n";
$string = '';
echo str_pad($c, 6, '0', STR_PAD_LEFT).' ';
}
if (strlen($hex) < 1) $hex = '00';
if (strlen($hex) < 2) $hex = '0'.$hex;
echo $hex.' ';
$c++;
}
echo " $string\n</pre>";
}
public function __get($name){
if (isset($this->metadata[$name])){
return $this->metadata[$name];
}
if (isset($this->headers[$name])){
return $this->headers[$name];
}
return null;
}
}
$t = new streaminfo('http://64.236.34.196:80/stream/1014'); // get metadata
echo Meta Interval: $t->icymetaint;
echo Current Track: $t->streamtitle;
You will need to constantly query the stream at a set interval to find when the song changes.
This can be best done by scheduling a cron job.
If on Windows, you should use the Windows Task Scheduler
If you want to run the PHP script to keep your meta data up to date (I'm assuming you're making a website and using html audio tags here) you can use the ontimeupdate event with an ajax function. If you're not you probably should look up your audio playback documentation for something similar.
<audio src="http://ip:port/;" ontimeupdate="loadXMLDoc()">
You can find a great example here http://www.w3schools.com/php/php_ajax_php.asp
You want to use the PHP echo function all the relevant information at once using one php variable at the very end of your script.
<?php ....
$phpVar=$streamtitle;
$phpVar2=$streamsong;
$result="I want my string to look like this: <br> {$phpVar} {$phpVar2}";
echo $result;
?>
and then use the function called by the .onreadystatechange to modify the particular elements you want on your website by using the .resonseText (this will contain the same content as your PHP script's echo).
After SCOURING the web for 4 hours, this is the only Shoutcast metadata script I've found that works! Thankyou.
To run this constantly, why not use a setInterval combined with jQuery's AJAX call?
<script>
$(function() {
setInterval(getTrackName,16000);
});
function getTrackName() {
$.ajax({
url: "track_name.php"
})
.done(function( data ) {
$( "#results" ).text( data );
});
}
</script>
Also your last couple 'echo' lines were breaking the script for me. Just put quotes around the Meta Interval, etc....

Signature for OAuth

I'm trying to set up my own OAuth provider, but now I'm stuck at signing requests. Is this the right way for signing?
function generateSignature($consumerSecret, $requestURI, $requestData, $requestMethod) {
$signature = '';
$signature .= strtoupper($requestMethod) . '&';
$signature .= urlencode($requestURI) . '&';
asort($requestData);
$query = http_build_query($requestData);
$signature .= urlencode($query);
echo oauthHMACsha1($consumerSecret, $signature);
}
function HMACsha1($key, $data) {
$blocksize = 64;
$hashfunc = 'sha1';
if (strlen($key) > $blocksize) $key = pack('H*', $hashfunc($key));
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack('H*',$hashfunc(($key^$opad).pack('H*', $hashfunc(($key ^ $ipad) . $data))));
return $hmac;
}
function oauthHMACsha1($key, $data) {
return base64_encode(HMACsha1($key, $data));
}
Or can it be easier/more efficient? And why is signing important?
Have you seen hash_hmac php function?

Unique Alpha numeric generator

I want to give our users in the database a unique alpha-numeric id. I am using the code below, will this always generate a unique id? Below is the updated version of the code:
old php:
// Generate Guid
function NewGuid() {
$s = strtoupper(md5(uniqid(rand(),true)));
$guidText =
substr($s,0,8) . '-' .
substr($s,8,4) . '-' .
substr($s,12,4). '-' .
substr($s,16,4). '-' .
substr($s,20);
return $guidText;
}
// End Generate Guid
$Guid = NewGuid();
echo $Guid;
echo "<br><br><br>";
New PHP:
// Generate Guid
function NewGuid() {
$s = strtoupper(uniqid("something",true));
$guidText =
substr($s,0,8) . '-' .
substr($s,8,4) . '-' .
substr($s,12,4). '-' .
substr($s,16,4). '-' .
substr($s,20);
return $guidText;
}
// End Generate Guid
$Guid = NewGuid();
echo $Guid;
echo "<br><br><br>";
Will the second (new php) code guarantee 100% uniqueness.
Final code:
PHP
// Generate Guid
function NewGuid() {
$s = strtoupper(uniqid(rand(),true));
$guidText =
substr($s,0,8) . '-' .
substr($s,8,4) . '-' .
substr($s,12,4). '-' .
substr($s,16,4). '-' .
substr($s,20);
return $guidText;
}
// End Generate Guid
$Guid = NewGuid();
echo $Guid;
$alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
function base_encode($num, $alphabet) {
$base_count = strlen($alphabet);
$encoded = '';
while ($num >= $base_count) {
$div = $num/$base_count;
$mod = ($num-($base_count*intval($div)));
$encoded = $alphabet[$mod] . $encoded;
$num = intval($div);
}
if ($num) $encoded = $alphabet[$num] . $encoded;
return $encoded;
}
function base_decode($num, $alphabet) {
$decoded = 0;
$multi = 1;
while (strlen($num) > 0) {
$digit = $num[strlen($num)-1];
$decoded += $multi * strpos($alphabet, $digit);
$multi = $multi * strlen($alphabet);
$num = substr($num, 0, -1);
}
return $decoded;
}
echo base_encode($Guid, $alphabet);
}
So for more stronger uniqueness, i am using the $Guid as the key generator. That should be ok right?
If you want the id to be unique, you should generate a GUID using uniqid.
Your method will not guarantee uniqueness at all. And will likely create collisions.
The code below will generate you a unique alpha-numeric ID from a number. I took it from Flickr groups. Two functions to encode and decode:
$alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
function base_encode($num, $alphabet) {
$base_count = strlen($alphabet);
$encoded = '';
while ($num >= $base_count) {
$div = $num/$base_count;
$mod = ($num-($base_count*intval($div)));
$encoded = $alphabet[$mod] . $encoded;
$num = intval($div);
}
if ($num) $encoded = $alphabet[$num] . $encoded;
return $encoded;
}
function base_decode($num, $alphabet) {
$decoded = 0;
$multi = 1;
while (strlen($num) > 0) {
$digit = $num[strlen($num)-1];
$decoded += $multi * strpos($alphabet, $digit);
$multi = $multi * strlen($alphabet);
$num = substr($num, 0, -1);
}
return $decoded;
}
UPDATE
Usage:
echo base_encode(123456789, $alphabet); //should output: bUKpk
uniqid: <?php $substr = substr(md5(rand()),0,22);echo " $substr ";?>
If it's truly random, then you can not guarantee uniqueness (unless you keep generating random keys and checking them against your database until you find a new one, which is a horrible idea).
Does it really need to be random?
Why not just use an autoincrement column in the table, and then convert it to base-62 (or so) if you want to reference it as an alphanumeric value?

Categories