Encrypt/ Decrypt text file in Delphi? - delphi

Hi i would like to know best encryption technique for text file encryption and ecryption.
My Scenario:
I have software having two type of users Administartor and Operators. Our requirement is to encrypt text file when Administrator enter data using GUI and save it. That encrypted file would be input for Operator and they just need to select it and use that file. Here file should be automatically decrypt data for further calculation when Operator select those files.
Please help me which encryption/ decryption technique should i use?

A golden rule when doing crypto is to understand that cryptography as a whole it is very difficult.
There are a multitude of different approaches/algorithms to choose from, and no single algorithm/method can be said to be the best one. It all depends on your needs and possibilities to affect application distribution etc.
An example of a potentially problematic situation is that in your scenario the decryption "key" needs to be distributed with the application(s) and might make it insecure. This is generally referred to as the "Key Distribution" problem.
A good place to start reading about crypto is http://en.wikipedia.org/wiki/Cryptography.
As for ready made stuff for Delphi there are a few good packages available:
DEC v5.2 - http://blog.digivendo.com/2008/11/delphi-encryption-compendium-dec-52-for-d2009-released/
DCPCrypt - http://www.cityinthesky.co.uk/cryptography.html
Torry's pages also has a long list of components:
http://www.torry.net/pages.php?id=519
http://www.torry.net/pages.php?id=312
I strongly recommend you use some of the existing implementations and not start to do your own, since creating a secure working crypto algo is very very difficult.

When moving an encryptet message from place/appliction to another, one of the problems you have to consider is where to store the encryption/decryption keys.
As i se your scenario, it seems like it is build in your applications. If so remember to use al sorts of tricks to hide it: Password strings should be split in several bits and onlys appended in a protected memoryspace, that has to be marked as non-pageable (else password could be seen in the pagefile).
The same rules for the content that is unencrypted (the text-file). It's best that it never is saved (even temporaly) unencrypted to disk. If it is saved, the overwrite the date with garbage after use, before deleting it.
Another approch (specialy if you already use compression components), is that the (text) file, can be compressed using a password.

Truthfully, there is no "best" technique. It basically depends on the sensitivity of the data you're trying to protect and the number of people who might access this data. What might be "best" for me might be pure overkill for your project.
In your case, you could use any dual-key encryption method. Or asymmetric key. Basically, the administrator has one key and the operator has the other. The administrator can then encrypt files, but he won't be able to decrypt them again, unless he has an operator key. The operator can decrypt the file and -if need be- encrypt a file that only an administrator can access. (Asymmetrical keys encrypt in both ways.)
There are several solutions that make use of these asymmetrical keys. The one that would be best is the one that you could add to your project in the easiest way while still offering enough protection for your needs.
Building your own asymmetrical key algorithm is possible too, if you're a real Math Wizard. The calculations are complex and involve extremely high prime numbers in most solutions. As K. Sandell said, find a good, existing solution that matches your needs in the best way.

Related

SpriteKit Level Data Security

I have been reading many different posts, threads, etc. regarding the best practices to store level data to be used throughout a game application (level boundary data, images, characters, time, etc.).
Many have suggested that using a Property List (.plist) is appropriate, as it is quite simple to store the game info then read it when needed. While this is easy to create and refer to, plist files are not exactly secure in any way, aside from simple AES encrypting the string contents.
Another method would be perhaps to hard code this data into a separate class file, titled LevelData.m and refer directly to the class to read the level data, as storing it this way should be "safer", as (from what I am aware of) users do not have direct or any access at all to these class files once an application has been packaged and distributed through, say the iOS App Store.
I have also read to use SpriteKit's built in NSCoding, where the data can be archived into a file (or NSData object) and later unarchived from that archive.
My question, can anyone suggest the best approach, or perhaps one that I haven't mentioned? YES, I understand they are all perfectly valid methods to saving big data, particularly non-trivial, and somewhat repetitive data that just needs to be read, and all have their pros and cons in terms of security measures. I am merely just trying to find the safest way to store this data without the user being able to tamper it in any way from other people who may have encountered a similar issue and have found the ideal solution.
NOTE: I'm sure that hosting this data server side and retrieving the data upon application launch would be the ideal secure approach. However, I am just looking to see which method should be the best practice in terms of security strictly through storing data on the device. Thanks!
If you are distrusting the users, how about signing the data which's integrity you distrust and validate the signature using public key encryption (with a pinned certificate in the binary)?
Thus, only data with a valid signature from you can be used.
Yet, after all, if a user dissembles your binary and modifies the public key, that doesn't work either.
As always with those problems, the question is: how hard are you making it for an adversary to break your security meassures - and what hardness is useful?
I know you got an answer already but I personally use a GameData Singleton class with NSCoding. I than save the encoded/archived data into iOSs Keychain (instead of NSUserDefaults, NSBundlePath etc).
To save into keychain you can use this helper
https://github.com/jrendel/SwiftKeychainWrapper
which is the one I use for my apps. Its works very similar to NSUserDefaults and is therefore very easy to use.
You can also get a more complex and feature rich one here.
https://github.com/matthewpalmer/Locksmith

What should an iOS/Mac library do about persisting a mix of sensitive/insensitive data?

I'm putting together an iOS/Mac library that I intend to open source. Part of the library vends data which client applications are likely to want to persist. The data is a mix of insensitive and sensitive. I've been trying to work out the best way to handle this divide. I've considered a few options, but they all involve trade offs I'm unhappy with. Are there any typical best practices for this situation?
Some background:
The class which stores this data is serializable via the NSSecureCoding protocol, but I only serialize the insensitive data.
Objects are still valid if the sensitive information goes missing, though clients of the library would need to take the user through an authentication process again.
Options I've considered:
Read and write to the keychain automatically in -initWithCoder: and -encodeWithCoder:. This puts the least burden on the client, but is arguably "surprising" behavior. I've largely rejected this option, but I'd be happy to be talked back into it.
Include an API to save and retrieve the sensitive information. This is what I currently have implemented and it works well for simple cases. It does put a burden on clients to remember to send these messages, though, which I find somewhat inelegant.
Include an API to serialize/deserialize the sensitive information in a form which the client can store in the keychain on its own. This puts the most burden on the client, and is even less elegant, but also provides the most flexibility in how the sensitive information is stored (keychain groups, etc). Of course it also allows client code to mishandle the sensitive information - but I'm not sure it's up to my library to enforce proper storage.
I implemented #1 first, switched to #2, and am currently mulling over switching to #3. I'm also sure there are other options I haven't considered. Is there an established best practice for this sort of thing (that I just haven't figured out the right search terms to find)?

How to generate a user registration key in Delphi?

