java - Generating an MD5 Hash with a char[] -


how 1 go converting char[] password obtained using method:

char[] password = passwordinputfield.getpassword(); 

to md5 hash? use method below, getbytes compatible strings:

messagedigest md = messagedigest.getinstance("md5"); md.update(password.getbytes()); string hashedpass = new biginteger(1, md.digest()).tostring(16); 

note: md5 hashing algorithm should never used password storage, it's hashes cracked. however, use simplicity.

the quick/easy/unsecure fix convert char array string. however, unsecure because strings immutable , can't cleared memory.

string password = new string(passwordinputfield.getpassword());  messagedigest md = messagedigest.getinstance("md5"); md.update(password.getbytes()); string hashedpass = new biginteger(1, md.digest()).tostring(16); 

a more secure solution: convert char[] byte[] , clear arrays memory afterward.

private byte[] tobytes(char[] chars) {     charbuffer charbuffer = charbuffer.wrap(chars);     bytebuffer bytebuffer = charset.forname("utf-8").encode(charbuffer);     byte[] bytes = arrays.copyofrange(bytebuffer.array(),             bytebuffer.position(), bytebuffer.limit());     arrays.fill(charbuffer.array(), '\u0000'); // clear sensitive data     arrays.fill(bytebuffer.array(), (byte) 0); // clear sensitive data     return bytes; }  char[] passchars = passwordinputfield.getpassword(); byte[] passbytes = tobytes(passchars);  messagedigest md = messagedigest.getinstance("md5"); md.update(passbytes); string hashedpass = new biginteger(1, md.digest()).tostring(16);  arrays.fill(passchars, '\u0000'); // clear sensitive data arrays.fill(passbytes, (byte) 0); // clear sensitive data 

edit:

updated answer more secure solution (credit user2656928 idea).

char[] byte[] method credit andreyne


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -