sqlite c# generated open on as3 - c#

I have a DB that is generated by C# code, and when i'm creating it I use the connection string I use
new SQLiteConnection("Data Source=" + dbPath + ";Version=3;New=False;Compress=True;Password=1234");
The database is created with success but when I download it to my computer and try to read in on adobe air I can't seem to open the database. The only way of passing password to the connection is passing it by bytearray but I can't get it right.
My as3 code is like this:
_connection = new SQLConnection();
_connection.addEventListener(SQLEvent.OPEN, onDatabaseOpen);
_connection.addEventListener(SQLEvent.CLOSE, onDatabaseClose);
_connection.addEventListener(SQLErrorEvent.ERROR, onDatabaseError);
var ba:ByteArray = new ByteArray();
ba.writeMultiByte("1234","unicode");
_connection.open(_mydatabaseFile,SQLMode.READ,false,1024,ba);
It always gets an error because of the length of the bytearray.
Edit:
I forgot to mention, if i don't put the password on the conection i can open the database without problem using just _connection.open(_mydatabaseFile)
Thanks in advance
Alex

Related

Set password in sqlite .db3 file in xamarin forms [duplicate]

I have to face a new little project. It will have about 7 or 9 tables, the biggest of them will grow by a max rate of 1000 rows a month.
I thought about SQLite as my db... But i will need to protect the db in case anybody wants to change data from the db
My main question is:
Is it possible password protect a sqlite db as you would do on access?
The development would be on C#, but I'm searching something free.
You can password protect a SQLite3 DB. Before doing any operations, set the password as follows.
SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();
then next time you can access it like
conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();
This wont allow any GUI editor to view your data. Some editors can decrypt the DB if you provide the password. The algorithm used is RSA.
Later if you wish to change the password, use
conn.ChangePassword("new_password");
To reset or remove password, use
conn.ChangePassword(String.Empty);
You can use the built-in encryption of the sqlite .net provider (System.Data.SQLite). See more details at http://web.archive.org/web/20070813071554/http://sqlite.phxsoftware.com/forums/t/130.aspx
To encrypt an existing unencrypted database, or to change the password of an encrypted database, open the database and then use the ChangePassword() function of SQLiteConnection:
// Opens an unencrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
// Encrypts the database. The connection remains valid and usable afterwards.
cnn.ChangePassword("mypassword");
To decrypt an existing encrypted database call ChangePassword() with a NULL or "" password:
// Opens an encrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3;Password=mypassword");
cnn.Open();
// Removes the encryption on an encrypted database.
cnn.ChangePassword(null);
To open an existing encrypted database, or to create a new encrypted database, specify a password in the ConnectionString as shown in the previous example, or call the SetPassword() function before opening a new SQLiteConnection. Passwords specified in the ConnectionString must be cleartext, but passwords supplied in the SetPassword() function may be binary byte arrays.
// Opens an encrypted database by calling SetPassword()
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.SetPassword(new byte[] { 0xFF, 0xEE, 0xDD, 0x10, 0x20, 0x30 });
cnn.Open();
// The connection is now usable
By default, the ATTACH keyword will use the same encryption key as the main database when attaching another database file to an existing connection. To change this behavior, you use the KEY modifier as follows:
If you are attaching an encrypted database using a cleartext password:
// Attach to a database using a different key than the main database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY 'mypassword'", cnn);
cmd.ExecuteNonQuery();
To attach an encrypted database using a binary password:
// Attach to a database encrypted with a binary key
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY X'FFEEDD102030'", cnn);
cmd.ExecuteNonQuery();
Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net
You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.
Quoting SQLite documentation:
The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.
You can find more info about this addon in this link.
One option would be VistaDB. They allow databases (or even tables) to be password protected (and optionally encrypted).
If you use FluentNHibernate you can use following configuration code:
private ISessionFactory createSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFileWithPassword(filename, password))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<DBManager>())
.ExposeConfiguration(this.buildSchema)
.BuildSessionFactory();
}
private void buildSchema(Configuration config)
{
if (filename_not_exists == true)
{
new SchemaExport(config).Create(false, true);
}
}
Method UsingFileWithPassword(filename, password) encrypts a database file and sets password.
It runs only if the new database file is created. The old one not encrypted fails when is opened with this method.
I know this is an old question but wouldn't the simple solution be to just protect the file at the OS level? Just prevent the users from accessing the file and then they shouldn't be able to touch it. This is just a guess and I'm not sure if this is an ideal solution.
Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.

