I am trying to write a password encryption class that I can use to encrypt and store user passwords. I want to make sure that I am doing this correctly. This code works fine and appears to generate an encrypted password, but I wanted to post it here to get some feedback. For me, this is fairly complicated, and I know with anything in crypto, it's easy to make mistakes without realizing that you are making them.
Here is my code:
public CipherHandler {
public String encryptPassword(char[] plaintext, String encoding) throws Exception {
MessageDigest msgDigest = null;
String hashValue = null;
/* Convert char array plaintext to byte array */
byte[] b = new byte[plaintext.length << 1];
for (int i = 0; i < plaintext.length; i++) {
b[i] = (byte) plaintext[i]; //will this work regardless of encoding?
}
try {
msgDigest = MessageDigest.getInstance("SHA-256");
msgDigest.update(b);
byte rawByte[] = msgDigest.digest();
hashValue = (new BASE64Encoder()).encode(rawByte);
} catch (NoSuchAlgorithmException e) {
System.out.println("No Such Algorithm Exists");
}
System.out.println(hashValue);
return hashValue;
}
}
This function will generally be called from a Swing event handler where the user will enter their password into a JPassword field, which is why I am starting with a char[]. For testing, I am using this code to call the function:
CipherHandler cp = new CipherHandler();
String initPW;
try {
initPW = cp.encryptPassword("welcome".toCharArray(), "UTF-8");
}
As this is my first attempt at this, I imagine that I have overlooked something. I'm interested in any advice or comments. I do have a couple of specific questions, though:
When I convert the char[] to a byte[], I don't trust that I am doing this correctly. How do I know which encoding to use? Here, I put "UTF-8" in, mostly as a placeholder, but I am concerned that this may fail in some circumstances.
I have read that I should be using salt and iterations after the password has been digested, but I can't figure out how to do this. Can somebody please advise me on this?
I am using SHA-256. Is this the suggested algorithm? I have read about MD5, also. Is there one algorithm that is preferable for password encryption?
Thanks for any help. I appreciate it!