Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt and decrypt a password in Java [closed]

I want to encrypt and decrypt a password in Java and store into database in the form of encrypted. It will great if it is open source. Any suggestions / pointers ?

like image 534
Raje Avatar asked Jul 06 '11 05:07

Raje


People also ask

What is the best way to encrypt passwords in Java?

Password-Based Encryption using Salt and Base64: The password-based encryption technique uses plain text passwords and salt values to generate a hash value. And the hash value is then encoded as a Base64 string. Salt value contains random data generated using an instance of Random class from java. util package.


1 Answers

Here is the algorithm I use to crypt with MD5.It returns your crypted output.

   public class CryptWithMD5 {    private static MessageDigest md;     public static String cryptWithMD5(String pass){     try {         md = MessageDigest.getInstance("MD5");         byte[] passBytes = pass.getBytes();         md.reset();         byte[] digested = md.digest(passBytes);         StringBuffer sb = new StringBuffer();         for(int i=0;i<digested.length;i++){             sb.append(Integer.toHexString(0xff & digested[i]));         }         return sb.toString();     } catch (NoSuchAlgorithmException ex) {         Logger.getLogger(CryptWithMD5.class.getName()).log(Level.SEVERE, null, ex);     }         return null;      } } 

You cannot decrypt MD5, but you can compare outputs since if you put the same string in this method it will have the same crypted output.If you want to decrypt you need to use the SHA.You will never use decription for a users password.For that always use MD5.That exception is pretty redundant.It will never throw it.

like image 101
Adrian Stamin Avatar answered Sep 25 '22 00:09

Adrian Stamin