Alright here is an example which we've used to encrypt a String realted using MD5 data hope this might be of some help.
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;
public final class EncryptService{
private static EncryptService Obj;
public synchronized String encrypt(String plaintext) throws Exception {
MessageDigest md = null;
try{
md = MessageDigest.getInstance("SHA");
} catch(NoSuchAlgorithmException e){
throw new Exception(e.getMessage());
}
try{
md.update(plaintext.getBytes("UTF-8"));
} catch(UnsupportedEncodingException e){
throw new Exception(e.getMessage());
}
byte raw[] = md.digest();
String hash = new BASE64Encoder().encode(raw);
return hash;
}
public static synchronized EncryptService getInstance(){
if(instance == null){
instance = new EncryptService();
}
return instance;
}
}
This is generally used for Password/Security word Encryption in most of the Real World Applications.
REGARDS,
RaHuL
hi, i too have something like these methods for encryption for passwords .,
i want to hide the data from the user,
usually i will do it in PHP, using encode/decode 64 function
eg:
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
same for encode
<?php
$str = 'This is an encoded string';
echo base64_encode($str);
?>
suggest me is there function like this
Use sun.misc.BASE64Encoder and sun.misc.BASE64Decoder.
String string = "test";
String encoded = new BASE64Encoder().encode(string.getBytes());
String decoded = new String(new BASE64Decoder().decodeBuffer(encoded)); // throws IOException
By the way, RahulSharna, MD5 is not the same as SH5. And why are you putting it in a (over)synchronized context in a singleton? There are only threadlocal vars and hashing is simply an one-way calculation. You can even safely declare it static.
Check here for a MD5 hasher: http://balusc.xs4all.nl/srv/dev-jep-use.html#GenerateMD5Hash
If you need to encrypt and decrypt, this talk of MD5 and SHA hashing is pointless. Hashing algorithms are one-way, meaning you can only "encrypt". Typically, they are used for passwords, where you do not need to decrypt - you just hash the input value and compare the hashed strings for equality.
If you you need to both encrypt and decrypt, you will need to use a symetric key encrpytion algorithm like 3DES, AES or similar.
Indeed, hashing is form of one-way encryption.
And also keep in mind that there is a difference between encrypying/decrypting and encoding/decoding. Encrypted values which are encrypted using a key are intented to be hard-to-hack (however, currently 3DES seems to be hackable). Encoded values are easy-to-hack by just decoding (translating) them back.
For passwords, please use hashes. Hash them by MD5 (or any kind of one-way encryption) and save the value in DB. During login, hash the entered password and compare it with the value in DB.