Skip to content

Instantly share code, notes, and snippets.

@mehmetcemyucel
Last active December 26, 2017 17:48
Show Gist options
  • Save mehmetcemyucel/769fba1f325bba59c93bf724f9a66d9d to your computer and use it in GitHub Desktop.
Save mehmetcemyucel/769fba1f325bba59c93bf724f9a66d9d to your computer and use it in GitHub Desktop.
package com.cem;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DESEncryptionDecryption {
public static byte[] DESEncryption(String key, String initVector, String value)
throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
return encrypted;
}
public static String DESDecryption(String key, String initVector, byte[] encrypted)
throws UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException,
NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] orginal = cipher.doFinal(encrypted);
return new String(orginal);
}
public static void main(String[] args) {
try {
String key = "Bar12345";
String initVector = "RandomIn";
String data = "Merhaba Dünya ışçğüö";
System.out.println(DESDecryption(key, initVector, DESEncryption(key, initVector, data)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment