Created
March 13, 2019 11:36
-
-
Save Goblin80/412ce94fff2ee76c1f2fd55397989623 to your computer and use it in GitHub Desktop.
3DES (ECB) implementation in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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