Naveen Attri Naveen Attri - 8 months ago 53
Java Question

Java: How to generate a encrypted string which doesn't contain comma or newline?

I need to generate a hashed string(md5 or sha-1 or whatever) which doesn't contain a comma or next line because I'm storing with some more data in a csv file.I've tried, after generating md5 normally, replacing all occurrences of ',' and '\n' by String.replace, but somehow, there are still some newline characters or some characters that behave like newline. Is there a way, to generates only alphabets and numbers in the string while encrypting?

This is my code.

public static String hashPassword(String password)
MessageDigest md=null;
try {
} catch (NoSuchAlgorithmException e) {
String passwd=new String (md.digest(password.getBytes()));

//To convert it to ',' so that it'll be removed with other ',''s
return passwd;

Answer Source

Don't use new String() or getBytes() without specifying an encoding. As soon as you move to a different platform (with a different default encoding), that will blow up spectacularly.

The safest way would be to convert the bytes to a hex string, although that will also double the size needed to store it. E.g. (using UTF-8 as encoding)

BigInteger foo = new BigInteger(md.digest(password.getBytes("UTF-8"))); 
String hex = foo.toString(16);