How to open a file with the .db extension of SQLite database?
I have downloaded a DB Browser For SQLite.
When I tried opening the database file, a new window popped up which is 'Titled SQLCipher Encryption' asking a password used to encrypt and file size (Confused With What Exactly 'File Size'..?).
I have an Application Source Code that I Managed To Find Password & tried with default Page Size 1024.
Tried Several times but unable to open.
public void ReadRecord(string sql)
{
try
{
this.sqlite_cmd.CommandText = this.cSql;
this.sqlite_datareader = this.sqlite_cmd.ExecuteReader();
if (this.sqlite_datareader.Read())
{
this.sAddEdit = "E";
this.txt1.Tag = this.sqlite_datareader["id"];
this.txt1.Text = this.sqlite_datareader["f0"].ToString();
this.txt2.Text = this.sqlite_datareader["f1"].ToString();
this.txt3.Text = this.sqlite_datareader["f2"].ToString();
this.txt4.Text = this.sqlite_datareader["f3"].ToString();
this.txt5.Text = this.sqlite_datareader["f4"].ToString();
this.dtpListDate.Text = this.sqlite_datareader["f5"].ToString();
this.txt7.Text = this.sqlite_datareader["f6"].ToString();
this.txt8.Text = this.sqlite_datareader["f7"].ToString();
this.txt9.Text = this.sqlite_datareader["f8"].ToString();
this.txt10.Text = this.sqlite_datareader["f9"].ToString();
this.txt11.Text = this.sqlite_datareader["f10"].ToString();
this.txt12.Text = this.sqlite_datareader["f11"].ToString();
this.txt13.Text = this.sqlite_datareader["f12"].ToString();
this.txt14.Text = this.sqlite_datareader["f13"].ToString();
this.txt15.Text = this.sqlite_datareader["f14"].ToString();
this.txt16.Text = this.sqlite_datareader["f15"].ToString();
this.txt17.Text = this.sqlite_datareader["f16"].ToString();
this.txt18.Text = this.sqlite_datareader["f17"].ToString();
this.txt19.Text = this.sqlite_datareader["f18"].ToString();
this.txt20.Text = this.sqlite_datareader["f19"].ToString();
this.txt21.Text = this.sqlite_datareader["f20"].ToString();
this.txt22.Text = this.sqlite_datareader["f21"].ToString();
this.txt23.Text = this.sqlite_datareader["f22"].ToString();
this.txt24.Text = this.sqlite_datareader["f23"].ToString();
this.txt25.Text = this.sqlite_datareader["f24"].ToString();
this.txt26.Text = this.sqlite_datareader["f25"].ToString();
this.txt27.Text = this.sqlite_datareader["f26"].ToString();
this.txt28.Text = this.sqlite_datareader["f27"].ToString();
this.txt29.Text = this.sqlite_datareader["f28"].ToString();
this.txt30.Text = this.sqlite_datareader["f29"].ToString();
}
this.sqlite_datareader.Close();
}
catch (Exception exception)
{
MessageBox.Show("A Error" + exception.ToString() + " Occcured Please Try Again or contact supplier", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
In namespace,
using Microsoft.VisualBasic.PowerPacks;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
1. regarding your question about page size,
please refer to SQLite Database file Format
1.3.2. Page Size
The two-byte value beginning at offset 16 determines the page size of the database. For SQLite versions 3.7.0.1 (2010-08-04) and earlier, this value is interpreted as a big-endian integer and must be a power of two between 512 and 32768, inclusive. Beginning with SQLite version 3.7.1 (2010-08-23), a page size of 65536 bytes is supported. The value 65536 will not fit in a two-byte integer, so to specify a 65536-byte page size, the value at offset 16 is 0x00 0x01. This value can be interpreted as a big-endian 1 and thought of as a magic number to represent the 65536 page size. Or one can view the two-byte field as a little endian number and say that it represents the page size divided by 256. These two interpretations of the page-size field are equivalent.
You can check the size of the database by using the ".dbinfo" command in an ordinary sqlite3.exe command-line shell program. The first info is the size
database page size: 4096
2. Regarding db decryption
Assuming the db is encrypted and you have the right passwords, (does it start with x' or 0x?, have you managed to open the db manually using the DB Browser app?), you'll have to decrypt the db before being able to read it. please refer SQLite Encryption Extension Documentation in order to learn more about the SQLite encryptions (& decryptions).
I suggest to use some opened source written cipher. just google it up and see which one is comfortable for you to work with. here's an example cipher that might be good for your needs
Related
I am writing a Windows Service using C# and .Net 4.6. The service is configured such that it runs perpetually by sleeping for a configurable period of time, before running and performing some tasks. As part of the initial start-up, the service goes and gets a list of connection strings so it can connect to a list of database servers and gather some information. I want to be able to persist the connection strings in memory. The idea is that the service grabs the connection strings on startup and holds them in memory until the service stops. Next time it starts it goes and grabs them again. This has led me down the path of encrypting the connection strings as some may contain username/password combinations.
So What I have tried to do it create a class to store this information, and handle the encryption/decryption of the connection string on the fly with the get and set properties.
Note: I have hard-coded a length of the byte array to 1024, but this should probably be dynamically adjusted to the nearest 16.
using System;
using System.Text;
using System.Security.Cryptography;
namespace XXXXXXX.DB
{
public class Instance
{
private byte[] _connectionString = new byte[1024];
System.Text.ASCIIEncoding ae = new ASCIIEncoding();
public string Name { get; set; }
public string ConnectionString
{
set
{
if (value.Length < _connectionString.Length)
value = value.PadRight(_connectionString.Length, ' ');
else
value = value.Substring(0, _connectionString.Length);
_connectionString = ae.GetBytes(value);
ProtectedMemory.Protect(_connectionString, MemoryProtectionScope.SameProcess);
}
get
{
ProtectedMemory.Unprotect(_connectionString, MemoryProtectionScope.SameProcess);
return ae.GetString(_connectionString).Trim();
}
}
}
So I set the ConnectionString property on an Instance object and it is encrypted as I expect. But when I access the unencrypted ConnectionString, the result is still encrypted:
using (SqlConnection connection = new SqlConnection(_theInstance.ConnectionString))
I think this is the fact that the private member variable for ConnectionString is a byte array which is a reference type? To be honest I'm scratching my head a bit on this.
Please note I've looked at many, many examples that make a simple console app and do the encryption and unencrypted all in the same method - but can it be done as I'm trying to do?
This question already has answers here:
How do I get a unique identifier for a machine running Windows 8 in C#?
(4 answers)
Closed 8 years ago.
How do I uniquely identify a surface(tablet)? How do I get id of a tablet? there is a way using `HardwareIdentification.GetPackageSpecificToken(null). The problem is, it changes for simple hardware changes like disabling bluetooth. Is there a way to get unique id for a tablet which never changes?
You can use HardwareIdentification.GetPackageSpecificToken(null), see http://msdn.microsoft.com/en-us/library/windows/apps/jj553431.aspx
That function gives you a lot of information, that you can filter as you like. For example:
using System.Runtime.InteropServices.WindowsRuntime;
public static string GetMachineId()
{
var hardwareToken =
HardwareIdentification.GetPackageSpecificToken(null).Id.ToArray();
var count = hardwareToken.Length / 4;
ulong id = 0ul;
for (int i = 0; i < count; i++)
{
switch (BitConverter.ToUInt16(hardwareToken, i * 4))
{
case 1:
// processor
case 2:
// memory
case 9:
// system BIOS
id = (id << 12) ^ BitConverter.ToUInt16(hardwareToken, i * 4 + 2);
break;
}
}
return Convert.ToBase64String(BitConverter.GetBytes(id));
}
However, bear in mind that this function, and the underlying API, cannot guarantee absolute uniqueness across all the machines connected to the internet. You would typically combine this with information about the user.
Another option is to generate and store a GUID in local (non-roaming) storage, and use that as your machine id. Depending in you exact needs, this may be a better solution.
UPDATE
The Guid method is fairly simple. Just generate a new Guid the first time the app is run using
Guid installationId = Guid.NewGuid();
Then store that in a local file using
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"installationId",
CreationCollisionOption.FailIfExists);
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
await fileStream.WriteAsync(installationId.ToByteArray(), 0, 16)
await fileStream.FlushAsync();
}
On subsequent runs, you detect that the file is there and read it.
A possible disadvantage of this method is that, when the application is uninstalled and subsequently reinstalled, a new GUID will be generated.
I'm trying to communicate between C# and C++ with varying amounts of success.
I am able to send a message between the two using reply/request, but the doubles that I am receiving are not correct.
For debugging purposes and understanding, I am currently running the following:
Clrzmq 3.0 rc1, Google ProtocolBuffer 2.5, Protobuf-csharp-port-2.4, ZeroMQ-3.2.3
.Proto
package InternalComm;
message Point
{
optional double x = 1;
optional double y = 2;
optional string label = 3;
}
server.cpp (the relevant part)
while (true) {
zmq::message_t request;
// Wait for next request from client
socket.recv (&request);
zmq::message_t reply (request.size());
memcpy ((void*)reply.data(), request.data(), request.size());
socket.send(reply);
}
client.cs (the relevant part)
public static Point ProtobufPoint(Point point)
{
Point rtn = new Point(0,0);
using (var context = ZmqContext.Create())
{
using (ZmqSocket requester = context.CreateSocket(SocketType.REQ))
{
requester.Connect("tcp://localhost:5555");
var p = InternalComm.Point.CreateBuilder().SetX(point.X).SetY(point.Y).Build().ToByteArray();
requester.Send(p);
string reply = requester.Receive(Encoding.ASCII);
Console.WriteLine("Input: {0}", point);
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(reply);
var message = InternalComm.Point.ParseFrom(bytes);
rtn.X = message.X;
rtn.Y = message.Y;
Console.WriteLine("Output: {0}", rtn);
}
}
return rtn;
}
On the C# side, Point is a very simple struct. Just x and y properties.
Here is what I'm getting from my unit tests as a result of running the above code.
Input (1.31616874365468, 4.55516872325469)
Output (0.000473917985115791, 4.55516872323627)
Input (274.120398471829, 274.128936418736)
Output (274.077917334613, 274.128936049925)
Input (150.123798461987, 2.345E-12)
Output (145.976459594794, 1.11014954927532E-13)
Input (150, 0)
Output (145.96875, 0)
I am thinking that the problem is my protobuf code is incorrect (doubtful this is a bug on Skeet's side). I am also running under the assumption that server.cpp is doing nothing to the message but returning it as is.
Thoughts?
The requestor.Receive(Encoding.ASCII) call is designed to receive a string, not a block of bytes. You are asking the ZmqSocket instance to return the message as an ASCII string, which is highly likely to cause modifications to the content. If you're sending a byte array, receive a byte array.
Try this:
int readSize;
byte[] reply = requester.Receive(null, out readSize);
var message = InternalComm.Point.ParseFrom(reply);
The readSize variable will contain the actual number of valid bytes in the received block, which may vary from the size of the reply array, so you may need to slice up the array to make it palatable to ProtoBuf.
Why the ASCII --> bytes --> parsing step? If you're parsing bytes, you should read bytes. If you're parsing text, you should read that.
Unnecessary charset-conversions look very likely to be erroneous.
Since I really don't get any progress in the last hours I need to consult you for a problem which I don't get solved.
We have a Win CE 5.0 application, written C#/Compact Frmaework 2.0 that uses RASDial to Dial into a VPN. Currently it uses PPTP but I have to change it to L2TP with a Pre Shard Key. But to be honest I have no experience in C++ and I really understand only half of the code or to be more clear I don't understand the RAS Api and Documentation in the MSDN.
I understand how to create this L2PT RAS Entry and how to Dial it but in no way I understand where and how to set the Pre Shared Key!
I found a peace of code that seems to do the same things our code does in priciple but on the Website/Board I found it the Author says this is with pre shared key but to be honest, I don't get where the key is.
(...)
// Device configuration for L2TP VPN
if (bIsL2TP) {
DWORD cbKey = 0;
if (g_sharedKey) {
cbKey = (wcslen(g_sharedKey))*sizeof(WCHAR);
}
pL2TPConfigData = (PL2TP_CONFIG_DATA)new BYTE
[sizeof(L2TP_CONFIG_DATA)+ cbKey];
ZeroMemory(pL2TPConfigData, sizeof(L2TP_CONFIG_DATA)+ cbKey);
pL2TPConfigData->dwVersion = 1;
pL2TPConfigData->dwAuthType = L2TP_IPSEC_AUTH_PRESHAREDKEY;
pL2TPConfigData->dwFlags = 0;
pL2TPConfigData->cbKey = cbKey;
pL2TPConfigData->dwOffsetKey = sizeof(L2TP_CONFIG_DATA);
pL2TPConfigData->cMyCerts = 0;
pL2TPConfigData->cRootCerts = 0;
pL2TPConfigData->dwOffsetCertHashes = sizeof(L2TP_CONFIG_DATA);
if (g_sharedKey) {
memcpy((PBYTE)pL2TPConfigData+pL2TPConfigData->dwOffsetKey,
g_sharedKey, cbKey);
}
pConfigData = (PBYTE)pL2TPConfigData;
cbConfigData = sizeof(L2TP_CONFIG_DATA) + cbKey;
}
(...)
// Create a new phone-book entry.
res = ::RasSetEntryProperties(NULL, g_entryName, &rasEntry, sizeof
(rasEntry), pConfigData, cbConfigData);
if (res != 0) {
wprintf(L"Cannot create or update the phone book entry (error# %u).
Aborting.", res);
goto exit;
}
In the code the Length (cbKey) of the key is determined but can someone explain to me where the actual key is in the code? Or can someone provide me an explaination on how to set a Pre Shared Key in RASEntry for L2TP?
Thank you so much
twickl
The pre-shared key is copied into the L2TP_CONFIG_DATA structure with this line:
memcpy((PBYTE)pL2TPConfigData+pL2TPConfigData->dwOffsetKey, g_sharedKey, cbKey);
Basically this line says "copy the data from g_sharedKey into the pL2TPConfigData instance, starting at an offset of pL2TPConfigData->dwOffsetKey for a length of cbKey"
The code wraps this in an if block, so if g_sharedKey is NULL, it doesn't do this copy.
I have an issue where I need to be able to have a compiled exe ( .net 3.5 c# ) that I will make copies of to distribute that will need to change a key for example before the exe is sent out.
I cannot compile each time a new exe is needed. This is a thin client that will be used as part of a registration process.
Is it possible to add a entry to a resource file with a blank value then when a request comes in have another application grab the blank default thin client, copy it, populate the blank value with the data needed.
If yes how? If no do you have any ideas? I have been scratching my head for a few days now and the limitation as due to the boundaries I am required to work in.
The other idea I has was to inject the value into a method, which I have no idea how I would even attempt that.
Thanks.
Convert the assembly to IL, do a textual search and replace, recompile the IL to an assembly again. Use the standard tools from the .NET SDK.
Instead of embedding the key in the assembly, put it in the app.config file (or another file delivered with the application) and prevent your application from running if the key is not present and valid. To protect it against modification by users, also add an RSA signature the config file.
This code could be used to generate XML containing your key.
public static void Main()
{
Console.WriteLine(GenerateKey());
}
public static Byte[] Transform(Byte[] bytes, ICryptoTransform xform)
{
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
using (CryptoStream cstream = new CryptoStream(stream, xform, CryptoStreamMode.Write))
{
cstream.Write(bytes, 0, bytes.Length);
cstream.Close();
stream.Close();
return stream.ToArray();
}
}
}
public static string GenerateKey()
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
// This is the private key and should never be shared.
// Generate your own with RSA.Create().ToXmlString(true).
String rsaPrivateKey = "<RSAKeyValue><Modulus>uPCow37yEzlKQXgbqO9E3enSOXY1MCQB4TMbOZyk9eXmc7kuiCMhJRbrwild0LGO8KE3zci9ETBWVVSJEqUqwtZyfUjvWOLHrf5EmzribtSU2e2hlsNoB2Mu11M0SaGd3qZfYcs2gnEnljfvkDAbCyJhUlxmHeI+35w/nqSCjCk=</Modulus><Exponent>AQAB</Exponent><P>4SMSdNcOP0qAIoT2qzODgyl5yu9RubpIU3sSqky+85ZqJHXLUDjlgqAZvT71ROexJ4tMfMOgSWezHQwKWpz3sw==</P><Q>0krr7cmorhWgwCDG8jmzLMo2jafAy6tQout+1hU0bBKAQaPTGGogPB3hTnFIr84kHcRalCksI6jk4Xx/hiw+sw==</Q><DP>DtR9mb60zIx+xkdV7E8XYaNwx2JeUsqniwA3aYpmpasJ0N8FhoJI9ALRzzp/c4uDiuRNJIbKXyt6i/ZIFFH0qw==</DP><DQ>mGCxlBwLnhkN4ind/qbQriPYY8yqZuo8A9Ggln/G/IhrZyTOUWKU+Pqtx6lOghVdFjSxbapn0W8QalNMFGz7AQ==</DQ><InverseQ>WDYfqefukDvMhPHqS8EBFJFpls/pB1gKsEmTwbJu9fBxN4fZfUFPuTnCIJsrEsnyRfeNTAUFYl3hhlRYZo5GiQ==</InverseQ><D>qB8WvAmWFMW67EM8mdlReI7L7jK4bVf+YXOtJzVwfJ2PXtoUI+wTgH0Su0IRp9sR/0v/x9HZlluj0BR2O33snQCxYI8LIo5NoWhfhkVSv0QFQiDcG5Wnbizz7w2U6pcxEC2xfcoKG4yxFkAmHCIkgs/B9T86PUPSW4ZTXcwDmqU=</D></RSAKeyValue>";
rsa.FromXmlString(rsaPrivateKey);
String signedData = "<SignedData><Key>Insert your key here</Key></SignedData>";
Byte[] licenseData = System.Text.Encoding.UTF8.GetBytes(signedData);
Byte[] sigBytes = rsa.SignData(licenseData, new SHA1CryptoServiceProvider());
String sigText = System.Text.Encoding.UTF8.GetString(Transform(sigBytes, new ToBase64Transform()));
System.Text.StringBuilder sb = new StringBuilder();
using (System.Xml.XmlWriter xw = System.Xml.XmlTextWriter.Create(sb))
{
xw.WriteStartElement("License");
xw.WriteRaw(signedData);
xw.WriteElementString("Signature", sigText);
xw.WriteEndElement();
}
return sb.ToString();
}
Example output from this code:
<?xml version="1.0" encoding="utf-16"?>
<License>
<SignedData>
<Key>Insert your key here</Key>
</SignedData>
<Signature>cgpmyqaDlHFetCZbm/zo14NEcBFZWaQpyHXViuDa3d99AQ5Dw5Ya8C9WCHbTiGfRvaP4nVGyI+ezAAKj287dhHi7l5fQAggUmh9xTfDZ0slRtvYD/wISCcHfYkEhofXUFQKFNItkM9PnOTExZvo75pYPORkvKBF2UpOIIFvEIU=</Signature>
</License>
Then you can use code like this to verify it. You never have to distribute the private key:
public static Boolean CheckLicenseSignature(String licXml)
{
try
{
System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.LoadXml(licXml);
String licSig = xd.SelectSingleNode("/License/Signature").InnerText;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
String rsaPublicKey = "<RSAKeyValue><Modulus>uPCow37yEzlKQXgbqO9E3enSOXY1MCQB4TMbOZyk9eXmc7kuiCMhJRbrwild0LGO8KE3zci9ETBWVVSJEqUqwtZyfUjvWOLHrf5EmzribtSU2e2hlsNoB2Mu11M0SaGd3qZfYcs2gnEnljfvkDAbCyJhUlxmHeI+35w/nqSCjCk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
rsa.FromXmlString(rsaPublicKey);
Byte[] licenseData = System.Text.Encoding.UTF8.GetBytes(xd.SelectSingleNode("/License/SignedData").OuterXml);
return rsa.VerifyData(licenseData, new SHA1CryptoServiceProvider(), Transform(System.Text.Encoding.UTF8.GetBytes(licSig), new FromBase64Transform()));
}
catch (System.Xml.XmlException ex)
{
return false;
}
catch (InvalidOperationException ex)
{
return false;
}
}
From within the capability of the .NET code itself, I'm not sure if this is doable. But it is possible to dynamically generate a .NET DLL which contains some key that can be referred from the main application. That is, if you wouldn't mind a second file in the distribution.
Or if you don't mind to use Ildasm to disassemble the .exe, change the key, then use Ilasm to reassemble, then you can do something to automate that.
The accepted answer is GARBAGE!
I HAVE DONE THIS SUCCESSFULLY. MUCH EASIER
Just put your base application (.net) that needs the key somewhere with a string resource FILLED WITH "XXXXXXXXXXXXXXX" (more than you'll need)
.Net resources are usually kept at the top of the code so you will find them fast skipping the first 100,000 bytes in my case.
Then you just read it in and look for those XXXXXX's. When you find them you replace them with the real API key and replace the rest of the X's with spaces you just trim off in code. This is the answer. It works and it works well.
ApiToken at = new ApiToken(UserId, SelectedCID);
at.MakeToken();
byte[] app = System.IO.File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "notkeyedapp.exe"));
for (int i = 100000; i < app.Length; i++)
{
if (app[i] == 0x58 && app[i + 1] == 0x58 && app[i + 2] == 0x58)
{
for (int j = 0; j < 128; j++)
{
if (at.Token.Length >= j + 1)
app[i + j] = System.Text.Encoding.ASCII.GetBytes(at.Token[j].ToString())[0];
else
app[i + j] = 0x20;
}
break;
}
}
string filename = "SoftwareProduct for - " + BaseModel.CompanyName.Replace(".", "") + ".exe";
return File(app, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
I don't think You can get away without recompiling Your .exe and having key embedded into said .exe. The compilation process can be automated though via use of ildasm.exe and ilasm.exe as Daniel Earwicker suggested in his response https://stackoverflow.com/a/2742902/2358659
I'd like to expand on that if anyone else stumbles across this topic in the future.
I recently was facing similar problem due to my poor source code version control habits. In a nutshell I had an executable that was supposed to write some data to a Google Spreadsheet by referencing it's ID. Long after executable was released came another request from a different team to use the tool, but it had to write same information into a different spreadsheet in order to keep data separate for two teams. At the time I did not have the original source code, hence I was not able to change the static variable holding the original spreadsheet ID. What I did was as follows:
Using CMD.exe → call "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\ildasm.exe" "myApplication.exe" /out="myApplication.il"
Using Notepad++ → Find and replace original ID to new ID inside myApplication.il file. This action can also be automated by writing own C# application to do this, or using PowerShell, or using vb/j-script or using some other find and replace tool available off-the-shelf, like FART (using CMD.exe → call fart.exe myApplication.il "OldKey" "NewKey")
Using CMD.exe → call "C:\Windows\Microsoft.NET\Framework\v4.0.30319\ilasm.exe" "myApplication.il" /res="myApplication.res" /key="myApplicationKeyFile.snk"
As You see, all of these steps can be put into one .bat file that takes "NewKey" as an input and produces new .exe with NewKey embedded.
I hope that helps.
What comes to my mind, but not tried yet: Create a default String in your program, for example as
static public string regGuid = "yourguidhere";
Then, search the compiled EXE with any decent hex editor. If you find the string, replace it with another test. If you still can execute the program, you could try to automate this process and voila! Here you are.