Solved

need to encrypt password

Posted on 2007-11-19
11
240 Views
Last Modified: 2008-02-07
I am trying to encrypt a password in Java/jsp. I have not really found a straightforward example searching EE. Can someone give me a sample code fragment to do this? Thanks.
0
Comment
Question by:jmarkfoley
  • 4
  • 4
  • 3
11 Comments
 
LVL 9

Expert Comment

by:brunoguimaraes
ID: 20314474
Here's a simple example:
         Key key;

         IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]);

         try {

         ObjectInputStream in = new

         ObjectInputStream(new FileInputStream("key.dat"));

         key = (Key)in.readObject();

         in.close();

         }

         catch (Exception e) {

         KeyGenerator generator = KeyGenerator.getInstance("DESede", "SunJCE");

         generator.init(new SecureRandom());

         key = generator.generateKey();

         ObjectOutputStream out = new ObjectOutputStream(

         new FileOutputStream("key.dat"));

         out.writeObject(key);

         out.close();

         }

                

         Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");

                

         byte[] input = new String("PASSWORD TO BE ENCRYPTED").getBytes("UTF8");

                        

         cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

                        

         byte[] cipherText = cipher.doFinal(input);

                        

         System.out.println(Base64.encodeBytes(cipherText));

Open in new window

0
 
LVL 9

Accepted Solution

by:
ysnky earned 400 total points
ID: 20314535
0
 
LVL 1

Author Comment

by:jmarkfoley
ID: 20315149
Thanks ysnky, that 1st example was the shortest, simplest example I've come across. I'll leave this question open for a bit in case someone thinks this technique is a bad idea. I'm used to languages where encrypting things is more-or-less built in, so all of this "digesting" business is new for me.

Here it is for reference:

private byte[] pwCrypt(String pw)
{
     java.security.MessageDigest d =null;
     d = java.security.MessageDigest.getInstance("SHA-1");
     d.reset();
     d.update(pw.getBytes());
     return  d.digest();
}
0
 
LVL 9

Expert Comment

by:brunoguimaraes
ID: 20315492
Just to clarify... This example you posted is actually hashing the password. If you need to decrypt it back to the original String, you won't be able to.

But I guess you won't really need to to that!
0
 
LVL 1

Author Comment

by:jmarkfoley
ID: 20335357
brunoguimaraes: Yes, all I want is one-way encryption. I've got to be honest, Java's "encryption" methods are the most complex and over-engineered things I've ever seen. Unix/Linux gives C a simple  one-liner call: *crypt(const char *key, const char *salt);, and you can get even fancier using md5sum, also implemented as a single line of code. I don't see why Java had to implemented it at the professional crytographer level for simple things like one-way password one-way!
Now, it seems, it is a bit of a chore to convert byte[]'s to Strings, which I need to save me results. AND, someone said that digest() function might not return printable characaters (does that matter for a Java string?). So, I am trying to figure out  how to get a String. Even your initial example, brunoguimaraes, eft me with byte[]s. I'm getting ready to forget about it and just use password.hashCode(), which might be good enough.
If someone can give me a SIMPLE byte[] to String conversion, I will be glad to split points.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Expert Comment

by:ysnky
ID: 20335561
           String orgStr = "experts";
            byte[] bAry = orgStr.getBytes("UTF8");
            String newStr = new String(bAry, "UTF8");
            
            System.out.println("org str:" + orgStr + ", new str:" + newStr);
0
 
LVL 9

Assisted Solution

by:brunoguimaraes
brunoguimaraes earned 100 total points
ID: 20349607
You have to use Base64 to convert the array of bytes to a String.

Download this class: http://iharder.sourceforge.net/current/java/base64/

And do the following:


byte[] byteArray;

String result = Base64.encodeBytes( byteArray );

Open in new window

0
 
LVL 1

Author Comment

by:jmarkfoley
ID: 20350087
ysnky: your suggestion (if I did it right) gabe me an exception. Not sure why:

An error occurred at line: 15 in the jsp file: /include/crypt.inc
Unhandled exception type UnsupportedEncodingException
12:       e.printStackTrace();
13:     }
14:
15:     return new String(d.digest(), "UTF8");

brunoguimaraes: I've downloaded the class you linked, but I'm new at this. Where do I install it? There isn't a 'make' or 'install' file giving instructions.
0
 
LVL 1

Author Comment

by:jmarkfoley
ID: 20350270
You know what guys, this is way too much work for what should be simple. I'm leery of download a class that probably won't exist in "vanilla" installations.

When I use ysnky's referenced code and do return new String(digestedBytes); I get a 10 digit string, just like using hasCode (though possibly a different 10 bytes). So I'm just gonna do:

private String pwCrypt(String pw)
{
    return "" + pw.hashCode();
}

This gives me 9 1/2 signed digits for 4 billion possible combinations. Finite, to be sure, but good enough.  
0
 
LVL 9

Expert Comment

by:brunoguimaraes
ID: 20351074
I know you'll use hashCode(), but here's a function to convert an array of bytes to an hexadecimal String (no downloads needed):

public static String toHexString(byte[] bytes) {
         if( bytes == null ) return null;
         String hexDigits = "0123456789abcdef";
         StringBuffer sbuffer = new StringBuffer();
         for (int i = 0; i < bytes.length; i++) {
             int j = ((int) bytes[i]) & 0xFF;
             sbuffer.append(hexDigits.charAt(j / 16));
             sbuffer.append(hexDigits.charAt(j % 16));
         }
         return sbuffer.toString();
}
0
 
LVL 9

Expert Comment

by:ysnky
ID: 20351643
hey jmarkfoley, where did you get exception, send the full code?
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

759 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now