41

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 ?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Raje
  • 3,285
  • 15
  • 50
  • 70

5 Answers5

20

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.

Adrian Stamin
  • 687
  • 2
  • 8
  • 21
  • I don't know why, but this algorithm didn't work 100% for me. Sometimes the result was not correct (I compared the result with the MD5 crypted password returned by JDBC realm on Tomcat). This worked for me perfect: http://www.java2s.com/Code/Java/Security/UseMD5toencryptastring.htm – Xithias Jan 21 '15 at 13:58
  • 1
    @AdrianStamin Would you please explain what `0xff & digested[i]` does? :) – theapache64 Apr 02 '16 at 07:39
  • 3
    md5 is not secure (easily decrypted), and should never be used for passwords. – alttag Apr 04 '16 at 18:07
  • 1
    @theapache64 The digested[i] & 0xff ensures that only the 8 least significant bits of digested[i] can be non-zero . 0xff is 255 in decimal base and 00000000 00000000 00000000 11111111 in binary base When you make the bitwise operation AND (&) with any byte it will ensure that only the least important bits in the resulting number can be non zero. Example: 00000000 00000000 00000000 11111111 (255) & 00000000 00011111 00000000 01000000 (8000) => 00000000 00000000 00000000 01000000 – Adrian Stamin May 06 '16 at 12:25
  • 1
    @alttag You are right. MD5 is unsecure. Nowadays people use salted MD5. The best way to store passwords is to let others do it. Like facebook or yahoo :) – Adrian Stamin May 06 '16 at 12:26
  • 1
    @AdrianStamin : Even salted MD5 is a bad idea. Salting is good, but salting with a broken hash is still broken. – alttag Jul 08 '16 at 19:24
10

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

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
zw324
  • 26,764
  • 16
  • 85
  • 118
  • 51
    md5 is one-way hash only. You cannot decrypt. – Kal Jul 06 '11 at 05:43
  • 5
    +1. @avs31586, you don't ever really need to decrypt a password. instead you encrypt with MD5 and then when you check you always check the two MD5's. Kind of gets you around the problem of people guessing your encryption algorythm – griegs Jul 06 '11 at 05:44
  • Oops. Missed the decryption part... Although when storing a password this probably won't make much difference, but I give my vote to Kal. – zw324 Jul 06 '11 at 05:55
  • @:Ziyao..thanks for your suggestion but in our application we need to decrypt that password and display to user. do you have other idea for encryption and decryption? – Raje Jul 06 '11 at 06:27
  • 9
    I know this is an old question, but please *NEVER* use md5 to "encrypt" passwords. md5 is not secure, and is easily decrypted. – alttag Apr 04 '16 at 18:06
  • as Kal alreaady said, the question was to encrypt and decrypt a password. MD5 is just one way -> hashing. – Anton Nov 02 '17 at 09:31
  • hashing is one way – sam Apr 06 '18 at 09:11
  • 1
    MD5 is broken since 2009: http://cryptocrats.com/crypto/md5-the-hash-algorithm-is-now-broken/ – tgr Jun 04 '18 at 05:27
8

Jasypt can do it for you easy and simple

Michu93
  • 5,058
  • 7
  • 47
  • 80
GustyWind
  • 3,026
  • 3
  • 41
  • 50
  • 1
    Working on something similar right now ... since it sounds like you DO need to decrypt the password at some point, something like MD5 won't work. I think this is the simplest solution. – JasonStoltz Sep 22 '11 at 17:09
  • @JasonStoltz How to add salt along with Jasypt ? – kittu Dec 18 '15 at 12:50
2

You can use java.security.MessageDigest with SHA as your algorithm choice.

For reference,

Try available example here

raksja
  • 3,969
  • 5
  • 38
  • 44
  • 1
    your example is great. but it does not provide decryption . do you have any idea for decryption? – Raje Jul 06 '11 at 06:24
  • Use `Base64Decoder` [Example here](http://www.kodejava.org/examples/376.html) – raksja Jul 06 '11 at 06:37
  • which package is required for org.apache.commons.codec.binary.Base64; – Raje Jul 06 '11 at 08:16
  • What I have suggested is a very simple approach. But sun packaged files stricktly are not usable. `String encoded = (new BASE64Encoder()).encode("text to be encoded".getBytes("UTF-8")); byte decodedRaw[] = (new BASE64Decoder()).decodeBuffer(encoded); String decoded = new String(decodedRaw, "UTF8");` If you want to go with another approach you can refer [this](http://www.idevelopment.info/data/Programming/java/security/java_cryptography_extension/StringEncrypter.java) and create a custom encryptor/decryptor. – raksja Jul 06 '11 at 08:51
  • 5
    What does Base64-encoding have to do with encryption and decryption? Nothing. – user207421 Jul 06 '11 at 10:17
  • 7
    Base64 encoding is NOT encryption, and anything stored in Base64 can easily be known. There's no protection in it. Do any of you work at banks or financial institutions that might have my money? Dear god I hope not! – chubbsondubs Aug 10 '11 at 21:29
2

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.

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60