How to decrypt an encrypted sqlcipher database file on command line? - encryption

The question is simple
What I have is:
I have a database file which is encrypted using sqlcipher.
I also have the passphrase which was used to encrypt this db file
What I need is:
I need to decrypt the database file/ need a database file which is unencrypted/non encrypted/decrypted.

Download and Build sqlcipher --Skip this if sqlcipher is already installed
Pull the code from https://github.com/sqlcipher/sqlcipher in a directory (say ~/sqlcipher)
mkdir ~/bld; # Build will occur in a sibling directory
cd ~/bld; # Change to the build directory
../sqlcipher/configure --enable-tempstore=yes CFLAGS="-DSQLITE_HAS_CODEC" LDFLAGS="-lcrypto";
#configure sqlcipher
make install; # Install the build products
Decrypt the database to a plaintext database
$ cd ~/;
$ ./sqlcipher encrypted.db
sqlite> PRAGMA key = 'testkey';
sqlite> ATTACH DATABASE 'plaintext.db' AS plaintext KEY ''; -- empty key will disable encryption
sqlite> SELECT sqlcipher_export('plaintext');
sqlite> DETACH DATABASE plaintext;
Find the decrypted database at ~/plaintext.db which you can use with any sqlite browser like this.
Update : September 2015
http://sqlitebrowser.org now supports sqlcipher databases. That's neat.

Use SQliteStudio
Select SQLiteCipher and enter the password.
The database will be opened.

This shell script will decrypt a SQLCipher database called mydb.db and create one called mydb-decrypt.db. Params are $1=key, $2, path to read & write from.
#!/bin/bash
echo "Decrypting $2 using key $1"
echo "PRAGMA key='$1';select count(*) from sqlite_master;ATTACH DATABASE '$2/mydb-decrypt.db' AS plaintext KEY '';SELECT sqlcipher_export('plaintext');DETACH DATABASE plaintext;" | sqlcipher $2/mydb.db
echo "Done."
If you wanted to do this in a single command line, the guts of this are:
echo "PRAGMA key='$1';select count(*) from sqlite_master;ATTACH DATABASE '$2/mydb-decrypt.db' AS plaintext KEY '';SELECT sqlcipher_export('plaintext');DETACH DATABASE plaintext;" | sqlcipher $2/mydb.db

Building on the previous answers , I have a comprehensive answer. I have the configuration- OS X version - 10.10.4
Steps :
1. Donwload and build OpenSSL code:
$ curl -o openssl-1.0.0e.tar.gz https://www.openssl.org/source/openssl-1.0.0e.tar.gz
$ tar xzf openssl-1.0.0e.tar.gz
$ cd openssl-1.0.0e
$ ./Configure darwin64-x86_64-cc
$ make
Download and build SQLCipher code.
In another directory,
$ git clone https://github.com/sqlcipher/sqlcipher.git
$ cd sqlcipher
Change '/path/to/libcrypto.a' in the following command to your path
$ ./configure --enable-tempstore=yes CFLAGS="-DSQLITE_HAS_CODEC" LDFLAGS="/path/to/libcrypto.a"
$ make
Decrypt to plaintext database (As illustrated in previous post by Vinay)
$ cd ~/;
$ ./sqlcipher encrypted.db
sqlite> PRAGMA key = 'testkey';
sqlite> ATTACH DATABASE 'plaintext.db' AS plaintext KEY ''; -- empty key will disable encryption
sqlite> SELECT sqlcipher_export('plaintext');
sqlite> DETACH DATABASE plaintext;
Tis should help you decrypt the encrypted file...

Related

How do I grant other users permission to write to SQLite database?

I faced a strange error related to permissions for a SQLite database.
I type in bash
rm -f test.db
sqlite3 test.db 'CREATE TABLE t (qwe, qqq)'
chmod 666 test.db
sudo -u another-user sqlite3 test.db 'INSERT INTO t VALUES (4, 2)'
It prints
Error: unable to open database file
It prints the same if I change an owner of test.db file to another-user.
But if I try to insert the record on behalf of root or me, there is no any
error, and it's inserted successfully.
What's the troubles?
An output of getfacl test.db is the following
# file: test.db
# owner: mymedia
# group: mymedia
user::rw-
group::rw-
other::rw-
AppArmor has no profiles related to SQLite, SeLinux is disabled. I was
experimenting on Ubuntu 16.04. The version of SQLite is 3.11.0.
Here the problem seems to be not with file permissions, but with directory. Check if a directory where your database file is placed has proper permissions for another-user.

Unable to copy postgresql table in another database

I try to copy postgresql table in another database as I write in pgAdmin 3 this query
$pg_dump -t pl_biz_enhanced business_catalog | psql business_catalog_enhanced
here pl_biz_enhanced is the table i want to copy and business_catalog is the database in which is this table
But I receive syntax error near $.
That's not an SQL query.
$pg_dump -t pl_biz_enhanced business_catalog | psql business_catalog_enhanced
The $ is a reference to the UNIX shell prompt, which usually ends in $.
This is a shell command. You can't run it in PgAdmin-III.
As far as I know there's no equivalent feature in PgAdmin-III. Either do the pg_dump | pg_restore in the command prompt or manually do the equivalent in PgAdmin-III, which would be to dump just the pl_biz_enhanced table of business_catalog and then restore it to the separate database business_catalog_enhanced.

how to take encrypted database backup in mysql

i am using mysql-5.5 and rhel5 and my intention is to use mysqldump to take the encrypted backup and compressed backup
as i am using mysqldump as below
mysqldump -u root -p db_name | gzip >file_name.sql.gz
it will give compressed backup but not encrypted one
How about this:
mysqldump -u root -p db_name | gpg --encrypt -r 'user_id' | gzip >file_name.sql.gz
of course you need the public key of the user that you want to encrypt for.
e.g.
gpg --import keyfile
Instead of using GPG which is frankly, kind of overkill unless you really like GPG, you can use OpenSSL which is likely built-in and has no real dependency structure for making easily portable and decryptable backups. This way you can readily decrypt the backup on just about any Linux system (and many other platforms) without any keyring, just knowing the passphrase.
Read more at this link about how do so.
Backup one database, change what is inside [..]
mysqldump -u root --single-transaction [DataBaseName] | gzip | openssl enc -pbkdf2 -k [MyPassword] > database.sql.zip.enc
Backup all databases separately:
date=`date "+%Y%m%d"`
for DB in $(mysql -u root -e 'show databases' -s --skip-column-names); do
mysqldump -u root --single-transaction $DB | gzip | openssl enc -pbkdf2 -k [MyPassword] > db-$DB-$date.sql.gz.enc;
done
Also note that using -p via command line is really bad practise as the password can be read out via ps aux.
I suggest using openssl as pgp is getting to slow on big files.
The best solution I have found so far which I am regularly using at work now is mysqldump-secure.
It offers openssl encryption and compression as well as other more features and even ships with a nagios monitoring plugin.
I use the following Bash script that uses Dropbox to sync the backups directly to our own company server (followed by automatic backups of that data). Replace the script variables with your own. Then I just add that to my crontab to run it every 12 hours.
FILENAME=dbname.$(date +%Y-%m-%d-%H-%M)
SQLFILE=/root/Desktop/$FILENAME.sql
ZIPFILE=/root/Desktop/$FILENAME.zip
GPGFILE=/root/Dropbox/SQL-Backups/$FILENAME.gpg
mysqldump --user=dbuser --password=password --port=3306 --default-character-set=utf8 --single-transaction=TRUE --databases "dbname" --result-file="$SQLFILE"
zip -9 $ZIPFILE $SQLFILE
gpg --output "$GPGFILE" --encrypt --recipient "recipient#company.com" "$ZIPFILE"
unlink $ZIPFILE
unlink $SQLFILE
This uses GnuPG to encrypt the resulting zipped SQL dump. Remember to never import the private key to the web server. The web server's GPG setup only needs the public key.
You can use the GPG software available for most platforms to create your key and publish the public key to a key server.

decrypt encrypted gpg file using external secret key

I encryptd a file using gpg, now I want to decrypt the file.
Is there any way to decrypt the file without need to import the secret file?
We have the secret key in a file called key.sec; can we pass the secret file to gpg as a parameter (when we run the decrypt command from the bash command line) to use when decrypting the encrypted file? Or must we import the secret key then decrypt the encrypted files?
You must add the secret key to a keyring. From the gpg(1) documentation:
--no-default-keyring
Do not add the default keyrings to the list of
keyrings. Note that GnuPG will not operate without any
keyrings, so if you use this option and do not provide
alternate keyrings via --keyring or --secret-keyring,
then GnuPG will still use the default public or secret
keyrings.
You could --import --no-default-keyring --secret-keyring temporary to import the key, use --secret-keyring temporary when decrypting the content, then delete the ~/.gnupg/temporary.gpg file when you're done. But that's just a work-around.
You have to import the secret key to use it but the way that secret keys are managed by GnuPG version 2.x has changed. There is a gpg-agent daemon that handles secret keys access and its use is mandatory from version 2.1.
Here is a way that you can quickly create a temporary keyring to decrypt with a secret key that is contained in a file:
$ mkdir -m 700 ~/.gnupg-temp
$ gpg --homedir .gnupg-temp --import key.sec
$ gpg --homedir .gnupg-temp -d an_ecrypted_file
If you want to clean up afterwards, stop the agent and remove the directory:
$ gpg-connect-agent --homedir .gnupg-temp KILLAGENT /bye
$ rm -r ~/.gnupg-temp
There used to be an option --secret-keyring about which the documentation for version 2.1 has this to say:
This is an obsolete option and ignored. All secret keys are stored in the private-keys-v1.d directory below the GnuPG home directory.
The private-keys-v1.d directory (wthin the --homedir or ~/.gnupg) is owned and operated by the agent.
The objective of the OP Mohammed appears to be keeping his PUBLIC and SECRET key apart. After all, do we want to keep the Secret key with the data it was used to encrypt? Thus, Mohammed's and 10,650+ others (at the time I write this) are interested in if/how it's possible. Indeed it is, and this is how you do it:
The publicly-facing host only has two keys: Both are Public Keys
Your GPG Public key used to encrypt data
Your SSH Public key in .ssh/authorized_keys to facilitate non-interactive logins.
Round-tripping an encrypted file using Public-Secret key separation:
The following bash snippet when executed on the host with the Secret Key will fetch the crypted file from the DMZ host via scp, and squirt the gpg decrypted standard output back onto the DMZ host into a file so it can be read/operated upon. This code is tested and known to work correctly:
echo "$(gpg -d $(scp myuser#192.168.1.10:/home/myuser/test-gpg.txt.asc .;ls ./test-gpg.txt.asc))" | ssh myuser#192.168.1.10 'cat > /home/myuser/test-gpg.txt'
Note that you will still be prompted for a password once decryption begins. But once the password is supplied, the script continues and injects the decrypted gpg stream into a file on DMZ host.
And don't forget to do an rm test-gpg.txt of the decrypted file once the operation that required it's contents to be readable has been completed.
So yes, very possible to keep your secret key apart from the publicly accessible host where encryption occurs and your secret key tucked safely away in a host outside of that DMZ. HTH- Terrence Houlahan

How to Export Private / Secret ASC Key to Decrypt GPG Files

