How to decode string using unkown algorithm? - http

I use Fiddler capture http request, but meet mojibake in http body.
mojibake http request img
I copy the http body as bas64 encode and try to know what it is.
There is the base64 encode string:
H4sIAAAAAAAAAIVUz2/cRBR2ckAcEFeuZYSE1O5aM+MZz9gHqONdixyaA0XNoa2qWXucjOK1t/6R7DYbqULcuNBKgLhFIQiQUoEQNy4lFw45cF9x459A4sLzbrNJowKWZc37Md/3/M1788XMettxPEcPBsqNB1JIJiRPJeNM0kQOUpzyeGZdIyTi2OlxFlEacRawXkR6nrfGRcQ8yp2vfo6Loa3ypCxMYleTqtbDxvzIbGbTrmO7NrGxoN4R8X63rJU7v9SH7/0ULLJvfNS7cYfY1BYMiAIZ9J2eE4UsXIt6QUix47q8x4UXMIrX+qfz/eyv1z5YLv6w3vphYLYqNayafMvfKMabwPP0zHrxLBdfj6V7Iii+TqjE1ynHR+HGSbhtcnXtVjEwmT56tP36s/Oy5rVbx5vr0frpN8zFGC++h4fWzPqYTqkQEgtGOQG1PG8ahUFAWJ/1HS4gDU8dTqlkGASVgrtk2u4WlFMiMGGUTqUnwSMJJpec/3sY07zJsmlejGer797dR3FTljqvkQ9rkyAfRaEfBD5hfh9ex+cCdVCmd3WG/C7nHVSNtIY8gnEHbZsk0TnyU5VVuoNyXe8V5c46hCGYq6EGvHto05Q6uX17vXcPAVayHY+Qv4+SvCIA40rJPU47aKiqndYWQlACPBCnc5xMq0r3mlLVpgAu6bKWutLlri6Rz0AlTAQAbO1dtgyQUJe41PEkPmjh43/5uZcz7wN0rPJcDTJ9IQomvsR+TH2M569zRZS6gtKZcBn1HI9jj3VQWuqHAMwIXUqxFAK1NGpXmWxBU5cNyFdPRm3WnkkNwMdFnpqtpmzFhjJGpSlKU0/+S9rL+rcMAJHruG4RWoaDzv45R6yzrMlUiV5KenGMVwo7uD+zfrt7sRXmtNZ5DE1jD2Fk47hooH+WRf35+DFqmfS4LhWcMJo3PcTnDjhSFN4Kw3ObtfZG2xamGmVqsrEAudLqaClOZYbnW10wr4z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KenGMVwo7uD+zfrt7sRXmtNZ5DE1jD2Fk47hooH+WRf35+DFqmfS4LhWcMJo3PcTnDjhSFN4Kw3ObtfZG2xamGmVqsrEAudLqaClOZYbnW10wr4zIRRWvmg1Q3bKePF39cma9o2IpU+k5XXeARZelmHYVTWlXJ2nsAJJ2vbi9IDZ//fvNh6vWZ08+f/bgQT22q2THrnSeHK7Mo6dvvH/yyVFdfK9ylU1qE1fHcZHos5tmcWN8m6lWq8nZzQ+fzx3HlXkE4U+/m1srz/8Br1K6vkAFAAA=";
$str = base64_decode($b64Encode);
$str = gzdecode($str);
var_dump($str);
file_put_contents('d:/123.txt', $str);
$enclist = array(
'UTF-8', 'ASCII',
'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', 'ISO-8859-5',
'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9', 'ISO-8859-10',
'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
'Windows-1251', 'Windows-1252', 'Windows-1254', 'GBK', 'GB2312',
);
var_dump(mb_detect_encoding($str, $enclist));
$str2 = iconv("ISO-8859-1", "UTF-8", $str);
var_dump($str2);
php result img
It is already mojibake. How to decode it?

Related

Sending multipart text and html email in Fat Free Framework

