Downgrade sqlcipher encryption from 4 to 3 via cli

I have the latest sqlcipher installed on my system, and I use db with cipher default 4. I want to keep it as 4 so all my bash scripts go on working just fine.

I am trying to access this DB via php pdo, unfortunately the only driver I was able to get my hands on was to cipher 3.

The idea is to automate a bash script to open the original sql4 db and save it some place else with sql3 compatibility.

Is it possible to do that? If so, what are the commands I need to use once I open the db with “sqlcipher db4.db”?

Thank you in advance

Hello @genintel - you could use sqlcipher_export() for this:

https://www.zetetic.net/sqlcipher/sqlcipher-api/#sqlcipher_export

In conjunction, use cipher_compatibility to change the settings.

https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_compatibility

Thank you so much for the fast reply. I don’t know what I am doing wrong. It keeps encrypting the db as 4, even with cipher_compatibility. This is the script I am using. Am I doing something wrong?

#!/bin/bash

encrypted_db="enc.db"
decrypted_db="dec.db"
encrypted_new_db="new_enc.db"

password="mypass"

sqlcipher $encrypted_db <<EOF
PRAGMA key = '$password';
ATTACH DATABASE '$decrypted_db' AS decrypted KEY '';
SELECT sqlcipher_export('decrypted');
DETACH DATABASE decrypted;
EOF

echo "Database has been decrypted and saved as $decrypted_db"

sqlcipher $decrypted_db <<EOF
PRAGMA cipher_compatibility = 3;
ATTACH DATABASE '$encrypted_new_db' AS encrypted KEY '$password';
SELECT sqlcipher_export('encrypted');
DETACH DATABASE encrypted;
EOF

echo "Database has been encrypted and saved as $encrypted_new_db"

My version is:
3.42.0 2023-05-16 12:36:15 (SQLCipher 4.5.5 community)

Also tried with:
3.45.3 2024-04-15 13:34:05 64-bit) (SQLCipher 4.6.0 community)

I finally got this working.
I was missing the: PRAGMA encrypted.user_version = 3;
I’ll place the script I am using in case anyone needs it:

#!/bin/bash

encrypted_v4="original_v4.db"
encrypted_v3="newly_created_v3.db"
password="same_pass_for_both"

downgrade_db() {
sqlcipher $encrypted_v4 <<EOF
PRAGMA key = '$password';
ATTACH DATABASE '$encrypted_v3' AS encrypted KEY '$password';
PRAGMA encrypted.cipher_compatibility = 3;
SELECT sqlcipher_export('encrypted');
PRAGMA encrypted.user_version = 3;
DETACH DATABASE encrypted;
EOF
echo "Database $encrypted_v4 has been encrypted as v3 and saved as $encrypted_v3"
}

if [ -f "$encrypted_v3" ]; then
    echo "Deleting outdated database"
    rm "$encrypted_v3"
    downgrade_db
else
	downgrade_db
fi