Here is a little nugget you might enjoy how to do some MD5 Encryption with Java pretty easy really. Mostly taken from this book:
package test.md5.encrypt;
import java.io.ByteArrayInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import junit.framework.TestCase;
public class TestMessageDigest extends TestCase {
private static String[] hexDigits = {"0", "1", "2", "3",
"4", "5", "6", "7",
"8", "9", "a", "b",
"c", "d", "e", "f"};
public void testEncrypt(){
MessageDigest md = null;
DigestInputStream dis = null;
String digestedString = null;
try{
md = MessageDigest.getInstance("MD5");
ByteArrayInputStream bis =
new ByteArrayInputStream("password".getBytes());
dis = new DigestInputStream(bis, md);
byte[] bytes = new byte[1024];
dis.read(bytes);
md = dis.getMessageDigest();
dis.close();
byte[] digest= md.digest();
digestedString =byteArrayToString(digest);
System.out.println(digestedString);
} catch (Exception e){
e.printStackTrace();
assertTrue(false);
}
}
private String byteToHexString(byte aByte){
int n = aByte;
if (n < 0) n = 256 + n;
int d1 = n/16;
int d2 = n%16;
return hexDigits[d1] + hexDigits[d2];
}
private String byteArrayToString(byte[] bytes){
String result = "";
for (int a = 0; a < bytes.length; a++){
result += byteToHexString(bytes[a]);
}
return result;
}
}
Not too bad is it? Thanks to Jamie Jaworski and Paule Perrone for authoring that book (heh, I actually got in on clearance for $15.00) not too shabby...
-Aaron
No comments:
Post a Comment