Skip to content

Instantly share code, notes, and snippets.

@Goblin80
Last active March 13, 2019 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Goblin80/4d3cf42d7f79485455e7be3607afaf66 to your computer and use it in GitHub Desktop.
Save Goblin80/4d3cf42d7f79485455e7be3607afaf66 to your computer and use it in GitHub Desktop.
Crack DES (ECB) through searching whole key space using Java Streams
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.util.Arrays;
import java.util.stream.LongStream;
public class BruteDES {
public static byte[] encrypt(byte[] plaintext, byte[] rawkey) {
try {
return _digest(plaintext, rawkey, Cipher.ENCRYPT_MODE);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] decrypt(byte[] encrypted, String rawkey) throws Exception {
return _digest(encrypted, rawkey.getBytes(), Cipher.DECRYPT_MODE);
}
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);
}
private static SecretKey prepKey(byte[] key) throws Exception {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
return skf.generateSecret(dks);
}
public static byte[] longToBytes(long l) {
byte[] result = new byte[8];
for (int i = 7; i >= 0; i--) {
result[i] = (byte) (l & 0xFF);
l >>= 8;
}
return result;
}
public static long bytesToLong(byte[] b) {
long result = 0;
for (int i = 0; i < 8; i++) {
result <<= 8;
result |= (b[i] & 0xFF);
}
return result;
}
public static void main(String[] args) {
byte[] plaintext = "The dog in the garden row is covered in mud".getBytes();
// String passphrase = "cndr&smk";
byte[] cipher = {
(byte) 0xbe, (byte) 0x67, (byte) 0x02, (byte) 0x2e, (byte) 0xa9, (byte) 0x6d, (byte) 0xf9, (byte) 0xc9,
(byte) 0xcd, (byte) 0x09, (byte) 0x0e, (byte) 0xd8, (byte) 0x3c, (byte) 0x96, (byte) 0xec, (byte) 0x75,
(byte) 0x69, (byte) 0x4c, (byte) 0x7a, (byte) 0x7d, (byte) 0x4a, (byte) 0xa8, (byte) 0x68, (byte) 0x59,
(byte) 0x5f, (byte) 0xf3, (byte) 0x31, (byte) 0x4a, (byte) 0xe2, (byte) 0x53, (byte) 0xa4, (byte) 0xdb,
(byte) 0x4b, (byte) 0x19, (byte) 0x38, (byte) 0x25, (byte) 0x59, (byte) 0xde, (byte) 0x35, (byte) 0xa2,
(byte) 0xbc, (byte) 0xed, (byte) 0x19, (byte) 0xb9, (byte) 0x98, (byte) 0xf0, (byte) 0x37, (byte) 0xee};
LongStream.range(0x0, 0x1000000000000000L)
// LongStream.range(7164774498627186027L - 10000, 7164774498627186027L + 10000)
.parallel()
// .peek(x -> {if(x % 1000000 == 0) System.out.print("#");})
.filter(x -> Arrays.equals(cipher, encrypt(plaintext, longToBytes(x))))
.forEach(x -> System.out.println("\nKey Found: " + new String(longToBytes(x))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment