import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class JavaEncryptionDecryption {
private static String KEY = "ABCD1234";
public static byte[] encrypt(String textData) throws Exception {
String algo = "DES";
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
byte[] encBytes = KEY.getBytes("UTF8");
DESKeySpec keySpecEncrypt = new DESKeySpec(encBytes);
SecretKey keyEncrypt = keyFactory.generateSecret(keySpecEncrypt);
Cipher cipherEncrypt = Cipher.getInstance(algo);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, keyEncrypt);
byte[] encryptedBytes = cipherEncrypt.doFinal(textData.getBytes());
return encryptedBytes;
}
public static String decrypt(byte[] encrypted) throws Exception {
String algo = "DES";
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
byte[] encBytes = KEY.getBytes("UTF8");
DESKeySpec keySpecEncrypt = new DESKeySpec(encBytes);
SecretKey keyEncrypt = keyFactory.generateSecret(keySpecEncrypt);
Cipher cipherEncrypt = Cipher.getInstance(algo);
cipherEncrypt.init(Cipher.DECRYPT_MODE, keyEncrypt);
byte[] decryptedBytes = cipherEncrypt.doFinal(encrypted);
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
byte[] encryptText = encrypt("Hello@14$");
System.out.println("Encrypted Text = " + encryptText);
String decryptText = decrypt(encryptText);
System.out.println("Decrypted Text = " + decryptText);
}
}
Output:
Decrypted Text = Hello@14$