I need a way to encode a string to Mime/Base64 in Delphi 7 and PHP
These two encoders must be compatible :)
The Indy-Project provides base64 encoder/decoder classes. You can find the documentation here.
For PHP, you can use the PHP-internal functions base64_encode and base64_decode.
The unit EncdDecd has been included since Delphi 6; below are the Mime compatible base64 functions it contains.
This cached post from FlexVN (the original post is not always on-line) explains how to do the base64 thing between PHP and Delphi using the EncdDecd unit.
unit EncdDecd;
interface
uses Classes, SysUtils;
procedure EncodeStream(Input, Output: TStream);
procedure DecodeStream(Input, Output: TStream);
function EncodeString(const Input: string): string;
function DecodeString(const Input: string): string;
function DecodeBase64(const Input: AnsiString): TBytes;
function EncodeBase64(const Input: Pointer; Size: Integer): AnsiString;
Related
I'm migrating a web service that was developed in VB.NET to PHP
I explain:
In VB. NET I have a method that compresses a single string with GZIP. ("Hello world!")
The method in the web service returns an array of bytes.
Then the array of bytes is received on a device with android, decompressed and converted to a string, this process works perfect.
the method in VB.NET, is this:
<WebMethod(Description:="GZIP Test")> _
Public Function GZIP() As Byte()
Dim vTest As String = "Hello world!"
Dim vBuffer1() As Byte = StrToByteArray(vTest)
Dim vBuffer2() As Byte = Compress(vBuffer1)
Return vBuffer2
End Function
Private Function StrToByteArray(ByVal str As String) As Byte()
Dim encoding As New System.Text.UTF8Encoding()
Return encoding.GetBytes(str)
End Function
Private Function Compress(ByVal Bits() As Byte) As Byte()
On Error Resume Next
Using ms As New MemoryStream(), zipMem As New GZipStream(ms, CompressionMode.Compress, True)
zipMem.Write(Bits, 0, Bits.Length)
zipMem.Close()
Return ms.ToArray
End Using
End Function
this method returns me the following value:
<base64Binary>H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Ir6dl2WVXlV1Oftd/x+VGYUbDAAAAA==</base64Binary>
I want PHP return me the SAME VALUE.
the tests I've done in PHP returns me the following.
function GZIP() {
ob_start ( 'ob_gzhandler' );
return base64_encode(gzdeflate('Hello world!', 9));
}
the value returned in PHP is:
80jNyclXKM8vyklRBAA=
Why ? There is an example that returns the same ?
Thanks in advance for all.
You are using the wrong de-/compression algorithm. Use phps gzcompress() and gzuncompress() instead.
First off, you can't require the exact same result. All you can require of a lossless compressor is that it reproduce exactly the same input when decompressed.
Second, you want to use gzencode to produce gzip streams. Neither gzdeflate nor gzcompress will do that. The former produces raw deflate streams, and the second zlib streams. (Don't get me started about the misleading names and the messed up PHP documentation about them.)
I have been trying to unserialize PHP session data in Python by using phpserialize and a serek's modules(got it from Unserialize PHP data in python), but it seems like impossible to me.
Both modules expect PHP session data to be like:
a:2:{s:3:"Usr";s:5:"AxL11";s:2:"Id";s:1:"2";}
But the data stored in the session file is:
Id|s:1:"2";Usr|s:5:"AxL11";
Any help would be very much appreciated.
The default algorithm used for PHP session serialization is not the one used by serialize, but another internal broken format called php, which
cannot store numeric index nor string index contains special characters (| and !) in $_SESSION.
The correct solution is to change the crippled default session serialization format to the one supported by Armin Ronacher's original phpserialize library, or even to serialize and deserialize as JSON, by changing the session.serialize_handler INI setting.
I decided to use the former for maximal compatibility on the PHP side by using
ini_set('session.serialize_handler', 'php_serialize')
which makes the new sessions compatible with standard phpserialize.
After reaching page 3 on Google, I found a fork of the original application phpserialize that worked with the string that I provided:
>>> loads('Id|s:1:"2";Usr|s:5:"AxL11";')
{'Id': '2', 'Usr': 'AxL11'}
This is how I do it in a stupid way:
At first, convert Id|s:1:"2";Usr|s:5:"AxL11"; to a query string Id=2&Usr=AxL11& then use parse_qs:
import sys
import re
if sys.version_info >= (3, 0):
from urllib.parse import parse_qs, quote
else:
from urlparse import parse_qs
from urllib import quote
def parse_php_session(path):
with open(path, 'r') as sess:
return parse_qs(
re.sub(r'\|s:([0-9]+):"?(.*?)(?=[^;|]+\|s:[0-9]+:|$)',
lambda m : '=' + quote(m.group(2)[:int(m.group(1))]) + '&',
sess.read().rstrip().rstrip(';') + ';')
)
print(parse_php_session('/session-save-path/sess_0123456789abcdef'))
# {'Id': ['2'], 'Usr': ['AxL11']}
It used to work without replacing ; to & (both are allowed). But since Python 3.10 the default separator for parse_qs is &
I was looking for a equivalent function to PHP RawURLEncode (and Decode) in cpp builder (or delphi).
I use the following string to test: _%_&_+_=_ _"_'_a_b_c_d_e_f_g_h_ (I wish to encode only var values, not a entire URL)
The rawurlencode returns: _%25_%26_%2B_%3D_%20_%22_%27_a_b_c_d_e_f_g_h_
I have tried without success:
TIdURI::ParamsEncode: _%25_&_+_=_%20_%22_'_a_b_c_d_e_f_g_h_
TIdURI::PathEncode: _%25_&_%2B_=_%20_%22_'_a_b_c_d_e_f_g_h_
TIdURI::URLEncode: Error: No Protocol (Needs full path)
HTTPApp::HTMLEncode: _%_& amp;_+_=_ _& quot;_'_a_b_c_d_e_f_g_h_ (space added after "&")
Wininet::WinHTTPEncode: Function not found in unit
IdGlobal::URLEncode: Function not found in unit
SynaCode::URLEncode: Unit not found in XE2
PHP's RawURLEncode is an implementation of RFC 3986. My websearch for that yields this Delphi unit which claims to implement RFC 3986.
I tested it on your input:
{$APPTYPE CONSOLE}
uses
System.SysUtils,
UURIEncode in 'UURIEncode.pas';
begin
Writeln(URIEncode('_%_&_+_=_ _"_''_a_b_c_d_e_f_g_h_'));
Readln;
end.
The output was:
_%25_%26_%2B_%3D_%20_%22_%27_a_b_c_d_e_f_g_h_
The key to my successful websearch was found in the PHP documentation for RawURLEncode where is states:
URL-encode according to RFC 3986
So I've got some data that's been compressed with PHP's gzcompress method:
http://us2.php.net/manual/en/function.gzcompress.php
How can I decode this data from node.js??
I've tried "compress", "zlib" and several other node compression libraries, but none of them seem to reckognize the data. For example, zlib just gives me "Error: incorrect header check"
Answer: Turns out that "zlib" is the way to go. We had an additional issue with binary data from memcache. If you have binary data in a node.js Buffer object and you call toString() instead of .toString('binary'), it get's all kinds of scrambled as stuff is escaped or escape sequences are interpreted or whatever. Unfortunately, all the memcache plugins I've tried to date assume string data from memcache, and are not disciplined about handling it properly.
Best ZLIB module I've found:
https://github.com/kkaefer/node-zlib
// first run "npm install zlib", then...
var zlib = require('zlib');
var gz = zlib.deflate(new Buffer("Hello World", 'binary')); // also another 'Buffer'
console.log(zlib.inflate(gz).toString('binary'));
FYI, this question is VERY similar to a related question about Java:
PHP's gzuncompress function in Java?
Stealing from another post (Which compression method to use in PHP?)
gzencode() uses the fully self-contained gzip format, same as the gzip command line tool
gzcompress() uses the raw ZLIB format. It is similar to gzencode but has different header data, etc. I think it was intended for streaming.
gzdeflate() uses the raw DEFLATE algorithm on its own, which is the basis for both the other formats.
Thus, "zlib" would be the correct choice. This is NOT cross-compatible with gzip.
Try https://github.com/kkaefer/node-zlib
php:
<?php
$data = 'HelloWorld';
$gzcompress = gzcompress($data);
$gzcompress_base64_encode = base64_encode($gzcompress);
echo "Compressing: {$data}\n";
echo $gzcompress."\n";
echo $gzcompress_base64_encode."\n";
echo "--- inverse ---\n";
echo gzuncompress(base64_decode($gzcompress_base64_encode))."\n";
nodejs:
const zlib = require('zlib');
var data = 'HelloWorld';
var z1 = zlib.deflateSync( Buffer.from(data));
var gzcompress = z1.toString();
var gzcompress_base64_encode = z1.toString('base64');
console.log('Compressing '+data);
console.log(gzcompress);
console.log(gzcompress_base64_encode);
console.log('--- inverse ---');
console.log(zlib.inflateSync(Buffer.from(gzcompress_base64_encode,'base64')).toString());
I have a string that I would like to encrypt in Python, store it as a cookie, then in a PHP file I'd like to retrieve that cookie, and decrypt it in PHP. How would I go about doing this?
I appreciate the fast responses.
All cookie talk aside, lets just say I want to encrypt a string in Python and then decrypt a string in PHP.
Are there any examples you can point me to?
Use a standard encryption scheme. The implementation is going to be equivalent in either language.
RSA is available (via third party libraries) in both languages, if you need asymmetric key crypto. So is AES, if you need symmetric keys.
There is a good example here:
http://www.codekoala.com/blog/2009/aes-encryption-python-using-pycrypto/
Other links that may help:
http://www.phpclasses.org/browse/package/4238.html
http://www.chilkatsoft.com/p/php_aes.asp
If you're not talking about encryption but encoding to make sure the contents make it through safely regardless of quoting issues, special characters, and line breaks, I think base64 encoding is your best bet. PHP has base64_encode / decode() out of the box, and I'm sure Python has, too.
Note that base64 encoding obviously does nothing to encrypt your data (i.e. to make it unreadable to outsiders), and base64 encoded data grows by 33%.
Well, my first thought would be to use a web server that uses SSL and set the cookie's secure property to true, meaning that it will only be served over SSL connections.
However, I'm aware that this probably isn't what you're looking for.
Although a bit late. Find sample code below using the Fernet library
#Python Code - fernet 1.0 library
from cryptography.fernet import Fernet
key = b"Gm3wFh9OiQHcVc8rcAMm8IOqKOJtk7CbrGRKVhrvXhg="
f = Fernet(key)
token = f.encrypt(b'the quick brown fox jumps over the lazy hare')
print(token)
##gAAAAABiMWVPsStLo42ExcmIqcGvRvCCmnhB5B6dc2JsOm4w-VsE9oJOuk_qYuZvHv5quQR4t_6ZjNJzAdCiDPOtESNzCreJZLwc2X-_apbqKKnBwc3KhmqL-K5X7t1uR1WXuyUEYUtW
<?php
//PHP - kelvinmo/fernet-php v1.0.1 A
require 'vendor/autoload.php';
use Fernet\Fernet;
$key = "Gm3wFh9OiQHcVc8rcAMm8IOqKOJtk7CbrGRKVhrvXhg=" ;
$fernet = new Fernet($key);
$token = "gAAAAABiMWVPsStLo42ExcmIqcGvRvCCmnhB5B6dc2JsOm4w-VsE9oJOuk_qYuZvHv5quQR4t_6ZjNJzAdCiDPOtESNzCreJZLwc2X-_apbqKKnBwc3KhmqL-K5X7t1uR1WXuyUEYUtW";
echo $fernet->decode($token);
?>