I was trying to compress a String in php using the following code.
<?php
$compressed = gzcompress('Compress me', 9);
echo $uncompressed;
?>
The compressed string is "xÚsÎÏ-(J-.VÈM½?".
But when tried to decompress this in java using the following function
public static String unzipString(String zippedText) {
String unzipped = null;
try {
byte[] zbytes = zippedText.getBytes("ISO-8859-1");
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString();
} catch (IOException io) {
printIoError(io);
}
return unzipped;
}
I was getting null string..Please correct me if i did something wrong this code.
Related
Itext is a powerful toolkit for PDF generation, PDF programming, handling & manipulation. Java sample:
public void processPDF(String src, String dest) {
try {
PdfReader reader = new PdfReader(src);
PdfArray refs = null;
PRIndirectReference reference = null;
int nPages = reader.getNumberOfPages();
for (int i = 1; i <= nPages; i++) {
PdfDictionary dict = reader.getPageN(i);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object.isArray()) {
refs = dict.getAsArray(PdfName.CONTENTS);
ArrayList<PdfObject> references = refs.getArrayList();
for (PdfObject r : references) {
reference = (PRIndirectReference) r;
PRStream stream = (PRStream) PdfReader.getPdfObject(reference);
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("test", "tested");
stream.setData(dd.getBytes());
}
}
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
System.out.println("content---->" + dd);
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("This", "FIRST");
stream.setData(dd.getBytes(StandardCharsets.UTF_8));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
catch (Exception e) {
}
}
The question is how I can use this toolkit for PHP or there is any PHP toolkit like this?
I am using Yii2 Framework and just want to replace text inside a certain file (.doc, .docx, .pdf)
Original file:
Expected file after editing:
I have this piece of code which is in java but i want it in php .
there is a function to convert hex to byte . and a main code:
public static byte[] ConvertHexStringToByteArray(String s)
{
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
and here is main code :
public static String hmacSha1(String value, String key)
{
try
{
// Get an hmac_sha1 key from the raw key bytes byte[]
keyBytes = ConvertHexStringToByteArray(key);
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing
key Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(value.getBytes(StandardCharsets.US_ASCII));
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
Hello
Your Java code in php is same as blow :
$key = strtolower($CPCode.$service_id.$price.$timestamp.$request_id);
$authKey = $CPCode;
$sign = hash_hmac("sha1",$key,$authKey);
Good Luck
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)
I want to upload an Image i selected with the PhotoChooserTask.
The Selection itself works fine and i can open the Image.
I also already decoded it to Base64 (Works).
Since I can't find any working example on how to work with httpwebrequest on windowsphone I tried it the following way.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
MyImage.Source = bmp;
String str = BitmapToByte(MyImage);
String url = "http://klopper.puppis.uberspace.de/php/app/image.php?image="+ str;
LoadSiteContent(url);
}
}
The rest of the code is working fine.
I get: System.IO.FileNotFoundException
If I change the str to "test" it's working.
Is the problem, that the string is too long?
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("http://localhost:4223/File/Upload", UriKind.Absolute);
WebClient wc = new WebClient();
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "POST");
}
Reference
to post image file in windows phone 7 application
this is my first post. please be kind :)
i'm trying to get picture from media library (in WP 7), upload it using httpwebrequest, and save it to folder in the server. i succeed to convert the image to string of byte (but i suspect there are something wrong here), send the string using POST, and retrieve it in my php web page.
Everything seems to be working well, but when i convert the string of byte to jpeg (using imagecreatefromstring function) it always come up empty picture. here is my code in C# and php. I'm sorry for my English if it's not perfect (or far from perfect) :)
this is my c# code along with some comments
public partial class MainPage : PhoneApplicationPage
{
string uploadUri = #"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server
string requestImageName = "picture"; //variable name for post ---- >$_POST['picture']
string postdata; //byte data generate using BitmapToByte function
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
Image image1 = new Image ();
private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest req = HttpWebRequest.Create(
new Uri(this.uploadUri)) as HttpWebRequest;
postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req);
}
}
private void HttpWebRequestButton2_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
using (var requestStream = req.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata"
writer.Flush();
}
}
req.BeginGetResponse(HttpWebRequestButton_Callback, req);
}
private void HttpWebRequestButton_Callback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
var reader = new StreamReader(strm);
this.Dispatcher.BeginInvoke(() => {
this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly.
this.DownloadedText.Visibility = System.Windows.Visibility.Visible;
});
}
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //i suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
and this is my code in php web page
if(isset($_REQUEST['picture'])) //check
{
$myFile = "picture.jpg";
$fh = fopen($myFile, 'wb') or die("can't open file");
$stringData = $_REQUEST['picture']."<br>";
$im = imagecreatefromstring($stringData);
if ($im) {
imagejpeg($im);
fwrite($fh, $im);
imagedestroy($im);
}
fclose($fh);
echo $stringData;
}
Please look at my question here: Photo upload with parameters to a PHP page
And my solution here: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/