How to compress/decompress long string from php to android? - php

In my android app, it downloads a huge huge string from php. I want to compress it to save bandwidth. I found this page http://php.net/manual/en/function.gzcompress.php which allows me to compress it in php. But once I have it in android, how can I get back the original string?
Thanks

In my case I needed to decompress a string in PHP which was compressed in Android and visa versa and these strings were transported by RabbitMQ.
Here is how I solved it:
In Android:
public static byte[] compress(String string) throws IOException {
// string = "Lorem ipsum shizzle ma nizle";
byte[] data = string.getBytes("UTF-8");
ByteArrayOutputStream os = new ByteArrayOutputStream( data.length );
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write( data );
gos.close();
os.close();
return os.toByteArray();
}
public static String decompress(byte[] compressed) throws IOException {
final int BUFFER_SIZE = compressed.length;
ByteArrayInputStream is = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1) {
string.append(new String(data, 0, bytesRead));
}
gis.close();
is.close();
return string.toString();
}
RabbitMQ Calls from Android:
.
.
// Publish
chan.basicPublish(EXCHANGE, routing_key, MessageProperties.PERSISTENT_BASIC, compress(message.payload));
.
.
// Subscribe
String message = decompress(body);
.
.
.
From the RabbitMQ management plugin I retrieved the Base64 encoded version of the string in Latin, and ran it against this test app in PHP to see which decompression methodology works.
<?php
$data = "Lorem ipsum shizzle ma nizle";
// try all the compression algorithms and out the results in Hex format
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL ;
echo "\n\n";
for($i=-1;$i<=9;$i++)
echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL ;
echo "\n\n";
for($i=-1;$i<=9;$i++)
echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL;
echo "\n\n";
for($i=-1;$i<=9;$i++)
echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL;
echo "\n\n";
// add the Base64 encoded text from the RabbitMQ plugin
$data = "H4sIAAAAAAAAAPPJL0rNVcgsKC7NVSjOyKyqyklVyE1UyMsEMgCX3v4lHAAAAA==";
$data = base64_decode($data);
// output the binary version of the compressed string in Hex format
echo chunk_split(strtoupper(bin2hex($data)),2," ") . PHP_EOL ;
// match the HEX string to the samples from above as there may be an offset that you need to deal with
// finally see which of the decompression methods work
echo gzuncompress($data)."\n";
echo gzinflate($data)."\n";
echo gzdecode($data)."\n";
// Double check that you have the correct one
$data = "Lorem ipsum shizzle ma nizle";
echo chunk_split(strtoupper(bin2hex(gzencode($data,9,FORCE_GZIP))),2," ") . PHP_EOL;
$data = gzencode($data,9,FORCE_GZIP);
echo gzdecode($data)."\n";
Thanks

Looks like it is just using gzip compression. If that's the case, take a look at:
http://developer.android.com/reference/java/util/zip/GZIPInputStream.html
If that isn't exactly the compression algorithm being used, there are a few more built in algorithms you can use as needed:
http://developer.android.com/reference/java/util/zip/package-summary.html

Related

Convert VB.NET code to PHP

I have code to MD5 string in VB.Net, but i want convert it to php with same value return
VB.Net Code :
Public Shared Function ConverFileName(ByVal FileName As String) As String
Dim str2 As String = ""
Dim provider As New MD5CryptoServiceProvider
Try
Dim buffer As Byte() = provider.ComputeHash(Encoding.Default.GetBytes(FileName))
Dim num2 As Integer = (buffer.Length - 1)
Dim i As Integer = 0
Do While (i <= num2)
str2 = (str2 & StringType.FromByte(buffer(i)))
i += 1
Loop
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim exception As Exception = exception1
ProjectData.ClearProjectError
End Try
Return str2
End Function
There is already a inbuilt function to calculate the MD5 Hash of file in PHP.
md5_file($filename)
Example #1 Usage example of md5_file()
<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';
echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>
or if you need to find the MD5 Has for a string then
http://php.net/manual/en/function.md5.php
<?php
$str = 'apple';
echo 'MD5 hash of ' . $str. ': ' . md5($str);
?>
can u help change from vb net to php to
Function Enkrip(pwd As String) As String
Dim s As String
s = ""
For i = 1 To Len(pwd)
s = s + Chr(Asc(Mid(pwd, i, 1)) + 32)
Next i
Enkrip = s
End Function

Sending and receiving a file via WinHTTP from Lotus Notes

I am trying to send a document file from Lotus Script to a web server and save it there. Unfortunately the file transfer does not work. I have a Lotusscript agent to get the document and this part is working ( str_filecontent contains the correct xml file ), but the file transfer or saving is not working. Here is my Lotusscript agent:
Option Public
Option Declare
Sub Initialize
'Declare long
Dim lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout As Long
'Declare integer
Dim int_serverCredentials As Integer
'Declare variants
Dim var_submitObject As Variant
'Set values
int_serverCredentials = 0
lng_resolveTimeout = 120000 'miliseconds = 2 minutes
lng_connectTimeout = 1200000
lng_sendTimeout = 1200000
lng_receiveTimeout = 1200000
'Create HTTP object
Set var_submitObject = CreateObject("WinHTTP.WinHTTPRequest.5.1")
Call var_submitObject.SetTimeouts(lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout)
'Standards for this post
%REM
Content-Type: multipart/form-data; boundary={boundary}
{boundary}
Content-Disposition: form-data; name="data"; filename="{filename}"
Content-Type: text/plain
{contents}
{boundary}--
%END REM
Dim str_url As String
str_url = "http://.../upload.php"
Dim str_AUTH As String
Dim str_boundary As String
Dim str_filecontent As String
str_filecontent = get_data()
Dim submitHTTP
'Set post parameters
Call var_submitObject.open("POST", str_url, False)
Call var_submitObject.setRequestHeader("Accept", "application/xml")
Call var_submitObject.setRequestHeader("Authorization", "Basic " & str_auth)
Call var_submitObject.setRequestHeader("Content-Type", "multipart/form-data; boundary=b1")
str_boundary = |--b1| & Chr(13) & Chr(10) &_
|Content-Disposition: form-data; name="data"; filename="name.txt"| & Chr(13) & Chr(10) &_
|Content-Type: text/plain| & Chr(13) & Chr(10) &_
str_fileContent & |b1--|
'Send the HTTP request
Call var_submitObject.Send(str_boundary)
'Wait for the answer and set object as returned value for further validation
Call var_submitObject.WaitForResponse
Set submitHTTP = var_submitObject
'Clear memory
Set var_submitObject = Nothing
End Sub
%REM
Function get_data
Description: Comments for Function
%END REM
Function get_data() As String
Dim session As New NotesSession
Dim doc As NotesDocument
' Dim db As NotesDatabase
Dim exporter As NotesDXLExporter
' Set db = session.CurrentDatabase
Dim workspace As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc = workspace.CurrentDocument
Set doc = uidoc.Document
' Set doc = SESSION.CU
Set exporter = session.CreateDXLExporter
get_data = exporter.Export(doc)
Print get_data
End Function
Here is my web server PHP to receive and save the file:
<?php
define("UPLOAD_DIR", "/temp/");
if (!empty($_FILES["data"])) {
$myFile = $_FILES["data"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
?>
Thanks for your time!

PHP decrypting data with RSA Private Key

I have a program that encrypts passwords using a c# rsa public key which outputs a byte array.
In order for me to transport it easily and maintain data I am converting the bytes directly to a Hex string. Now this is where I am having issue. I send the post data to my script and am now unsure what to convert it to and how to decrypt it.
I am attempting to use http://phpseclib.sourceforge.net/ which I was pointed to by this post RSA decryption using private key The documentation on this is very vague and I don't know what data/type decrypt() should take.
<?php
include('Crypt/RSA.php');
if (isset($_POST['Password']))
{
$Password = $_POST['Password'];
$crypttext = pack("H*",$Password);
echo $cryptext;
$rsa = new Crypt_RSA();
$rsa->loadKey('key.priv');
$decryptedText =$rsa->decrypt($cryptext);
echo "Pass = >" . $decryptedText;
}
?>
Note that this gives no errors but $decryptedText is empty.
EDIT: Adding more info.
This is my c# encrypt method.
public static string Encrypt(string data, string keyLocation, string keyName)
{
Console.WriteLine("-------------------------BEGIN Encrypt--------------------");
// Variables
CspParameters cspParams = null;
RSACryptoServiceProvider rsaProvider = null;
string publicKeyText = "";
string result = "";
byte[] plainBytes = null;
byte[] encryptedBytes = null;
try
{
// Select target CSP
cspParams = new CspParameters();
cspParams.ProviderType = 1; // PROV_RSA_FULL
rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
// Read public key from Server
WebClient client = new WebClient();
Stream stream = client.OpenRead(keyLocation + "/" + keyName);
StreamReader reader = new StreamReader(stream);
publicKeyText = reader.ReadToEnd();
//
//Console.WriteLine("Key Text : {0}",publicKeyText);
// Import public key
rsaProvider.FromXmlString(publicKeyText);
// Encrypt plain text
plainBytes = Convert.FromBase64String(data);
Console.WriteLine("inputlength : {0}",plainBytes.Length);
encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
result = ByteArrayToString(encryptedBytes);
Console.WriteLine("Encrypted Hex string : {0}", result);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception encrypting file! More info:");
Console.WriteLine(ex.Message);
}
rsaProvider.Dispose();
Console.WriteLine("-------------------------END Encrypt--------------------");
return result;
} // Encrypt
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
I modified the php to this
<?php
include('Crypt/RSA.php');
if (isset($_POST['Password']))
{
$Password = $_POST['Password'];
$crypttext = pack("H*",$Password);
echo $cryptext;
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents('key.priv')); // Added file_get_contents() which fixed the key loading
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); // Added this which is essential thank you guys/gals
$decryptedText =$rsa->decrypt($cryptext);
echo "Pass = >" . $decryptedText; // gives unsual data. This needs to be converted from binary data to base64string I think
echo "Pass = >" . base64_encode($decryptedText); // gives no data.
echo "Pass = >" . base64_decode($decryptedText); // gives no data.
}
?>
I searched around and tried several things to convert back to text and I have tried base64_encode() and base64_decode() but I get nothing and otherwise I get gobbledey gook.
The final solution was to use imap_binary($decryptedText) to convert back.
Edit :
It has since been brought to my attention that a better way of doing this would be to replace 2 things
C#
plainBytes = Convert.FromBase64String(data);
Changed to
plainBytes = Encoding.UTF8.GetBytes(data);
and PHP
imap_binary($decryptedText)
Changed to
utf8_decode($decryptedText)

Rsa encrypted via php giving symbols in vb.net

im trying to crypt string in php decrypt it in vb.net
same key (xml converted to pem)
here is my php code
$source = "Baselsayeh!##312";
echo "Source: $source";
$fp=fopen("publicKey.pem","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
$hh = $source;
openssl_public_encrypt($hh,$crypttext,$pub_key);
$crypttext = base64_encode($crypttext);
echo "String crypted: " . $crypttext;
and here is my vb.net code
Function Decrypt(ByVal strCipherText As String, _
ByVal strPrivateKey As String) As String
Dim rsa As New RSACryptoServiceProvider()
Dim bytPlainText() As Byte
Dim bytCipherText() As Byte
Dim uEncode As New UnicodeEncoding()
rsa.FromXmlString(strPrivateKey)
bytCipherText = Convert.FromBase64String(strCipherText)
bytPlainText = rsa.Decrypt(bytCipherText, False)
Decrypt = uEncode.GetString(bytPlainText)
rsa.Clear()
End Function
any encrypted string giving 慂敳獬祡桥䀡㌣㈱
but encrypt in vb.net and decrypt in php works fine
never mind
solved it by using utf8 instaid of unicode
change
Dim uEncode As New UnicodeEncoding()
to
Dim uEncode As New UTF8Encoding()

Erlang Binary Packet

I'm very new to Erlang, and I am converting some of my PHP stuff, and I can't figure this one out. Here is the function in PHP:
public function raw_send($string1, $string2 = NULL, $type = SERVERDATA_EXECCOMMAND) {
$data = pack('VV', $this->get_request_id(), $type) . $string1 . chr(0) . $string2 . chr(0); // build data
$packet = pack('V', strlen($data)) . $data;
fwrite($this->fp, $packet, strlen($packet));
}
This is my attempt:
raw_send(Sock, String1, String2, Type) ->
RequestId = random:uniform(10),
PacketData = list_to_binary([<<RequestId, Type>>, String1, 0, String2, 0]),
DataLength = byte_size(PacketData),
Packet = list_to_binary([<<DataLength>>, PacketData]),
ok = gen_tcp:send(Sock, Packet).
I've tried using crc32 to compare things, pack("VV", 1, 3) in php should = <<1/unsigned-little, 3/unsigned-little>>, no?
Also, specs of what I'm trying to do: http://developer.valvesoftware.com/wiki/Source_RCON_Protocol
Halp!
Thanks
Got it, wasn't using 32 bit integers! (Thanks to ndim # freenode)
raw_send(Sock, String1, String2, Type) ->
RequestId = random:uniform(10),
String1Bin = list_to_binary(String1),
String2Bin = list_to_binary(String2),
PacketData = <<RequestId:32/little, Type:32/little, String1Bin/binary, 0, String2Bin/binary, 0>>,
DataLength = byte_size(PacketData),
Packet = <<DataLength:32/little, PacketData/binary>>,
ok = gen_tcp:send(Sock, Packet).
Hope that helps someone!

Categories