SQLite encryption in java using Hibernate - java

I am currently using hibernate-sqlite.
To access dynamically created sqlite databases, this works perfectly. Now I want to secure the sqlite files. After some research I found out the way to go is (AES) encryption. Can anyone explain to me if this is possible using hibernate? And If so, how? If this doesn't work, is there any other solution for securing the data in the files?

You know about SQLite's Encryption Extension, right?

You can use the built-in encryption of the sqlite (System.Data.SQLite). See more details at http://sqlite.phxsoftware.com/forums/t/130.aspx
You can also Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net
and as you need hibernate
you can 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.
EDIT :
more options for you
SEE - The official implementation.
wxSQLite - A wxWidgets style c++ wrapper that also implements SQLite's encryption.
SQLCipher - Uses openSSL's libcrypto to implement.
SQLiteCrypt - Custom implementation, modified API.
botansqlite3 - botansqlite3 is an encryption codec for SQLite3 that can use any algorithms in Botan for encryption.
The SEE and SQLiteCrypt require the purchase of a license.

Related

Android autofill service save request on sensitive data

I'm trying to give the user the option to save their passwords after registering on a website, using the autofill service provided by android.
List<FillContext> contexts = request.getFillContexts();
AssistStructure structure = contexts.get(contexts.size() - 1).getStructure();
ParsedStructure parsedStructure = ParsedStructure.parse(structure);
parsedStructure.getPasswordView().getText().toString()
This code is in the onSaveRequest method of Android's AutofillService.
When I log the last line, the text in the console only contains asterix characters and not the password itself. Does anyone have an idea why that is and an solution for that?
AS most of the browsers are in Compatibility mode and do not support the native autofill api yet.
Read more at the android documentation.

Accessing SecureString SSM parameters with Scala

