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 ?
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.
EDIT : this answer is old. Usage of MD5 is now discouraged as it can easily be broken.
MD5 must be good enough for you I imagine? You can achieve it with MessageDigest.
MessageDigest.getInstance("MD5");
There are also other algorithms listed here.
And here's an third party version of it, if you really want: Fast MD5
Jasypt can do it for you easy and simple
You can use java.security.MessageDigest
with SHA
as your algorithm choice.
For reference,
Try available example here
I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.
精彩评论