For my current application I use a very simple scheme to register new users. When a new user registers an email is sent with a key. To check wether this key is correct a kind of checksum is computed (3-7-11 digit check) which is added as the last 2 digits of the key. There is no check on any further validity of the key. The application does not check whether the key got invalidated.
It is a simple scheme and someone took the time to crack it by deassembling the code. I want to use another scheme for my new application but I am not sure what is the best way to do this.
Is there a Delphi library I could use?
Is it advisable to use some user supplied info in the key, like his name?
Is there a best practice way of registering users?
Anything else I have forgotten?
Some registration schemes require an application to check each time at a webserver whether the key is still valid. I'd rather not go that far because this requires a lot of effort on the server side.
Any suggestion or link for a robust way to register new users is very welcome.
A better registration scheme is based on asymmetric cryptography (usually RSA algorithm). The idea is that only you can generate a valid key, while everybody can check that a key is valid (asymmetric cryptography allows this trick). So when you see your program with a valid key on torrents you just cancel support for a customer who was given this key.
There are Delphi and non-Delphi libraries (i.e Protexis) available to protect your software - remember that almost anything that works with C can work with Delphi as well. But a sound copy protection scheme may be hard to achieve. A simple key may not work, usually it used together a machine fingerprint to allow it to be used on given system only.
A good key generator algorithm should generate keys that are not easily predictable, yet can be checked if valid. There are different ones around, there is not a "generic" one, depends on your needs, some may also include what features to activate or expiry informations. Some keys can be strings, other can be whole license files (as those used by Delphi itself). Anyway code can be disassembled to try to guess the algorithm, some techniques to obfuscate it and make it harder to understand can be used.
Also, one simple key check is not enough because it can be easily bypassed patching the executable. If you really need copy protection, you should scatter checks all around the code, maybe encrypting and then decrypting data or code sections using the key - it won't protect you against keygen, anyway and will require more code changes, it's not as simple as calling one function at startup.
The level of protection is up to you. If you need just a simple registration mechanism and you don't mind much about your software being cracked you can use a simple one. If you need a more secure one then there are more sophisticated one.
If your goal is to force people to download a cracked EXE from the Internet instead of a key generator from the Internet, then asymmetric cryptography is your answer.
If your goal is to be able to void serial numbers that have been released to the wild, restrict the number of installations, or force the user to have a real "paid for" serial number, then activation is your answer. Still, if they crack your EXE, they can get around this.
You only have control up to the point that someone cracks your EXE. We have to accept this and move on. We must figure out other ways to reach out to our customers, such as more affordable versions, value added support options, web services, and other ways that convince the user that the price of our software is fair, and there is a benefit in paying.
On my latest release, I use activation, so the serial numbers are randomly generated, though checked for uniqueness, and associated with an email address.
After all of this, the application is just $4.99, but with no individual support. The goal is to make it so affordable that if they want to use it, even just once, it's a good value.
We've been using Oreans' WinLicense for two years and are quite happy with it. They handle key generation (with the user name embedded), trial versions that time-out, hardware keys (where the key you send them is unique for their computer) and VM detection. They also use a variety of other techniques to make it harder for your code to be disassembled, including wrapping code of your choice in an encrypted VM they provide.
You can also disable specific keys if you determine that they are "stolen." Having done this, future updates you supply will no longer run with those keys.
We also have our software "phone home" at certain times to see if their key is stolen.
Any protection scheme can be broken by someone who is determined and skilled enough. But, we've been happy with the degree of security we believe that WinLicense gives us. Their support is also excellent. The library is callable from Delphi.

Why should we not store the passwords or keys for encryption in source code for an iPhone App?

Why should we not store the passwords or keys for encryption in source code for an iPhone App?
Is there any possibility for people to reverse engineer code and find the stored keys? or if the hard code values are stored in a location which is easily accessible?
If you store keys in source code, yes they can be reverse engineered. You can make this even harder by making the key "generated" through a generator function but this is still an extra level of obfuscation. A really motivated attacker can get through that. Another drawback of this approach is that the same key will work on all instances of your application, unless the generator function generates a key deriving from some hardware constants.
Again, you have to do an analysis of how secure you want your application to be and how much effort you want to put into security. Security is always a trade off. It is not worthwhile to spend a lot of effort on security, when the probability or cost of an attack are extremely unlikely.
A more secure approach would be to create a random key and then store it in a secure storage on the device. I am not terribly familiar with the iOS Api and if such functionality is offered. On Windows there is something called DPAPI that provides this, for example.
Anything that gets into users' hands is accessible. Obfuscation of keys does part of the work, but doesn't eliminate the problem completely.

How to protect file system?