I'm using a Scala Script in Glue to access a third party vendor with a dependent library. You can see the template I'm working off here
This solution works well, but runs with the parameters stored in the clear. I'd like to move those to AWS SSM and store them as a SecureString. To accomplish this, I believe the function would have to pull a CMK from KMS, then pull the SecureString and use the CMK to decrypt it.
I poked around the internet trying to find code examples for something as simple as pulling an SSM parameter from within Scala, but I wasn't able to find anything. I've only just started using the language and I'm not very familiar with its structure, is the expectation that aws-java libraries would also work in Scala for these kinds of operation? I've tried this but am getting compilation errors in Glue. Just for example
import software.amazon.awscdk.services.ssm.StringParameter;
object SfdcExtractData {
def main(sysArgs: Array[String]) {
print("starting")
String secureStringToken = StringParameter.valueForSecureStringParameter(this, "my-secure-parameter-name", 1); // must specify version
Gives a compilation error, although aws glue doesn't good job of telling me what the issue is.
Thank you for your time! If you have any code examples, insight, or resources please let me know. My job is running Scala 2 on Spark 2.4
was able to do this with the following code snippet
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClient
import com.amazonaws.services.simplesystemsmanagement.model.GetParameterRequest
import com.amazonaws.services.simplesystemsmanagement.model.GetParameterResult
// create a client AWSSimpleSystemsManagementClient object
val client = new AWSSimpleSystemsManagementClient()
// Create a GetParameterRequest object, which send the actual request
val req = new GetParameterRequest()
// set the name of the parameter in the object.
req.setName("test")
// Only needed if the parameter is a secureString encrypted with the default kms key. If you're using a CMK you need to add the glue user as a key user. To do so, navigate to KMS console --> Customer Managed Keys --> Click on KMS key used for encryption --> Under Key policies --> Key user --> Add ( Add the Glue role )
req.setWithDecryption(true)
// call the getParameter() function on the object
val param = client.getParameter(req)
Remember to give your glue role iam permissions to ssm too!

Unable to validate passwordhash+salt created using php password_hash() using jBcrypt

We are migrating our authentication module from PHP to Java. Currently the password hash+salt is stored in the database using BCrypt algorithm. This value is generated by using PHP's password_hash() function. For validating plain text password, we are using PHP's password_verify() function.
PHP code
$hash = password_hash($password,PASSWORD_DEFAULT); //stored in db
if(password_verify($candidate,$hash)===TRUE) { //$hash fetched from DB
echo "valid";
}
For migrating this auth module to Java, we are using jBCrypt library by using jBCrypt-0.4.jar
Java code
private static String hashPassword(String password) {
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
return hashed;
}
private static boolean checkpasword(String candidate, String hashed){
boolean matches = false;
if (BCrypt.checkpw(candidate, hashed)){
matches = true;
}
return matches;
}
However, the passwordhash+salt generated from php is not being validated in java. For the string 'abcd' , the hash+salt generated is
PHP - $2y$10$SA4iLMAniuNO6p9P1ZJElePaJvlN5eHGZ2dDt2Mutle4FQr1OY4hC
Java - $2a$10$YnqJT5NPCPTI8qKBbLfgIOIOW4eckdbE1R85tJGNRUJKmxz1TLkWG
When I tried matching the string generated using PHP in Java using
if (BCrypt.checkpw("abcd", "$2y$10$SA4iLMAniuNO6p9P1ZJElePaJvlN5eHGZ2dDt2Mutle4FQr1OY4hC")){
matches = true;
}
I was getting the below
Exception in thread "main" java.lang.IllegalArgumentException: Invalid salt revision
at org.mindrot.jbcrypt.BCrypt.hashpw(BCrypt.java:665)
at org.mindrot.jbcrypt.BCrypt.checkpw(BCrypt.java:764)...`
How do I make both compatible ?
The hash generated by password_hash() in PHP includes the salt. Which means when you're checking it against the plain-text password, the same salt is used to generate a hash against the plain-text password, and the two hashes are compared in a constant time manner for verification.
What you're doing in Java is generating a different salt each time, which means you can't compare the two. Your Java implementation is using a different version, denoted by the $2a$ in your hash. Notice PHP is using $2y$ and the salts are clearly different.
From the PHP manual
Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to ยป this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".
So you shouldn't be generating a new hash in Java to validate the existing hash that was generated by PHP and stored in your database. Instead, supply the stored hash to BCrypt.checkpasword for validation.

Which hashing algorithm does .NET use and am I able to perform a password check on these hashes with java

I have a legacy webapplication built with ASP.NET 2.0. There is a user registration process implemented in this application and usernames and passwords are stored to a SQL Server database.The passwords are hashed as it was to expect. Although I am not a very experienced .NET programmer, I guess that the System.Security.Cryptography assembly does the job.
Now we want to reuse this user database for other services (basically a SAML Identity Proider would be ideal). I would like to use a combination of Mule ESB and Java Code to do this, but do I even have a chance to hash a password in java the same way .NET does and check this hash on my user database? Has anybody done this already?
EDIT: I have further investigated the legacy app. I created an 'Testuser' with the password 'stackoverflow'. In the database I have 2 fields, one named "Password" and one name "EncryptionToken".
For the credentials above 'stackoverflow' becomes
Password: F545C9A2670C9C261C657CC48AA8F91F284DD824B8142466DB7370FF4A30D741
SecurityToken: tn+nms4=
The code for persisting the user password looks like this:
public void SetEncryptedPassword(Account user, string password)
{
user.SecurityToken = CryptoProviderBase.GenerateRandomSalt();
var hash = new SHA256HashBuilder { Text = password, Salt = user.SecurityToken };
user.Password = hash.CalculateHash();
}
So the hash seems to be a SHA256 hash with a random salt which is stored in SecurityToken.
Unfortunately I am not able (dont have a clue) how to reproduce this in Java. Can you give me some hints?
I think I have solved it by myself just by deep investigating (decompiling) some code and think and try around. There is an online SHA-256 calculator I used for this.
If I type in the SecurityToken/Salt "tn+nms4=" first and appended the password "stackoverflow" to it. Hashing this then. I got exactly the hash which is stored in the database.
Looks like the implementation of the encrytion provider which is used in the legacy app isn't plain .NET at all but more likely something self crafted.

how to copy a schema in mysql using java

in my application i need to copy a schema with its tables and store procedures from a base schemn to a new schema.
i am looking for a way to implement this.
i looked into exacting the mysqldump using cmd however it is not a good solution because i have a client side application and this requires an instillation of the server on the client side.
the other option is my own implantation using show query.
the problem here is that i need t implement it all from scratch and the must problematic part is that i will need to arrange the order of the tables according to there foreign key (because if there is a foreign key in the table, the table i am pointing to needs to be created first).
i also thought of creating a store procedure to do this but store procedures in my SQL cant access the disk.
perhaps someone has an idea on how this can be implemented in another way?
You can try using the Apache ddlutils. There is a way to export the ddls from a database to an xml file and re-import it back.
The api usage page has examples on how to export schema to an xml file, read from xml file and apply it to a new database. I have reproduced those functions below along with a small snippet on how to use it to accomplish what you are asking for. You can use this as starting point and optimize it further.
DataSource sourceDb;
DataSource targetDb;
writeDatabaseToXML(readDatabase(sourceDb), "database-dump.xml");
changeDatabase(targetDb,readDatabaseFromXML("database-dump.xml"));
public Database readDatabase(DataSource dataSource)
{
Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
return platform.readModelFromDatabase("model");
}
public void writeDatabaseToXML(Database db, String fileName)
{
new DatabaseIO().write(db, fileName);
}
public Database readDatabaseFromXML(String fileName)
{
return new DatabaseIO().read(fileName);
}
public void changeDatabase(DataSource dataSource,
Database targetModel)
{
Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
platform.createTables(targetModel, true, false);
}
You can use information_schema to fetch the foreign key information and build a dependency tree. Here is an example.
But I think you are trying to solve something that has been solved many times before. I'm not familiar with Java, but there are ORM tools (for Python at least) that can inspect your current database and create a complementing model in Java (or Python). Then you can deploy that model into another database.

Categories

Resources