public class TripleDES {
public static final String DES_PROVIDER = "SunJCE";
public static final int DES_KEYSIZE = 112;
public static final byte SEED[] = "15454432999".getBytes();
public final static String ENCODED_PASSWORD_PREFIX = "enc";
private static TripleDES _me=new TripleDES();
private TripleDES() {};
public static TripleDES getInstance() {
return _me;
}
public String encrypt(String code) {
return encrypt(code, null);
}
private String encrypt(String code, SecureRandom sr){
SecureRandom rng;
KeyGenerator keyGen;
Key key;
Cipher cipher;
byte[] byteData = code.getBytes();
if(sr == null) rng = new SecureRandom(SEED);
else rng = sr;
try{
keyGen = KeyGenerator.getInstance("DESede", DES_PROVIDER);
keyGen.init(DES_KEYSIZE, rng);
key = keyGen.generateKey();
cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding", DES_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, key);
return new sun.misc.BASE64Encoder().encode(cipher.doFinal(byteData));
}catch(NoSuchProviderException npro){
}catch(NoSuchAlgorithmException nalg){
}catch(NoSuchPaddingException npad){
}catch(InvalidKeyException inv){
}catch(BadPaddingException bad){
}catch(IllegalBlockSizeException ile){
}
return null;
}
public String decrypt(String code){
return decrypt(code, null);
}
private String decrypt(String code, SecureRandom sr){
SecureRandom rng;
KeyGenerator keyGen;
Key key;
Cipher cipher;
if(sr == null) rng = new SecureRandom(SEED);
else rng = sr;
try{
keyGen = KeyGenerator.getInstance("DESede", DES_PROVIDER);
keyGen.init(DES_KEYSIZE, rng);
key = keyGen.generateKey();
cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding", DES_PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] codeBytes = new sun.misc.BASE64Decoder().decodeBuffer(code);
byte[] text = cipher.doFinal(codeBytes);
return new String(text);
}catch(NoSuchProviderException npro){
npro.printStackTrace();
}catch(NoSuchAlgorithmException nalg){
nalg.printStackTrace();
}catch(NoSuchPaddingException npad){
npad.printStackTrace();
}catch(InvalidKeyException inv){
inv.printStackTrace();
}catch(BadPaddingException bad){
bad.printStackTrace();
}catch(IllegalBlockSizeException ile){
ile.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
}
# posted by Tomer Ben David @ 1:19 AM