PageRenderTime 24ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/mpv5/utils/text/MD5HashGenerator.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 76 lines | 44 code | 17 blank | 15 comment | 4 complexity | bfbd57eec46b1a530554fd9fce018090 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0, GPL-3.0, GPL-2.0, AGPL-3.0, JSON, BSD-3-Clause
  1. package mpv5.utils.text;
  2. //~--- JDK imports ------------------------------------------------------------
  3. import java.security.*;
  4. /**
  5. *
  6. * @author pertinax
  7. */
  8. public class MD5HashGenerator {
  9. private static final char[] hexChars = {
  10. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  11. };
  12. static private MD5HashGenerator md5 = null;
  13. private MessageDigest md = null;
  14. /**
  15. * Constructor is private so you must use the getInstance method
  16. */
  17. private MD5HashGenerator() throws NoSuchAlgorithmException {
  18. md = MessageDigest.getInstance("MD5");
  19. }
  20. /**
  21. * This returns the singleton instance
  22. * @return
  23. * @throws NoSuchAlgorithmException
  24. */
  25. public static MD5HashGenerator getInstance() throws NoSuchAlgorithmException {
  26. if (md5 == null) {
  27. md5 = new MD5HashGenerator();
  28. }
  29. return (md5);
  30. }
  31. public String hashData(char[] password) {
  32. byte[] byteArray = new byte[password.length];
  33. for (int i = 0; i < password.length; i++) {
  34. byteArray[i] = (byte) password[i];
  35. }
  36. return hashData(byteArray);
  37. }
  38. public String hashData(byte[] dataToHash) {
  39. return hexStringFromBytes((calculateHash(dataToHash)));
  40. }
  41. private byte[] calculateHash(byte[] dataToHash) {
  42. md.update(dataToHash, 0, dataToHash.length);
  43. return (md.digest());
  44. }
  45. public String hexStringFromBytes(byte[] b) {
  46. String hex = "";
  47. int msb;
  48. int lsb = 0;
  49. int i;
  50. // MSB maps to idx 0
  51. for (i = 0; i < b.length; i++) {
  52. msb = ((int) b[i] & 0x000000FF) / 16;
  53. lsb = ((int) b[i] & 0x000000FF) % 16;
  54. hex = hex + hexChars[msb] + hexChars[lsb];
  55. }
  56. return (hex);
  57. }
  58. }
  59. //~ Formatted by Jindent --- http://www.jindent.com