· 6 years ago · Mar 18, 2019, 04:52 AM
1import javax.crypto.*;
2import javax.crypto.spec.DESKeySpec;
3import java.util.Arrays;
4import java.util.stream.LongStream;
5
6public class BruteDES {
7
8 public static byte[] encrypt(byte[] plaintext, byte[] rawkey) {
9 try {
10 return _digest(plaintext, rawkey, Cipher.ENCRYPT_MODE);
11 } catch (Exception e) {
12 e.printStackTrace();
13 }
14 return null;
15 }
16
17 public static byte[] decrypt(byte[] encrypted, String rawkey) throws Exception {
18 return _digest(encrypted, rawkey.getBytes(), Cipher.DECRYPT_MODE);
19 }
20
21 private static byte[] _digest(byte[] plain, byte[] key, int mode) throws Exception {
22 Cipher cipher = Cipher.getInstance("DES");
23 cipher.init(mode, prepKey(key));
24 return cipher.doFinal(plain);
25 }
26
27 private static SecretKey prepKey(byte[] key) throws Exception {
28 DESKeySpec dks = new DESKeySpec(key);
29 SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
30 return skf.generateSecret(dks);
31 }
32
33 public static byte[] longToBytes(long l) {
34 byte[] result = new byte[8];
35 for (int i = 7; i >= 0; i--) {
36 result[i] = (byte) (l & 0xFF);
37 l >>= 8;
38 }
39 return result;
40 }
41
42 public static long bytesToLong(byte[] b) {
43 long result = 0;
44 for (int i = 0; i < 8; i++) {
45 result <<= 8;
46 result |= (b[i] & 0xFF);
47 }
48 return result;
49 }
50
51 public static void main(String[] args) {
52 byte[] plaintext = "The dog in the garden row is covered in mud".getBytes();
53// String passphrase = "cndr&smk";
54
55 byte[] cipher = {
56 (byte) 0xbe, (byte) 0x67, (byte) 0x02, (byte) 0x2e, (byte) 0xa9, (byte) 0x6d, (byte) 0xf9, (byte) 0xc9,
57 (byte) 0xcd, (byte) 0x09, (byte) 0x0e, (byte) 0xd8, (byte) 0x3c, (byte) 0x96, (byte) 0xec, (byte) 0x75,
58 (byte) 0x69, (byte) 0x4c, (byte) 0x7a, (byte) 0x7d, (byte) 0x4a, (byte) 0xa8, (byte) 0x68, (byte) 0x59,
59 (byte) 0x5f, (byte) 0xf3, (byte) 0x31, (byte) 0x4a, (byte) 0xe2, (byte) 0x53, (byte) 0xa4, (byte) 0xdb,
60 (byte) 0x4b, (byte) 0x19, (byte) 0x38, (byte) 0x25, (byte) 0x59, (byte) 0xde, (byte) 0x35, (byte) 0xa2,
61 (byte) 0xbc, (byte) 0xed, (byte) 0x19, (byte) 0xb9, (byte) 0x98, (byte) 0xf0, (byte) 0x37, (byte) 0xee};
62
63 LongStream.range(0x0, 0x1000000000000000L)
64// LongStream.range(7164774498627186027L - 10000, 7164774498627186027L + 10000)
65 .parallel()
66// .peek(x -> {if(x % 1000000 == 0) System.out.print("#");})
67 .filter(x -> Arrays.equals(cipher, encrypt(plaintext, longToBytes(x))))
68 .forEach(x -> System.out.println("\nKey Found: " + new String(longToBytes(x))));
69 }
70}