Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Password Encryption and Decryption

843836Feb 3 2004 — edited Sep 25 2008
Hello Everybody,

I am working on a web site and i need to store password in the encrypted form in the database. I used DES Encryption using javax.crypto API's for this purpose and it is working fine. But when i try to decrypt the password stored in database, it returns null. I am posting the, can anyone please help me out in figuring out what's the problem is.

//DesEncrypter Bean
import java.io.*;
import java.util.*;
import javax.crypto.*;

public class DesEncrypter
{
public String encrypt(String str, Cipher ecipher)
{
try
{
byte[] utf8 = str.getBytes("UTF8");

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

return new sun.misc.BASE64Encoder().encode(enc);
}
catch (javax.crypto.BadPaddingException e)
{
}
catch (IllegalBlockSizeException e)
{
}
catch (UnsupportedEncodingException e)
{
}
catch (java.io.IOException e)
{
}
return null;
}

public String decrypt(String str, Cipher dcipher)
{
try
{
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

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

return new String(utf8, "UTF8");
}
catch (javax.crypto.BadPaddingException e) {
}
catch (IllegalBlockSizeException e) {
}
catch (UnsupportedEncodingException e) {
}
catch (java.io.IOException e) {
}
return null;
}
}

//jsp Page
<%@ page import="javax.crypto.*" %>
<%!
Cipher dcipher;
%>
<%
SecretKey key = KeyGenerator.getInstance("DES").generateKey();

try
{
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key1);
}
catch (java.security.NoSuchAlgorithmException e) {
}
catch (java.security.InvalidKeyException e) {
}

String Pass = rs.getString("PASSWORD");
String decrypted = Enc.decrypt(Pass, dcipher);

//decrypted contains null, does i need to store key used during encryption.

Any help is appreciated.

Thanks and regards

MSoldier
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 23 2008
Added on Feb 3 2004
6 comments
567 views