Skip to content

Instantly share code, notes, and snippets.

@Goblin80
Created March 13, 2019 11:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Goblin80/412ce94fff2ee76c1f2fd55397989623 to your computer and use it in GitHub Desktop.
Save Goblin80/412ce94fff2ee76c1f2fd55397989623 to your computer and use it in GitHub Desktop.
3DES (ECB) implementation in Java
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.util.Arrays;
public class TripleDES {
enum MODE {
ENCRYPT(0), DECRYPT(1);
int code;
MODE(int code) {
this.code = code;
}
}
public static byte[] encrypt(String plaintext, String rawkey) throws Exception {
return _trip(plaintext.getBytes(), rawkey.getBytes(), MODE.ENCRYPT);
}
public static String decrypt(byte[] encrypted, String rawkey) throws Exception {
String res = "";
for (byte b : _trip(encrypted, rawkey.getBytes(), MODE.DECRYPT))
res += String.format("%c", b);
return res;
}
private static SecretKey prepKey(byte[] key) throws Exception {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
return skf.generateSecret(dks);
}
private static byte[] _trip(byte[] input, byte[] key, MODE mode) throws Exception {
int process[][] = {
{Cipher.ENCRYPT_MODE, Cipher.DECRYPT_MODE, Cipher.ENCRYPT_MODE}, // encrypt
{Cipher.DECRYPT_MODE, Cipher.ENCRYPT_MODE, Cipher.DECRYPT_MODE}}; // decrypt
byte[] res = input;
for (int i = 0; i < 3; i++)
res = _digest(res, Arrays.copyOfRange(key, 0 * 8, (i + 1) * 8), process[mode.code][i]);
return res;
}
private static byte[] _digest(byte[] plain, byte[] key, int mode) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, prepKey(key));
return cipher.doFinal(plain);
}
public static void main(String[] args) {
String plaintext = "Did you hear about the restaurant on the moon?",
passphrase = "Good food, no atmosphere";
try {
byte[] encrypted = TripleDES.encrypt(plaintext, passphrase);
System.out.println(TripleDES.decrypt(encrypted, passphrase));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment