[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


Encryption & Decryption with Java.

Posted on 2005-05-01
Medium Priority
Last Modified: 2012-06-21


I am using this class for Encryption.  However I have two questions:

1) How can I store the key so the string can be decrypted at a later date?
2) Any recommendations in storing this key?


import javax.crypto.*;

public class DesEncrypter {
  public DesEncrypter() {
  Cipher ecipher;
  Cipher dcipher;

  public DesEncrypter(SecretKey key) {
      try {
          ecipher = Cipher.getInstance("DES");
          dcipher = Cipher.getInstance("DES");
          ecipher.init(Cipher.ENCRYPT_MODE, key);
          dcipher.init(Cipher.DECRYPT_MODE, key);

      } catch (javax.crypto.NoSuchPaddingException e) {
      } catch (java.security.NoSuchAlgorithmException e) {
      } catch (java.security.InvalidKeyException e) {
  public String encrypt(String str) {
      try {
          // Encode the string into bytes using utf-8
          byte[] utf8 = str.getBytes("UTF8");

          // Encrypt
          byte[] enc = ecipher.doFinal(utf8);

          // Encode bytes to base64 to get a string
          return new sun.misc.BASE64Encoder().encode(enc);
      } catch (javax.crypto.BadPaddingException e) {
      } catch (IllegalBlockSizeException e) {
      } catch (java.io.IOException e) {
      return null;

  public String decrypt(String str) {
      try {
          // Decode base64 to get bytes
          byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

          // Decrypt
          byte[] utf8 = dcipher.doFinal(dec);

          // Decode using utf-8
          return new String(utf8, "UTF8");
      } catch (javax.crypto.BadPaddingException e) {
      } catch (IllegalBlockSizeException e) {
      } catch (java.io.IOException e) {
      return null;

Question by:amacfarl
  • 5
  • 3
  • 2
  • +1

Expert Comment

ID: 13906666
Normally a key is stored in keystore in file system.

Expert Comment

ID: 13906926
limaideal is right, KeyStores are the most common way of storing keys but this is not always an ideal solution.
Storing a SecretKey on your file system can make your encrypted data vulnerable to attack.
One risk is that someone might gain remote access to your hard disk and copy the key.
Another is that anyone that uses your computer could get the key and decrypt your data with very little effort.

Depending on how secure you need this to be, storing the key on your hard disk might be the best solution.
If you wanted to use a KeyStore for this, check out the java.security.KeyStore class.

You could also just write the raw key to a file which would make things easier (and less secure).

Expert Comment

ID: 13906954
One more comment: you can also protect your keystore with passwd, which will add one more layer of protection.
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.


Expert Comment

ID: 13907079
if you make ur own encryption algorithms, then i'm sure nobody in this world will decrypt that data.

Expert Comment

ID: 13907098
>if you make ur own encryption algorithms, then i'm sure nobody in this world will decrypt that data.

I disagree.

1. Its very easy to get source code from a class file so an attacker can see the algorithm and find a potential weakness.
2. Brute force attacks have never failed to crack any encryption algorithm. If you have a fast enough super computer, it can be done.
3. Assuming an attacker has failed 1 and 2, he/she just needs the secret key and the encryption algorithm doesn't matter ;-)

Author Comment

ID: 13907766
Thanks for your comments and advice.  You have openned it up for me.  I have few more questions though I was wondering if you could help.

I am developing a web application that encrypting data entered by the user.  One option is to store the key on the database.  I would prefer this option instead of dealing with files on the web server as loading and saving files is not as streamless as reading from the database.

Also, what is the recommendation - use a different key for each user?

I am new in the world of encryption, but on the basis that someone has the key and the algorithm, they then have complete access to everything!  Surely on that basis it would be safer to develop my own algorithm as this one anyone can plug and play with the correct key and go.



Accepted Solution

OBCT earned 2000 total points
ID: 13907906
If someone has the key, the encryption algorithm that's used doesn't matter.
Let’s say that an attack somehow got one of the users’ keys. I'm not really sure what you’re encrypting or how you’re doing it but lets also assume that the server is waiting for the key before any information is shown.
Seeing as the attacker has the key, all he/she needs to do is send it to the server and the data will be shown.
There is no need for the attacker to know the encryption algorithm.

As for brute force attacks, it would certainly make things allot quicker to know the algorithm, but even without it, it's only a matter of time before it can be cracked.

As for storing keys in a database...
If someone manages to crack the database, they will have access to all the keys and the entire system will be compromised.
You can use one KeyStore for as many keys as you want. Imagine it to be like a small database that will only allow Key's to be put in it.
So really, you don't need any more than one file on your hard disk to keep track of the keys.

>Also, what is the recommendation - use a different key for each user?

It depends what you’re encrypting and how you’re doing it.
You could use a different key for each session but it may be a waste of time. Again, it comes down to what your project involves.

Am I able to ask what you’re encrypting?

Author Comment

ID: 13910299
Sure.  We are storing credit card data.

As I write this I hear you saying... "Ouch! Here we have some twit who knows nothing about encryption playing around with credit card numbers..."!!

Before you jump on and shout at me, let me explain.  I don't like the idea of storing credit data as it opens that big door labeled "Risk" which is right next to the other door labeled "Idiot".  However, my company as requested that we go down this root as apparently there is no alternative.

The site is hosted on a server housed in a secure location with limited & controlled access.  Our architecture is as follows:  the site is a JSP based site with a MS SQL database backend.  Connections are managed as follows:

User to Web Site is via SSL
Web Site to DB is via SSL and single IP only (therefore DB will only accept connections from the web server)

We have two databases.  One which holds customer data and another which has data which the customer is paying to access.  Access to the both databases are strictly controlled through DB security.

My main issue at the moment is how best to structure the architecture to encrypt this data.  I see two options:

1) Store Key on Web Server
2) Store Key on DB.

If I store the key on Web Server we run the risk as this is where all users access the site.  However if we store the key on the DB server, it is more difficult for a hacker to get access to it however the key is being stored on the same hardware as the customer data.  Not a good idea.

I have searched for some documentation on best practices, but not found much.   I have even contacted the acquiring bank and PSP who were not much help either.

Can anyone recommend a solution or provide some direction. Overall I am very apprehensive about storing CC data.....

Expert Comment

ID: 13910639
First of all, I will apologize if I've offended you as this was not my intention at all.
I was just trying to make the point that no system is 100% secure.

To be perfectly honest, I'm not sure if one option is better than the other.
At the end of the day, the attacker is going to need access to the DB. Without having that ability, they won't be able to decrypt anything (assuming the encrypted data is never stored in the servers memory).

As far as best practices go, the aim is to make it hard for attackers to crack in as many ways as possible.
So far, it seems like you've done a very good job of that.

My recommendation would be to store they key on the DB because it seems less likely that an attacker will get that far. Plus I don't like the idea of anyone un-authorized having a copy of the keys used to decrypt data.

Author Comment

ID: 13910712

Thanks ever so much for replying so promptly.  

You did not offend me at all! Sometime I come across wrongly - usually happens after 10 cups of coffee and often on mondays...  I am on cup number 15! ;-)

Anyway, thanks for your feedback.  Every time that I ask a question to Experts Exchange I am always so impressed by the time & effort that all put in to answering questions!! In my view it is money well spent!!

All the best.  I am now off to shoot my boss... get another coffee and implement your recommendation of storing the info on the DB.

Thanks & Kind regards

Expert Comment

ID: 13910752
> I am on cup number 15! ;-)

I use a coffee IV drip, no need to count cups :-p

>Anyway, thanks for your feedback.  Every time that I ask a question to Experts Exchange I am always so impressed by the time & effort that all put in to answering questions!! In my view it is money well spent!!

It is always nice to be appreciated so thank you and I'm always happy to help.
Good luck with the rest of your project :-)

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month20 days, 2 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question