我正在学习计算机安全课程,其中一项任务是对具有弱密钥的DES进行暴力破解。
我的代码:
public static void main(String[] args) throws Exception {
String temp;
String current;
String plaintext;
//Generate key for DES
String initkey = "00000006";
byte[] Rawkey = initkey.getBytes();
DESKeySpec dks = new DESKeySpec(Rawkey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
//Text Enc & Dec
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//Declare wether to enc or dec
cipher.init(Cipher.ENCRYPT_MODE,desKey);
byte []message = "Decrypted Successfully".getBytes();
byte []messageEnc = cipher.doFinal(message);
plaintext = new String(message);
System.out.println("Cipher Text: " + new String(messageEnc) );
for(int i=0;i<10;i++){
try{
temp = padLeftZeros(Integer.toString(i),8);
System.out.println(temp);
byte []RawkeyTest = temp.getBytes();
DESKeySpec dksTest = new DESKeySpec(RawkeyTest);
SecretKeyFactory skf2 = SecretKeyFactory.getInstance("DES");
SecretKey desKeyTest = skf2.generateSecret(dksTest);
cipher.init(Cipher.DECRYPT_MODE,desKeyTest);
byte []dec = cipher.doFinal(messageEnc);
current = new String(dec);
if(current.equals(plaintext)){
System.out.println("Decrypted Text: " + current);
System.out.println("");
//break;
}
}catch (BadPaddingException ex){
System.out.println("Wrong Key.");
System.out.println("");
}
}
}
public static String padLeftZeros(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
while (sb.length() < length - inputString.length()) {
sb.append('0');
}
sb.append(inputString);
return sb.toString();
}
}
输出
Cipher Text: �
B��4#Ǡ�`=Π��H�č:�
00000000
Wrong Key.
00000001
Wrong Key.
00000002
Wrong Key.
00000003
Wrong Key.
00000004
Wrong Key.
00000005
Wrong Key.
00000006
Decrypted Text: Decrypted Successfully
00000007
Decrypted Text: Decrypted Successfully
00000008
Wrong Key.
00000009
Wrong Key.
00000010
Wrong Key.
00000011
Wrong Key.
00000012
Wrong Key.
00000013
Wrong Key.
00000014
Wrong Key.
00000015
Wrong Key.
00000016
Decrypted Text: Decrypted Successfully
00000017
Decrypted Text: Decrypted Successfully
00000018
Wrong Key.
00000019
Wrong Key.
只有密钥 #6 应该可以成功解密,我不明白为什么密钥 7、16、17 也有效。
如有帮助或建议将不胜感激,谢谢!