package com.www;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @ClassName: demo06timeAttack
* @Description: todo
* @Author: WMY
* @Date: 2021/10/15 9:40
*/
public class demo06timeAttack {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < 50; i++){
String start = start();
if (map.get(start) != null){
map.put(start, map.get(start) + 1);
}else {
map.put(start,1);
}
}
Set<String> strings = map.keySet();
Iterator<String> iterator = strings.iterator();
Integer max = 0;
String maxKey = "";
while (iterator.hasNext()){
String next = iterator.next();
if (map.get(next) > max){
maxKey = next;
max = map.get(next);
}
}
System.out.println("密码:"+maxKey);
}
public static String start(){
//声明一个密码字符数组
String[] strList = new String[]{"a","b","c","d","e","f","g","q","w","r","t","y","u","i","o","p",
"s","h","j","k","l","z","x","v","n","m","1","2","3","4","5","6","7","8","9","0"};
//声明可变的字符串
StringBuilder attackSentence = new StringBuilder("111111");
//可以提前获得密码的长度
//可以通过穷举法获得长度,已知密码长度为6-10位
//首先可以获得前6位正确密码,获得第5+6位密码的平均执行时间
//然后试第7位密码,获得第5+6+7位密码的平均执行时间
//然后试第8位密码,获得5+6+7+8位密码的平均执行时间,如果与6+7时间相差极小,则为6位密码
for (int i = 0; i < attackSentence.length(); i++){
//用来存储执行时间和密码字符
Map<Long,String> map = new HashMap<>();
for(int j = 0; j < strList.length; j++){
//不停的对攻击密码进行字符替换
attackSentence.replace(i, i+1, strList[j]);
//获取执行开始时间和结束时间
long startTime = System.currentTimeMillis();
vlidatePwd(new String(attackSentence));
long endTime = System.currentTimeMillis();
//将执行时间差和此次循环字符加到map中
map.put(endTime-startTime,strList[j]);
}
//获得所有的key,也就是执行时间
Set<Long> keys = map.keySet();
Long maxKey = 0L;
//获得最大的key
Iterator<Long> iterator = keys.iterator();
while (iterator.hasNext()){
Long next = iterator.next();
maxKey = maxKey > next ? maxKey:next;
}
//将与最大执行时间差匹配的字符替换进攻击密码
attackSentence.replace(i, i+1, map.get(maxKey));
}
//输出正确密码
return new String(attackSentence);
}
public static boolean vlidatePwd(String attackSentence){
if(attackSentence.length() <= 0 ){
return false;
}
//测试密码
String pwd = "abc454";
for (int i = 0; i < pwd.length(); i++){
//
int i1 = pwd.charAt(i) ^ attackSentence.charAt(i);
if(i1 != 0){
return false;
}
//模拟服务器响应需要时间
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return true;
}
}
时序攻击小例子
最新推荐文章于 2023-11-11 20:22:04 发布