Background: My boss has tried exporting an ASC key to me with public and private parts but whenever I get the file the private part never loads up and it won't decrypt any files.
We have tried Exporting the ASC Key using:
Windows Application Kleopatra 2.1 (included in gpg4win)
Windows Application GNU Privacy Assistant (included in gpg4win)
Error: "Decryption failed. Secret Key Not available."
How do you properly export a secret or private asc key to decrypt gpg files?
You can export the private key with the command-line tool from GPG. It works on the Windows-shell. Use the following command:
gpg --export-secret-keys
A normal export with --export will not include any private keys, therefore you have to use --export-secret-keys.
Edit:
To sum up the information given in my comments, this is the command that allows you to export a specific key with the ID 1234ABCD to the file secret.asc:
gpg --export-secret-keys --armor 1234ABCD > secret.asc
You can find the ID that you need using the following command. The ID is the second part of the second column:
gpg --list-keys
To Export just 1 specific secret key instead of all of them:
gpg --export-secret-keys keyIDNumber > exportedKeyFilename.asc
keyIDNumber is the number of the key id for the desired key you are trying to export.
All the above replies are correct, but might be missing one crucial step, you need to edit the imported key and "ultimately trust" that key
gpg --edit-key (keyIDNumber)
gpg> trust
Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)
1 = I don't know or won't say
2 = I do NOT trust
3 = I trust marginally
4 = I trust fully
5 = I trust ultimately
m = back to the main menu
and select 5 to enable that imported private key as one of your keys
See the treatment by Dark Otter
https://montemazuma.wordpress.com/2010/03/01/moving-a-gpg-key-privately/
If the site is down use reference the archive.org backup:
https://web.archive.org/web/20170518155052/https://montemazuma.wordpress.com/2010/03/01/moving-a-gpg-key-privately/
which includes a reasonably secure way to transfer keys. You could put that recommendation into shell-scripts shown below for repeated use.
First get the KEYID you want from the list shown by
$ gpg -K
From the resulting list note the KEYID (the 8 hexadecimals following sec) you need for transfer.
Then envoke the tested shell scipts "export_private_key" on the first account and generate your pubkey.gpg + keys.asc. Subsequently invoke on the second account "import_private_key". Here is their content shown with cat (copy & paste content):
$ cat export_private_key
gpg -K
echo "select private key"
read KEYID
gpg --output pubkey.gpg --export $KEYID
echo REMEMBER THE COMING PASS-PHRASE
gpg --output - --export-secret-key $KEYID | \
cat pubkey.gpg - | \
gpg --armor --output keys.asc --symmetric --cipher-algo AES256
ls -l pubkey.gpg keys.asc
#################### E X P O R T _ P R I V A T E _ K E Y #####################
Now tranfer by some means the "pubkey.gpg" (if needed) and the private "keys.asc" to the second account and envoke the below-shown program.
$ cat import_private_key
gpg --no-use-agent --output - keys.asc | gpg --import
################### I M P O R T _ P R I V A T E _ K E Y ######################
In Otter's spirit "And that, should be, that".
I think you had not yet import the private key as the message error said, To import public/private key from gnupg:
gpg --import mypub_key
gpg --allow-secret-key-import --import myprv_key
this ended up working for me:
gpg -a --export-secret-keys > exportedKeyFilename.asc
you can name keyfilename.asc by any name as long as you keep on the .asc extension.
this command copies all secret-keys on a user's computer to keyfilename.asc in the working directory of where the command was called.
To Export just 1 specific secret key instead of all of them:
gpg -a --export-secret-keys keyIDNumber > exportedKeyFilename.asc
keyIDNumber is the number of the key id for the desired key you are trying to export.
Similar to #Wolfram J's answer, here is a method to encrypt your private key with a passphrase:
gpg --output - --armor --export $KEYID | \
gpg --output private_key.asc --armor --symmetric --cipher-algo AES256
And a corresponding method to decrypt:
gpg private_key.asc
1.Export a Secret Key (this is what your boss should have done for you)
gpg --export-secret-keys yourKeyName > privateKey.asc
2.Import Secret Key (import your privateKey)
gpg --import privateKey.asc
3.Not done yet, you still need to ultimately trust a key.
You will need to make sure that you also ultimately trust a key.
gpg --edit-key yourKeyName
Enter trust, 5, y, and then quit
Source: https://medium.com/#GalarnykMichael/public-key-asymmetric-cryptography-using-gpg-5a8d914c9bca

Resources