Is there any library for lazarus ( free pascal ) which supports asymmetric encryption?
Lazarus/FPC comes with openssh headers afaik. It might not be necessary to go the external program route.
To make asymmetric encryption in Lazarus you need to integrate openssl.
If you use windows download http://slproweb.com/download/Win32OpenSSL_Light-1_0_1e.exe
Now you can use openssl in lazarus like this:
uses ..., Process;
...
procedure encrypt_file();
var hProcess : TProcess;
begin
hProcess := TProcess.Create(nil);
hProcess.Executable := 'openssl';
hprocess.Parameters.Add('aes-256-cbc');
hprocess.Parameters.Add('-a -salt');
hprocess.Parameters.Add('-in secrets.txt'); //input file
hprocess.Parameters.Add('-out secrets.txt.enc'); //output file
hProcess.Options := hProcess.Options + [poWaitOnExit, poUsePipes];
hProcess.Execute;
end;
procedure decrypt_file();
var hProcess : TProcess;
begin
hProcess := TProcess.Create(nil);
hProcess.Executable := 'openssl';
hprocess.Parameters.Add('aes-256-cbc');
hprocess.Parameters.Add('-d -salt');
hprocess.Parameters.Add('-in secrets.txt.enc'); //input file
hprocess.Parameters.Add('-out secrets.txt.new'); //output file
hProcess.Options := hProcess.Options + [poWaitOnExit, poUsePipes];
hProcess.Execute;
end;
Note: The example is for symmetric encryption for asymmetric read this article:
http://www.devco.net/archives/2006/02/13/public_-_private_key_encryption_using_openssl.php
Related
TFDConnection.Params.Server is not a valid published property in Delphi XE7. How can I set the server location programmatically? I have 2 MySQL servers (test and production) that are at different ip's and based on what I am doing in the application, I want to easily switch back and forth between the 2 servers.
Please read the documentation, it tells you exactly how to define a FireDAC connection for MySQL:
Working with Connections (FireDAC)
Connect to MySQL Server (FireDAC)
You would specify the DB server as part of a Connection Definition:
Defining Connection (FireDAC)
Connection Definitions can be defined in an external .ini file, which you can then reference in the TFDManager.ConnectionDefFileName property, or load dynamically using the TFDManager.LoadConnectionDefFile() method.
[MySQL_Connection_1]
DriverID=MySQL
Server=192.168.1.100
...
[MySQL_Connection_2]
DriverID=MySQL
Server=192.168.1.101
...
Or dynamically using the TFDManager.ConnectionDefs property:
var
oDef: IFDStanConnectionDef;
begin
oDef := FDManager.ConnectionDefs.AddConnectionDef;
oDef.Name := 'MySQL_Connection_1';
oDef.DriverID := 'MySQL';
oDef.Server := '192.168.1.100';
...
oDef.Apply;
oDef := FDManager.ConnectionDefs.AddConnectionDef;
oDef.Name := 'MySQL_Connection_2';
oDef.DriverID := 'MySQL';
oDef.Server := '192.168.1.101';
...
oDef.Apply;
var
oParams: TStrings;
begin
oParams := TStringList.Create;
oParams.Add('Server=192.168.1.100');
...
FDManager.AddConnectionDef('MySQL_Connection_1', 'MySQL', oParams);
oParams.Clear;
oParams.Add('Server=192.168.1.101');
...
FDManager.AddConnectionDef('MySQL_Connection_2', 'MySQL', oParams);
Either way, you can then tell TFDConnection which Connection Definition to use to reach each database when needed:
FDConnection1.ConnectionDefName := 'MySQL_Connection_1';
// or: FDConnection1.ConnectionDefName := 'MySQL_Connection_2';
FDConnection1.Connected := True;
Alternatively, you can specify the connection parameters directly in the TFDConnection.Params property if you do not want to pre-define separate connection definitions:
FDConnection1.DriverName := 'MySQL';
FDConnection1.Params.Clear;
FDConnection1.Params.Add('Server=192.168.1.100');
// or: FDConnection1.Params.Values['Server'] := '192.168.1.100';
...
FDConnection1.Connected := True;
Late answer but it's simple to do.
Restating what TLama said in a comment:
The param properties can vary depending on the driver type, so set the driver type to MySQL and then cast the PARAMS as the driver type.
Just do:
(Conn1.Params as TFDPhysMySQLConnectionDefParams).Server := '127.0.0.1';
This way the compiler can verify the param at compile time.
This works for me. Add any additional parameters as needed
var
oParams: TStrings;
begin
oParams := TStringList.Create;
oParams.Add('Server=' + YourServer);
oParams.Add('Database=' + YourDatabase);
oParams.Add('OSAuthent=Yes');
FDManager.AddConnectionDef('CNX1', 'MSSQL', oParams);
FDConnection.ConnectionDefName := 'CNX1';
FDConnection.Connected := true;
if FDConnection.Connected then
ShowMessage('Connected');
oParams.Free;
As the title suggests, using Delphi 2010 and MyDAC 7.1, how do I output an entire string as a string like JSON / XML / CSV or some other plain text option?
eg output:
{user_id:1;username:testuser;password:testpass}
Presuming that MyDAC is a standard TDataSet descendant, you can build the string manually. For instance, for JSON:
var
i: Integer;
Output: string;
begin
Output := '{'; // #123;
for i := 0 to MyQry.FieldCount - 1 do
Output := Output +
MyQry.Fields[i].FieldName + ':' + // #58
MyQry.Fields[i].AsString + ';'; // #59
// Replace final ; with closing } instead
Output[Length(Output)] := '}'; // #125
end;
Or you can Google to find a Delphi JSON library (like SuperObject) and use it instead, as is done here.
For XML, use the same type loop with TXMLDocument. You can search for previous posts here tagged with Delphi to find examples.
For CSV, it can get complicated based on your data and the requirements. For instance, do you want or need a header row with field names? Does your data contain data that contains spaces or punctuation or CR/LFs? The easiest solution is to search for an already-existing library (via Google or Bing, not here) that exports to CSV.
According to the documentation you can use the SaveToXML procedures. should be something like this:
var
MyQuery: TMyQuery;
begin
try
MyQuery := TMyQuery.Create();
MyQuery.Connection := AConnection;
MyQuery.SQL.Text := ACommand;
MyQuery.Execute();
MyQuery.SaveToXML(<tstream or file>)
except
raise;
end;
end;
I'm inserting an image file into a blob field using...
procedure TfrmMain.FileToDB(filename: string; blobfield: TBlobField);
var
FS: TFileStream;
begin
FS := TFileStream.Create(filename,fmOpenRead);
try
BlobField.LoadFromStream(FS);
finally
FS.Free;
end;
end;
This works fine, and I can even open the file in mysql workbench and as it's an image file I can also view it.
When I try to save the image back to disk using...
procedure TfrmMain.DBToFile(filename: string; blobfield: TBlobField);
var
FS: TFileStream;
begin
FS := TFileStream.Create(filename,fmCreate);
try
BlobField.SaveToStream(FS);
finally
FS.Free;
end;
end;
I get a file of only 4 bytes. ??
I've tried this with BLOB / MEDIUMBLOB / LARGEBLOB type fields, and using the above BlobField.SaveToStream() method, as well as creating a blob stream and using FS.CopyFrom(). When using the later method, the blobstream.size property shows a value of 4 also.
I'm using the unicode driver, and a unicode schema in mysql. What could be going on here?
While the problem is not resolved using FireDAC, switching to ADO components got me past this issue.
procedure TfrmMain.DBToFile(filename: string; blobfield: TBlobField);
var
FS: TFileStream;
begin
FS := TFileStream.Create(filename,fmCreate);
try
BlobField.SaveToStream(FS);
**FS.position:=0; // It can help**
finally
FS.Free;
end;
end;
The following code is from the docs here:
Program ConnectDB
var AConnection : TSQLConnection;
Procedure CreateConnection;
begin
AConnection := TIBConnection.Create(nil);
AConnection.Hostname := 'localhost';
AConnection.DatabaseName := '/opt/firebird/examples/employee.fdb';
AConnection.UserName := 'sysdba';
AConnection.Password := 'masterkey';
end;
begin
CreateConnection;
AConnection.Open;
if Aconnection.Connected then
writeln('Succesful connect!')
else
writeln('This is not possible, because if the connection failed, ' +
'an exception should be raised, so this code would not ' +
'be executed');
AConnection.Close;
AConnection.Free;
end.
The main body of the code makes sense to me BUT I don't get where TSQLConnection came from. I cannot use CTRL + Space to autocomplete it either, which means my program has no reference to it. I'm trying to connect to Postgres by the way.
Can someone please state what TSQLConnection is? Thanks!
the TSQLConnection object is defined in the sqldb unit and is the base class for the specific connection components like the TIBConnection (interbase, firebird), TConnectionName (mysql) and TPQConnection (postgres).
I'm currently using this JSON escaping function in PostgreSQL as a stand in for future native JSON support. While it works, it's also limiting our systems performance. How can I go about optimizing it? Maybe some kind of lookup array?
CREATE OR REPLACE FUNCTION escape_json(i_text TEXT)
RETURNS TEXT AS
$body$
DECLARE
idx INTEGER;
text_len INTEGER;
cur_char_unicode INTEGER;
rtn_value TEXT := i_text;
BEGIN
-- $Rev: $ --
text_len = LENGTH(rtn_value);
idx = 1;
WHILE (idx <= text_len) LOOP
cur_char_unicode = ASCII(SUBSTR(rtn_value, idx, 1));
IF cur_char_unicode > 255 THEN
rtn_value = OVERLAY(rtn_value PLACING (E'\\u' || LPAD(UPPER(TO_HEX(cur_char_unicode)),4,'0')) FROM idx FOR 1);
idx = idx + 5;
text_len = text_len + 5;
ELSE
/* is the current character one of the following: " \ / bs ff nl cr tab */
IF cur_char_unicode IN (34, 92, 47, 8, 12, 10, 13, 9) THEN
rtn_value = OVERLAY(rtn_value PLACING (E'\\' || (CASE cur_char_unicode
WHEN 34 THEN '"'
WHEN 92 THEN E'\\'
WHEN 47 THEN '/'
WHEN 8 THEN 'b'
WHEN 12 THEN 'f'
WHEN 10 THEN 'n'
WHEN 13 THEN 'r'
WHEN 9 THEN 't'
END)
)
FROM idx FOR 1);
idx = idx + 1;
text_len = text_len + 1;
END IF;
END IF;
idx = idx + 1;
END LOOP;
RETURN rtn_value;
END;
$body$
LANGUAGE plpgsql;
Confession: I am the Google Summer of Code 2010 student who was going to try to bring JSON support to PostgreSQL 9.1. Although my code was fairly feature-complete , it wasn't completely ready for upstream, and the PostgreSQL development community was looking at some alternative implementations. However, with spring break coming up, I'm hoping to finish my rewrite and give it a final push this week.
In the mean time, you can download and install the work-in-progress JSON data type module, which should work on PostgreSQL 8.4.0 and up. It is a PGXS module, so you can compile and install it without having to compile all of PostgreSQL. However, you will need the PostgreSQL server development headers.
Installation goes something like this:
git clone git://git.postgresql.org/git/json-datatype.git
cd json-datatype/
USE_PGXS=1 make
sudo USE_PGXS=1 make install
psql -f json.sql <DBNAME1> # requires database superuser privileges
Although the build and install only needs to be done once, json.sql needs to be run on every database you plan to use the JSON data type on.
With that installed, you can now run:
=> SELECT to_json(E'"quotes and \n newlines"\n'::TEXT);
to_json
--------------------------------
"\"quotes and \n newlines\"\n"
(1 row)
Note that this does not escape non-ASCII characters.
All my approaches boil down to "do it some other way":
Write it in some other language, e.g. use pl/perl, pl/python, pl/ruby
Write a wrapper round some external JSON library written in C
Do the JSON escaping in the client rather than in the query (assuming your client has some good JSON escaping support)
In my experience pl/pgsql isn't fast at this sort of thing- its strength is in its integral support for exchanging data with the database, not as a general-purpose programming language.
Example:
create or replace function escape_json_perl(text) returns text
strict immutable
language plperlu as $$
use JSON;
return JSON->new->allow_nonref->encode($_[0]);
$$;
A quick test suggests this is on the order of 15x faster than the plpgsql function (although it returns quotes around the value which you probably want to strip off)
I have found a PostgreSQL function implemented in C here : http://code.google.com/p/pg-to-json-serializer/
I have not compared it with your PLSQL method but it should be faster than any interpreted language.
Another one : http://miketeo.net/wp/index.php/projects/json-functions-for-postgresql