Password protect a SQLite database with SQLite-Net Extensions [duplicate]

I have to face a new little project. It will have about 7 or 9 tables, the biggest of them will grow by a max rate of 1000 rows a month.
I thought about SQLite as my db... But i will need to protect the db in case anybody wants to change data from the db
My main question is:
Is it possible password protect a sqlite db as you would do on access?
The development would be on C#, but I'm searching something free.
You can password protect a SQLite3 DB. Before doing any operations, set the password as follows.
SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();
then next time you can access it like
conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();
This wont allow any GUI editor to view your data. Some editors can decrypt the DB if you provide the password. The algorithm used is RSA.
Later if you wish to change the password, use
conn.ChangePassword("new_password");
To reset or remove password, use
conn.ChangePassword(String.Empty);
You can use the built-in encryption of the sqlite .net provider (System.Data.SQLite). See more details at http://web.archive.org/web/20070813071554/http://sqlite.phxsoftware.com/forums/t/130.aspx
To encrypt an existing unencrypted database, or to change the password of an encrypted database, open the database and then use the ChangePassword() function of SQLiteConnection:
// Opens an unencrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
// Encrypts the database. The connection remains valid and usable afterwards.
cnn.ChangePassword("mypassword");
To decrypt an existing encrypted database call ChangePassword() with a NULL or "" password:
// Opens an encrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3;Password=mypassword");
cnn.Open();
// Removes the encryption on an encrypted database.
cnn.ChangePassword(null);
To open an existing encrypted database, or to create a new encrypted database, specify a password in the ConnectionString as shown in the previous example, or call the SetPassword() function before opening a new SQLiteConnection. Passwords specified in the ConnectionString must be cleartext, but passwords supplied in the SetPassword() function may be binary byte arrays.
// Opens an encrypted database by calling SetPassword()
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.SetPassword(new byte[] { 0xFF, 0xEE, 0xDD, 0x10, 0x20, 0x30 });
cnn.Open();
// The connection is now usable
By default, the ATTACH keyword will use the same encryption key as the main database when attaching another database file to an existing connection. To change this behavior, you use the KEY modifier as follows:
If you are attaching an encrypted database using a cleartext password:
// Attach to a database using a different key than the main database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY 'mypassword'", cnn);
cmd.ExecuteNonQuery();
To attach an encrypted database using a binary password:
// Attach to a database encrypted with a binary key
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY X'FFEEDD102030'", cnn);
cmd.ExecuteNonQuery();
Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net
You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.
Quoting SQLite documentation:
The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.
You can find more info about this addon in this link.
One option would be VistaDB. They allow databases (or even tables) to be password protected (and optionally encrypted).
If you use FluentNHibernate you can use following configuration code:
private ISessionFactory createSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFileWithPassword(filename, password))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<DBManager>())
.ExposeConfiguration(this.buildSchema)
.BuildSessionFactory();
}
private void buildSchema(Configuration config)
{
if (filename_not_exists == true)
{
new SchemaExport(config).Create(false, true);
}
}
Method UsingFileWithPassword(filename, password) encrypts a database file and sets password.
It runs only if the new database file is created. The old one not encrypted fails when is opened with this method.
I know this is an old question but wouldn't the simple solution be to just protect the file at the OS level? Just prevent the users from accessing the file and then they shouldn't be able to touch it. This is just a guess and I'm not sure if this is an ideal solution.
Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.

Grab image from web, save it in sql database

I'm trying to grab an image from the web, and add it to my database.
String lsResponse = string.Empty;
using (HttpWebResponse lxResponse = (HttpWebResponse)req1.GetResponse())
{
using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
{
Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
using (FileStream lxFS = new FileStream(id + ".png", FileMode.Create))
{
lxFS.Write(lnByte, 0, lnByte.Length);
My SQL Server datatype is Varbinary(MAX). Tried with different types (image,...) did not work.
Put it into database.
SqlCommand cmd = new SqlCommand("INSERT INTO PlayersDB (id) ) VALUES (#id);
cmd.Parameters.AddWithValue("#id", lnByte);
I keep getting an error:
Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
So, my program sees my lnByte not as binary?
First be sure about the data type is correct.I don't know much about SQL server but i've encountered similar problem in MySql. I changed the data type to Blob and it worked
We use blobs for storing images within a sql db at my workplace. I'm not particularly experienced with it myself, but here are some Technet resources that can explain it better than I can.
Binary Large Object (Blob) Data (SQL Server)
FILESTREAM (SQL Server)

C# OLEDB DBF Querying issue with codepage invalid data

Hello I'm trying to connect to a DBF and query it.
I use the following connectionstring:
string s = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.GetDirectoryName(this.ShapePathFileName) + "\\;Extended Properties=dBASE IV;User ID=Admin;Password=;";
Then I want to fill a datatable it the result:
oleDbDataAdapter = new OleDbDataAdapter(selectCommand);
((DbDataAdapter)oleDbDataAdapter).Fill(dataTable);
But I've in the results values like this:
"ÒoþÚ"
but in the file I've this:
"ãoçé"
also if in the SQL statement I've WHERE name like '%é' I get no results, but with WHERE name like '%Ú' I've results
any ideas how to fix this?
Try adding
Collate=YourDbCollation
or
CodePage=YourCodePage
in the query string.
Even better than that, try donwloading an usign
VIsual FoxPro OleDB Provider
You have lot of samples of how the new query string should look like:
Visual Fox Pro Connection Strings

Generating dBase II DBF File in C# 3.5

I'm generating dbf file to get imported to legacy systems that only accepts dBase II OR III. My aplication is .Net 3.5. I initially started working with this component VFPOLEDB.1 but it only generate dbf files in dBase V format which isn't backwards compatibily.
Anyone knows a component or driver to generate de dbf file in dBase II or III
Thanks
Try issuing a call to execute a script that opens the file, then does
COPY TO {some file} type FOX2X
that should get you the output...
There was another post of a similar all being done via C# through the VFPOleDB and I'll try to find it... Yup, and with credit to #DaveB here's a snippet of his post in Create .DBF in C# code that is readable from Excel (VFP or not)
string connectionString = #"Provider=VFPOLEDB.1;Data Source=C:\YourDirectory\";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand scriptCommand = connection.CreateCommand())
{
connection.Open();
string vfpScript = #"USE TestDBF
COPY TO OldDBaseFormatFile TYPE Fox2x
USE";
scriptCommand.CommandType = CommandType.StoredProcedure;
scriptCommand.CommandText = "ExecScript";
scriptCommand.Parameters.Add("myScript", OleDbType.Char).Value = vfpScript;
scriptCommand.ExecuteNonQuery();
}
}
The original post was for someone to be able to open the file in Excel format.
I remember trying to do this very thing several years ago and failing. My solution was to take an existing dBase II file, empty all data, and keep that empty file as a template for when I needed to create a new database.
ESRI's Shapefile format uses dBase III for storing attribute data. There's a decent implementation in the SharpMap project which you should be able to use independently (careful of the license, though: it's LGPL).
http://code.google.com/p/sharpmapv2/source/browse/trunk/SharpMap.Data.Providers/ShapeFileProvider/DbaseFile.cs

Categories

Resources