copymethod() with Java string -


i have requirement use copymethod() of unsafe class use string, came across link http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/, found following example-

string password = new string("l00k@myhor$e"); 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));  system.out.println(password); // ???????????? system.out.println(fake); // ????????????  static long toaddress(object obj) {     object[] array = new object[] {obj};     long baseoffset = getunsafe().arraybaseoffset(object[].class);     return normalize(getunsafe().getint(array, baseoffset)); }  private static long normalize(int value) {     if(value >= 0) return value;     return (~0l >>> 32) & value; } 

i tried example got illegalargumentexception. can please in getting example worked.

my advice: don't this!

if need erase string, can "safely" using reflection dig out string object's private chars array , filling nul characters. of course, need sure string erasing not shared other code; e.g. has not been interned.

the code copying looks broken. start, seems assuming references fit in int ... not 64 bit jvm. wouldn't trust code. wouldn't try fix it. wrong approach.

unsafe should used people really, know doing. copying else's code not substitute knowledge.

and in case, don't think original code erased characters properly. in fact, think merely dismantles string object, leaving char[] containing super-secret password intact in heap. blog post hints @ this.


in fact, next impossible guarantee have erased string. if succeed in erasing char[] containing characters, can't sure copy of data. instance, if string has been relocated gc, there still old copy of characters in memory @ original location. characters overwritten there no guarantees on when happen.

probably best can use jni / jna (or unsafe) allocate off-heap (that won't relocated gc) , over-write zeros before release it. obviously, can't string.

and ... there stale pages on paging device containing characters. or sufficient privilege set breakpoint , read secret out of memory.

my advice: make sure >>platform<< secured, both physically , access on network.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -