-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathClearMemory.java
More file actions
83 lines (67 loc) · 2.12 KB
/
ClearMemory.java
File metadata and controls
83 lines (67 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.ethjava;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
public class ClearMemory {
public static Unsafe UNSAFE = null;
public static void main(String[] args) {
String password = new String("11111111");
String fake = new String(password.replaceAll(".", "?"));
System.out.println(password); // l00k@myHor$e
System.out.println(fake); // ????????????
getUnsafe().copyMemory(fake, 0L, null, toAddress(password), sizeOf(password));
// getUnsafe().copyMemory(fake, 0L, null, toAddress(password), password.getBytes().length);
System.out.println(password); // ????????????
System.out.println(fake); // ????????????
}
public static Unsafe getUnsafe() {
if (UNSAFE != null) return UNSAFE;
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
UNSAFE = (Unsafe) theUnsafe.get(null);
System.out.println(UNSAFE);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return UNSAFE;
}
public static long toAddress(Object obj) {
Object[] array = new Object[]{obj};
long baseOffset = getUnsafe().arrayBaseOffset(Object[].class);
return normalize(getUnsafe().getInt(array, baseOffset));
}
public static Object fromAddress(long address) {
Object[] array = new Object[]{null};
long baseOffset = getUnsafe().arrayBaseOffset(Object[].class);
getUnsafe().putLong(array, baseOffset, address);
return array[0];
}
public static long normalize(int value) {
if (value >= 0) return value;
return (~0L >>> 32) & value;
}
public static long sizeOf(Object o) {
Unsafe u = getUnsafe();
HashSet<Field> fields = new HashSet<Field>();
Class c = o.getClass();
while (c != Object.class) {
for (Field f : c.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) == 0) {
fields.add(f);
}
}
c = c.getSuperclass();
}
// 获得偏移
long maxSize = 0;
for (Field f : fields) {
long offset = u.objectFieldOffset(f);
if (offset > maxSize) {
maxSize = offset;
}
}
return ((maxSize / 8) + 1) * 8; // padding
}
}