Currently I'm using the following code to send my e-mails in Fat Free Framework:
$smtp = new SMTP ( $f3->get('MAILHOST'), $f3->get('MAILPORT'), $f3->get('MAILPROTOCOL'), $f3->get('MAILUSER'), $f3->get('MAILPW') );
$smtp->set('Content-type', 'text/html; charset=UTF-8');
$smtp->set('Errors-to', '<$my_mail_address>');
$smtp->set('To', "<$my_mail_address>");
$smtp->set('From', '"$my_mailer_name" <$my_mail_address>');
$smtp->set('Subject', "$subject");
$smtp->set('Date', date("r"));
$smtp->set('Message-Id',generateMessageID());
$smtp->send(Template::instance()->render('emails/'.$mailTemplate.'.html'));
And it works like a charm. But I would like to add a text version to this e-mail.
Is there a way to do this within the Fat Free Framework smtp plugin?
If so, how should I do this?
And if not, how else should I do this in F3?
Actually it can send a multiplart text + html mail. The SMTP class is just a protocol implementation, so it might feel a little bit bare-bone at this point. You basically need to prepare your mail body with the multipart like this:
$text = 'Hello world.';
$html = 'Hello <b>world</b>';
$smtp = new \SMTP();
$hash=uniqid(NULL,TRUE);
$smtp->set('From', 'info#domain.com');
$smtp->set('To', 'info#domain.com');
$smtp->set('Content-Type', 'multipart/alternative; boundary="'.$hash.'"');
$smtp->set('Subject', 'Multipart test');
$eol="\r\n";
$body = '--'.$hash.$eol;
$body .= 'Content-Type: text/plain; charset=UTF-8'.$eol;
$body .= $text.$eol.$eol;
$body .= '--'.$hash.$eol;
$body .= 'Content-Type: text/html; charset=UTF-8'.$eol.$eol;
$body .= $html.$eol;
$smtp->send($body,true);

HTTPful attach file and json-body in one request

I need to upload files via Rest and also send some configuration with it.
Here is my example code:
$this->login();
$files = array('file'=>'aTest1.jpg');
$data =
array(
'name'=>'first file',
'description'=>'first file description',
'author'=>'test user'
);
$response = Request::post($this->getRoute('test'))
->addHeader('Authorization', "Bearer " . $this->getToken())
->attach($files)
->body(json_encode($data))
->sendsJson()
->send();
I am able to send the file or able to send the body. But it is not working if I try with both...
Any Hint for me?
Regards
n00n
For those coming to this page via Google. Here's an approach that worked for me.
Don't use attach() and body() together. I found that one will clear out the other. Instead, just use the body() method. Use file_get_contents() to get binary data for your file, then base64_encode() that data and place it into the $data as a parameter.
It should work with JSON. The approach worked for me with application/x-www-form-urlencoded mime type, using $req->body(http_build_query($data));.
$this->login();
$filepath = 'aTest1.jpg';
$data =
array(
'name'=>'first file',
'description'=>'first file description',
'author'=>'test user'
);
$req = Request::post($this->getRoute('test'))
->addHeader('Authorization', "Bearer " . $this->getToken());
if (!empty($filepath) && file_exists($filepath)) {
$filedata = file_get_contents($filepath);
$data['file'] = base64_encode($filedata);
}
$response = $req
->body(json_encode($data))
->sendsJson();
->send();
the body() method erases payload content, so after calling attach(), you must fill payload yourself :
$request = Request::post($this->getRoute('test'))
->addHeader('Authorization', "Bearer " . $this->getToken())
->attach($files);
foreach ($parameters as $key => $value) {
$request->payload[$key] = $value;
}
$response = $request
->sendsJson();
->send();

Receive Bearer Token from API with R

I'm searching for a solution to receive a Bearer token from an API using username and password.
Right now I'm reading the token through Chrome and extract my data, which is less then ideal of course.
I tried with httr and curl to optain through R and receive the Bearer token, but i think i am quite lost.
I think it should be quite simple, from the login information i gathered the mask from the login as
{"username":"name","password":"pw"}, shouldn't this just work with the POST command and the right headers?
POST(url="api_login",config=add_headers(c("username: name"
,"password: pw")))
Doesn't work at all. I can provide the example for php which looks like this:
<?php
// Include Request and Response classes
$url = 'url';
$params = array(
'username' => 'sample_username',
'password' => 'sample_password'
);
// Create a new Request object
$request = new Request($url, 'POST', $params);
// Send the request
$request->send();
// Get the Response object
$response = $request->getResponse();
if($response->getStatusCode() == 200) {
print_r($response->getBodyDecoded());
}
else {
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody() . PHP_EOL;
}
?>
As I'm not very familiar with php i would be very pleased for any help or a guide into the right direction. I searched hours
for API access through R but everything looks very specific to a special login.
I figured out this API uses a deprecated version of Swagger, if this is any useful information.
Thats what I'm doing atm, login with the website and read the token out of my browser. I want to login from inside R, sorry if I wasn't clear.
I updated my code now to:
opts=curlOptions(verbose=TRUE,
ssl.verifypeer = T)
postForm(url,
"username:" = uname, "password:"=pswd,
httpheader = c('Content-Type' = 'application/json', Accept = 'application/json'),
.opts=opts,
style='POST'
)
Which results in an error: SSL certificate problem: self signed certificate in certificate chain.
I tried a lot of different certificates with 'cainfo' inside the argument but can't make it work.

Create a plain HTTP PUT multipart request with a jpg attached

I'm creating a HTTP PUT request manualy. I have the following format
POST http://server.com/id/55/push HTTP/1.0
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: 168
--AaB03x
Content-Disposition: form-data; name="image"; filename="small.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
<file content>
--AaB03x--
My question is, how should I fill the "file content" area? If I open a jpeg with TexMate or with cat command line application and I paste the ASCII output, the request does not work.
UPDATE
I'm working with a microprocessor and I can't use C or a high level language I need to manually do the raw request. Do I need to separate with spaces every binary byte read from the file?
In case of saving the jpg into a file in the server side, Do I have to convert the binary stream to ASCII?
I read the binary code of a JPG from my hard drive with a simple php conde:
$filename = "pic.jpg";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, filesize($filename));
fclose($handle);
//echo $contents;
for($i = 0; $i < $fsize; $i++)
{
// get the current ASCII character representation of the current byte
$asciiCharacter = $contents[$i];
// get the base 10 value of the current characer
$base10value = ord($asciiCharacter);
// now convert that byte from base 10 to base 2 (i.e 01001010...)
$base2representation = base_convert($base10value, 10, 2);
// print the 0s and 1s
echo($base2representation);
}
whit this code I get a stream of 1 and 0. I can send it including the string of 101010101... to where the tag "file content" of my manually http request is but in the server side I can't visualise the JPG... ¿should I convert it to ASCII again?
SOLUTION
Okay the solution was very simple, I just dumped the ASCII code into the tag "file content" of the http request. Despite I'm using a micro controller I opened a socket with PHP and tested out. The solution was to read the ASCII from the file instead of paste directly the ASCII into the code.
Here a working example of the solution:
<?php
//We read the file from the hard drive
$filename = "pic.jpg";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, filesize($filename));
fclose($handle);
$mesage = $contents;
//A trick to calculate the length of the HTTP body
$len = strlen('--AaB03x
Content-Disposition: form-data; name="image"; filename="small.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
'.$mesage.'
--AaB03x--');
//We create the HTTP request
$out = "POST /temp/test.php HTTP/1.0\r\n";
$out .= "Content-type: multipart/form-data boundary=AaB03x\r\n";
$out .= "Content-Length: $len\r\n\r\n";
$out .= "--AaB03x\r\n";
$out .= "Content-Disposition: form-data; name=\"image\"; filename=\"small.jpg\"\r\n";
$out .= "Content-Type: image/jpeg\r\n";
$out .= "Content-Transfer-Encoding: binary\r\n\r\n";
$out .= "$mesage\r\n";
$out .= "--AaB03x--\r\n\r\n";
//Open the socket
$fp = fsockopen("127.0.0.1", 8888, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
//we send the message thought the opened socket
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
//Visualize the query sent
echo nl2br($out);
?>
In the real implementation I will simple read directly from the memory of the microcontroler just as I did in the php
You are mistyping the last boundary, it should have been:
--AaB03x--
You need to have an OutputStream of your outcoming connection and use this Stream to write ALL BYTES that you have read from the file.
If you used C#. You can check this: Sending Files using HTTP POST in c#
For Java:
Image writing over URLConnection
how to send data with file upload to the server
HttpURLConnection POST, conn.getOutputStream() throwing Exception

Japanese text garbled while passing to a http restlet service

I have a Perl client which is calling an http restlet service (put method). Some of the parameters in this call contain japanese text. When I printed the contents of these request parameters in the restlet service I found these chars garbled !
This is my PERL client code:
my %request_headers = (
'DocumentName' => $document_name, --> This name is a JAPANESE String
'DocumentDescription' => 'Test Japanese Chars',
'content-length' => 200,
'Content-Type' => 'application/octet-stream; charset=utf-8',
'User-Agent' => "JPCharTester",
);
$s->write_request('PUT', '/test-document/TEST/TEST_DOCUMENT' , %request_headers, $content);
in this call both the values of $context and $document_name are JAPANESE Strings. But ONLY the document_name is received as garbled in my backend service.
Here goes the Service code:
String URL_ENCODING = "UTF-8";
String documentName = requestHeaders.getFirstValue("DocumentName");
System.out.println("Encoded Document Name : "+documentName+" <<<"); --> documentName is garbled here
try {
documentName = URLDecoder.decode(documentName, URL_ENCODING);
System.out.println(>>> Decoded Document Name : "+documentName+" <<<"); --> documentName is garbled here
} catch (java.io.UnsupportedEncodingException ex) {
throwException(ex.getMessage(), Status.SERVER_ERROR_INTERNAL, ex);
}
both the above log statements printed GARBLED TEXT !!
Can someone tell me what is the mistake I am doing and how to fix this ?
Thanks in advance for your help.
Regards,
Satish.
Don't forget to encode the data on the client side as UTF-8. If you say
'Content-Type' => 'application/octet-stream; charset=utf-8'
than that doesn't magically solve the problem. It's just a hint for the receiver in which form it will get the data. You must also send it with the correct format. In perl:
use utf8;
...
'DocumentName' => utf8::encode($document_name),
...
... , utf8::encode($content) ...

Resources