I want to store large files (videos, sounds) and access them via Database. I am balancing now between filesystem (references to files would be stored in DB) and pure DB (which could be enormously large after time).
I have to protect the content too, so I thought, that DB solution suits better for this purpose. (probably it is not a good idea).
On the other hand I have got hint to encrypt files to protect them, if I choose to use file system.
How should I do this?
P.S
please see the question What database should I choose not to worry about size limit?
P.P.S
Under protection I mean encrypt videofile/soundfile using a crypt algorithm. When the application need to read them, it have to decrypt files...
In that way the stolen files are useless unless appropriate decrypt algorithm is present.
I thought to use RAR secured with password. As far as I know it is very hard to break it, when password is long enough. (Maybe I am wrong).
I am not familiar about MD5....
I can not protect files against theft, but I want to prohibit to read it freely.
One approach would be to create a background process with an elevated security token that would it access a section of the filesystem only available to administrators and that process. On Windows you'd create a "service". They call it "daemon" on *nix, I believe.
That service could then expose an API via pipes, sockets, or a shared memory region where the unelevated, user-mode database tool could get and set files.
There's no way to completely prevent system administrators from accessing a file directly, so if that is a requirement, you're out of luck. On Windows administrators have a special privilege that allows them to take ownership of any securable item such as a file or directory. Once they're owners, they can do anything they want to the securable item. There's just no way around that.
I have implemented both approaches in different projects with different requirements and constraints. And I would strongly recommend to keep all the contents in the database, storing the media files in large blobs. Eventhough that will require very large tables, that should not be a problem for the latest versions of the most well known databases.
I recommend DB2. DB2 since version 9 supports very large tables. The maximum is monstrously large. 512000 petabytes, half a zettabyte.
You need to accept that the choice between storing the files in the database vs. in the file system ultimately doesn't matter much - in both scenarios they can be read trivially from outside, unless there is some encryption. That moves the problem from where to store the data to how to store the secret key to decrypt encrypted data, in your application.
This is a hard problem. There's probably nothing you can develop that can't be cracked by a determined attacker in a rather short time. It depends on the audience of your program whether that's a real concern; if it is, then you can't do much. It takes a single successful crack to access your data and make it accessible to all interested in it. The attacker will go for the weakest part, which isn't the hard-to-break file encryption, but your application.
Use a DB (firebird or -embedded) and keep large content out of it.
If it is encryption you are worrying about, do this at the filesystem level instead of the db level.
All modern OSes have support for encrypted filesystems
There are merits in both approaches.
If you want to have the files separately in the filesystem, I would encrypt each one individually. A password-protected RAR or ZIP file would be as good a method as any.
Use a different password/decryption key for each file, and store the password in the database along with each file name.
The following is suggested without knowing the specifics of your application.
As you mention that you can not protect against theft, just about the only option to make sure the multimedia files are safe (unusable) by anyone other than the "owner" you need to encrypt them using a cipher like AES or BlowFish and a secure secret Key. These algorithms are different from MD5 that you mention. MD5 is a HASH algorithm.
For Delphi a rather good encryption library is DCPcrypt forund at http://www.cityinthesky.co.uk/cryptography.html. If has both HASH and Cipher algorithms.
Your problem will be Cipher KEY Management, namely "What password to use for encryption?". The simplest solution without thinking about this would be to use the users own password, untill you realize that the user may change the password. If the user does that you need to Decrypt and ReEncrypt every single multimedia file associated with the user.
To answer the actual question about key management I'd suggest reading up on key management. As I'm no expert on cryptography I hope someone more versed in the crypto world can help here... Link: http://en.wikipedia.org/wiki/Key_management.
I think it all depends on a few things:
Where do the files come from initially
How will the files be accessed (over the network or locally)
Who do you want to protect the files from
If the initial files come from "you" (the developer) then encrypted database blobs would probably be the best way as most dbs' come with some form of encryption.
If the files come from the user of the software, then using the file system would suffice - possibly using an temporary directory to store and retrieve files if used over the network, but actually storing the files in a non-shared location so that network users don't have access to all the files.
Just a few thoughts.
Local file protection, web project protection, and secure email, Record-level security in databases (DB2, Oracle, Firebird, MS SQ:, My SLQ etc.). Creating encryption systems from primitives etc. Look for File Protect System - SE or SPE or PE.

Resources