Password encryption in Delphi - delphi

I need to store database passwords in a config file. For obvious reasons, I want to encrypt them (preferably with AES). Does anyone know a Delphi implementation that is easy to introduce into an existing project with > 10,000 lines of historically grown (URGH!) source code?
Clarification: Easy means adding the unit to the project, adding max. 5 lines of code where the config file is read and be done with it. Should not take more than 15 minutes.
Another clarification: The password is needed in order to create a connection to the db, not to support a user management scheme for the application. So using hashes does not help. The db engine checks if the password is valid, not the app.

I second the recommendation for David Barton's DCPCrypt library. I've used it successfuly in several projects, and it won't take more than 15 minutes after you've read the usage examples. It uses MIT license, so you can use it freely in commercial projects and otherwise. DCPCrypt implements a number of algorithms, including Rijndael, which is AES.
There are many googlable stand-alone (single-unit) implementations too - the question is which one you trust, unless you are prepared to verify the correctedness of a particular library yourself.

For typical authentication purposes, you don't need to store the passwords, you only need to check if the password entered by the user is correct. If that's your case then you can just store a hash signature (e.g. MD5) instead and compare it with the signature of the entered password. If the two signatures match the entered password is correct.
Storing encrypted passwords may be dangerous because if someone gets your "master" password they can retrieve passwords of all your users.
If you decide to use MD5 you can use MessageDigest_5.pas which comes with Delphi (at least it's included with my copy of Delphi 2007). There are also other implementations with Delphi source code you can choose from.

I think Turbopower LockBox is an excellent library for criptography:
http://sourceforge.net/projects/tplockbox/
I don't know if it's too big for your uses but it is very easy to use and you can encrypt a string with 5 lines of code. It is all in the examples.

TOndrej has the right approach. You should never store a password using a reversible cypher. As it was correctly pointed out, if your "master" key were ever compromised, the entire system is compromised. Using a non-reversible hash, such as MD5, is much more secure and you can store the hashed value as clear text. Simply hash the entered password and then compare it with the stored hash.

I've always user Turbopower Lockbox. It works well, and very easy to use. I actually use it for exactly the same thing, storing a password in a config text file.
http://sourceforge.net/projects/tplockbox/

TurboPower LockBox 3 (http://lockbox.seanbdurkin.id.au/) uses automatic salting.
I recommend against Barton's DCPCrypt because the IV's are not salted. In some situations this is a very serious sercurity flaw.
Contrary to an earlier commment, LB3's implementation of AES is fully compliant with the standard.

I've used this library, really quick to add. But wiki shows few more solutions.

Even if you encrypt, it seems to me that your decryption key as well as the encrypted password will both be in your executable, which means that in no way is just security by obscurity. Anyone can take the decryption key and the encrypted passwords and generate the raw passwords.
What you want is a one-way hash.

Just a reminder.
If you don´t need to interoperate with others crypt libs, then DCP or LockBox would do the job.
BUT
if you need it to be fully compliant with the rinjdael specs, forget free components, they´re kinda "lousy" most of the time.

As others have pointed out, for authentication purposes you should avoid storing the passwords using reversible encryption, i.e. you should only store the password hash and check the hash of the user-supplied password against the hash you have stored. However, that approach has a drawback: it's vulnerable to rainbow table attacks, should an attacker get hold of your password store database.
What you should do is store the hashes of a pre-chosen (and secret) salt value + the password. I.e., concatenate the salt and the password, hash the result, and store this hash. When authenticating, do the same - concatenate your salt value and the user-supplied password, hash, then check for equality. This makes rainbow table attacks unfeasible.
Of course, if the user send passwords across the network (for example, if you're working on a web or client-server application), then you should not send the password in clear text across, so instead of storing hash(salt + password) you should store and check against hash(salt + hash(password)), and have your client pre-hash the user-supplied password and send that one across the network. This protects your user's password as well, should the user (as many do) re-use the same password for multiple purposes.

I reccomend using some type of salt. Do not store crypt(password) in config file, but insted of this store crypt(salt + password). As 'salt' you can use something that is required to open database, eg. db_name+user_name. For crypt function you can use some well known algortithm as AES, Idea, DES, or something as simple as xoring each byte with byte from some other string, that string will be your key. To make it more different to solve you can use some random bytes, and store them.
So to store:
init_str := 5 random bytes
new_password := salt + password // salt := db_name + user_name
crypted_password = xor_bytes(init_str + new_password, 'my keyphrase')
crypted_password := init_str + crypted_password
store crypted_password in config, as this will be bytes you can hexify or base64 it
And to connect:
split data read from config into init_str and crypted_password
new_password = xor_bytes(init_str + crypted_password, 'my keyphrase')
password := remove (db_name + user_name) from new_password

Nick is of course right - I just assume you know what you are doing when you say you want to spend all of 15 minutes on implementing a security solution. The DCPCrypt library also implements a number of hashing algorithms if you decide to go that (better) route.

A couple of solutions:
Don't store the password at all. If
the database supports integrated
authentication, use it. The process
can be set to run with a specific
identity, and be automatically
authenticated by the database
Use Windows certificate stores and a
certificate to encrypt your password.
If you store the key used to crypt
your password in your application,
you have very little security anyway,
you have to protect the key also.

You need to store it in a place where only the current user has acccess too.
Basically there are two ways to do this:
Store it in an EFS encrypted file.
Store it in the secure local storage.
Internet Explorer uses 2. But if you can get local access, you can decrypt both 1. and 2. if you have the right master key and algorithm (for instance, iepv can get at the Internet Explorer passwords).
So:
If you can, avoid storing passwords.
Look for alternatives (like Windows authentication, directory services, etc) first.
--jeroen

A simple but for most applications strong enough system is given by this Embarcadero's demo:
https://edn.embarcadero.com/article/28325

Related

How devise stores and read salts/hashes?

How does it work, that devise knows salts for encrypted passwords? Where does it store these hashes and how is that safe?
This is one of the main files for creating passwords: Devise::DatabaseAuthenticatable
Salt is not stored in the database, it is a string generated by this C program that is run by the BCrypt::Engine.generate_salt() function __bc_salt:
prefix = "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"
__bc_salt(prefix, cost, OpenSSL::Random.random_bytes(MAX_SALT_LENGTH))
This can be found here:
BCrypt::Engine
With some other interesting code here: BCrypt::Password
From what I can gather though, the salt itself is the 29 characters that appear after the third $ in the encrypted password. This alone cannot tell you the password though, since you also need to know the pepper which is based on your apps secret key (usually stored in your /config/initializers/secret_token.rb)
Conclusion: In order to decrypt a password, one would have to be using the right version of BCrypt, have obtained the secret token from the app, and have the encrypted password, and I think that at that point, user passwords are probably the least of your security concerns, so I think its pretty safe.

How to securely store user passwords for an external application?

I'm building an application with Rails and will be pulling timesheets from Harvest, a timetracking app. I'm using an API wrapper called harvested. To be able to interface with their API, I need to provide a subdomain, username and password.
Right now, I'm just storing the passwords as plain strings and have not done any encryption. Would like to encrypt them before storing in the DB. If I encrypt the passwords before storing, can I still use the encrypted password for authenticating with the Harvester API?
OAuth exists for this very reason. Storing plaintext is obviously a bad idea, but storing something encrypted that you then decrypt is ALSO a bad idea.
Modern password flows use one-way encryption: encrypting the password and then comparing it an already encrypted value in the database. This allows use of algorithms that can encrypt easily but are essentially impossible to decrypt. Using an algorithm that allows your application to easily decrypt database fields will also allow an attacker to do the same.
With a one-way flow (encryption only), even if a user gets ahold of your encrypted passwords, they are unusable since anything entered in the password box will be passed through the encryption again before testing for validity.
TL;DR
Use OAuth as someone else pointed out: https://github.com/harvesthq/api/blob/master/Authentication/OAuth%202.0.md

hashing user password for client / server application

I have an iPhone App communicating with a web server. When starting the App the user must authenticate with a user name and password.
The communication between the App and the web server is secured (HTTPS) but I don't want to send to the web server the clear password, I would like to send just the "signature" of the password (the signature will be stored in the database on the web server).
What is the best solution to create this "signature" on IOS? Should I use MD5 or something else?
Do I need to get an external library to build this signature or can it be done using SecKeyEncrypt from IOS SDK?
In the long term I will have an App running on Android and I must be able to generate the same signature for IOS and Android.
Thanks for your help,
Sébastien.
Transmitting the password in clear text is bad, so doing anything is a good first step. If you're going to make the effort, it is worth knowing how to do it right.
While MD5 is not a strong hashing algorithm anymore, choosing between MD5 and SHA256 (or even SHA512) is less important than how you use it. Let's ignore the specifics of the hashing algorithm and look at how it can be used first.
The idea of using a hash is that the hash of a string is always the same and is a one-way operation. By capturing the string, it is not supposed to be possible (or practical) to determine the password. That has become untrue in recent years with the mass use of rainbow tables. A rainbow table contains every possible password (up to a given length) and their hash, so that the attacker can use a reverse lookup to discover the password. Rainbow tables are readily available for all hash algorithms for passwords under 16 characters.
There are a few common solutions to this problem. One is to perform the hash many (around 1,000) times. The exact number of times must be known and predetermined by both the client and server so they can do it the same. This has the advantage and disadvantage of making hash generation expensive. It becomes computationally more difficult for an attacker to brute force, but rainbow tables are still useful if they are expanded to be large enough.
A better, but less common, solution is to add a known random string (commonly referred to as a Salt) to the password to make it long (maybe 64 characters). This salt must be known by both client and server in advance. This solution is cheap and easy, and it doesn't even matter if the salt is leaked out.
There is another common problem with password hashing. If a malicious user knows the hash of a user's password, that is as good as knowing the password itself for a poorly designed system. Let's assume we have an RPC function that requires a username and password hash. A malicious user that knows the password hash can submit it, even without knowing the password, and get access into the system. This known password hash will continue to work until the user changes their password, which could be months or years. What is needed is a way to limit the duration that the password hash is useful. That is achieved by using a dynamic salt.
The authentication then becomes a multi-step process.
The client connects to the server and presents some sort of client (or device) identifier, such as a UUID.
The server then generates a dynamic salt for that client identifier. The dynamic salt is only good for a short period of time (generally minutes to hours).
The server stores the dynamic salt, its expiration, and the associated client identifier in a database table for future use.
The server returns the dynamic salt back to the client, along with its expiration.
The client hashes the password, using either of the two mechanisms above, concatenates the dynamic salt, hashes again, and then attempts to authenticate by using username, client identifier, and dynamically-salted hash.
The server validates the submitted credentials by checking the users known password hash against the submitted value trying to concatenate and hash each known dynamic salt for that client identifier. If a match is found, authentication is accepted.
This is (roughly) the mechanism that is used by MySQL. It is secure enough that it can be used without SSL safely, but I would always recommend using SSL so that the rest of the payload is protected.
If you use secure mechanisms like this, it doesn't matter much if you use MD5 or a SHA variant. That said, it wouldn't make sense for any new development to not use SHA256, unless there was a very good reason MD5 was necessary.
md5 is not the best idea - there are lots of really fast rainbow tables nowdays to decrypt them.
I would suggest using AES256 - on iOS you have NSData+CommonCrypto which allows you to easily do that.
NSString* encryptionPass = #"myEncryptionPass";
NSData* passData = [userPassword dataUsingEncoding:NSStringEncodingConversionAllowLossy];
NSError* error = nil;
NSData* encryptedPassData = [passData AES256EncryptedDataUsingKey:encryptionPass error:&error];
if(!error)
{
NSString* encryptedString = [[NSString alloc] initWithData:encryptedPassData encoding:NSUTF8StringEncoding]
}

How should I store passwords locally for a multi-user application?

I want to create a multi-user application, but I don't know how to save and read encrypted passwords.
procedure SavePass(Password: WideString);
var
Pass: TIniFile;
begin
Pass := TIniFile.Create(ChangeFileExt(Application.ExeName, '.PASS'));
Pass.WriteString('Users', 'USERNAME', Password);
Pass.Free;
The passwords must be stored on the computer.
This works but it's stupid to save passwords using this.
Hashing passwords would be also good.
If the connecting software accepts hashed passwords, it's not going to stop people who steal the hashed passwords from connecting. All it will do is hide what the real password is.
Furthermore, if the software that you're connecting to does not accept hashed passwords (database, website, ...), you're going to have to store your password in such a way that you can get it back to its original state. A hashed version is not going to help you there.
If you want to scramble your storage so that humans cannot read the file, you could use Windows.EncryptFile() and Windows.DecryptFile(). In newer Delphi's that's neatly wrapped into IoUtils.TFile.Encrypt() and IoUtils.TFile.Decrypt.
If you really want to stop others from reading the cleartext version of your password, you're going to have to use some encryption with a key. Where do you store that key then?That would defeat the whole purpose of storing a password in the first place. It's better to prevent access by other users by using user privileges to the file system for example, because anything you or your software can do, a "hacker" can do if he has the same privileges.
My suggestion is to not use passwords in your application at all, unless you really need to. The user experience of having yet another password to enter & remember is usually not needed.
What I do for my applications is default to using the domain and user name of the current user as the identification. The user has already logged on with a password, or more secure system if they want it. Only by logging on can they be that current user. My server then accepts that as their identification.
Variations on this include optionally passing the machine name too, so that the same user is treated differently on different computers (when they need to use more than once computer at once). And of course you can still allow a normal password if you want to.
You should store hashed passwords. For example you could use one of the SHA algorithms from the Delphi Cryptography Package. When you check passwords hash the password that the user supplies and compare against that saved in the file.
Have you considered using Windows security rather than attempting to roll your own?
As an aside, you are liable to encounter problems writing to your program directory if your program resides under the program files directory and UAC is in use.
There are hash and encryption routines in Lockbox. You should hash the password concatenated with a random 'salt' and store the salt and hash together. To make it harder for people to brute-force the hash - trying all likely passwords until the right one is found - you should iterate the hash. When the user subsequently enters their password to login take the salt from your store and hash it with their entered password, and iterate, and test the result against the hash you have stored. If they are the same they have given the correct password.
As long as you can, don't store password, but hash them properly (use a salt, repeat hash n times, etc.) because rainbow table attacks are feasible and work well against poor chosen passwords and too simple hashing.
If possible, take advantage of "integrated security". Use Windows authentication to avoid storing passwords.
If you really need to store a master password or the like, use Windows APIs like CryptProtectData to protect them locally.
I think its best to keep user-specific settings in the Registry under HKEY_CURRENT_USER. That will keep their settings all together and separate from other users' settings.
You'll automatically read the correct user's settings when you read from this area of the Registry, and you should store your password there as well. Yes, do encrypt it as David recommends. The Registry is easy for anyone to read using RegEdit.
Here's an article on how you can write to and read from the registry.

Rails database - how to store encrypted data using the user's password?

I have a database that will be holding sensitive data, so it should be encrypted in the database. Basically the sensitive data are credentials to another web site. So I want to encrypt them with the users password + salt.
To decrypt the credentials one would need the password.
I see two ways:
On login, I could decrypt the credentials, and then store them in the session? Is that safe?
OR
Harder on the user would be to ask again for the password before decrypting the stored passwords/ids?
We don't want to have any ability to use the stored credentials ourselves.
I highly recommend "Security on Rails" for this. It's a tricky topic, so you'll need to spend some time reading up in order to get it right. They cover exactly this topic, including how to salt the encrypted data, unit test to make sure it is encrypted, and more.
Their sample code shows how to add class methods to ActiveRecord::Base so that you can make any database column encrypted in one line of code. Definitely an idiomatic Rails approach.
It's an awesome read - the unit tests blew me away, so seriously ... go get it.
By the way, when you said
We don't want to have any ability to
use the stored credentials ourselves.
you realize that because your code receives the unencrypted data from the user's browser, you do have access to the data in memory before it is encrypted on disk, or when it is unencrypted when the user wants to use that data later. And bad people could get access to that data if they root your box, sneak something into a Ruby eval(), etc.
Encrypting the data does help a lot, though. SQL injection attacks can't get the decrypted data, for example.

Resources