| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

メッセージダイジェスト

提供: MyMemoWiki
2020年2月16日 (日) 04:20時点におけるPiroto (トーク | 投稿記録)による版
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

メッセージダイジェスト

Java |

  1. /*
  2. * create : 2004/12/22
  3. * creator: yagi
  4. * version: 1.0
  5. * summary:
  6. *
  7. * history:
  8. * 1.0 新規作成
  9. */
  10. import java.security.MessageDigest;
  11. import java.security.NoSuchAlgorithmException;
  12.  
  13. public class Security {
  14. /**
  15. * MessageDigestインスタンス
  16. */
  17. private static MessageDigest md = null;
  18. /**
  19. * 暗号化に使用するアルゴリズム
  20. */
  21. public static final String DIGEST_ALGORITHM = "SHA";
  22. /**
  23. * パスワードをハッシュ関数(一方向要約関数)で、暗号化する
  24. * @param orginalPassword
  25. * @return
  26. * @throws NoSuchAlgorithmException
  27. */
  28. public static String getCryptPassWord(String orginalPassword) throws NoSuchAlgorithmException {
  29. byte[] digest = getDigest(orginalPassword.getBytes());
  30. StringBuffer sb = new StringBuffer();
  31. for(int i = 0; i < digest.length; i++) {
  32. sb.append(Integer.toHexString((digest[i] >> 4) & 0x0f));
  33. sb.append(Integer.toHexString( digest[i] & 0x0f));
  34. }
  35. return new String(sb);
  36. }
  37.  
  38. /**
  39. * 暗号化前のパスワードと暗号化後のパスワードを比較する
  40. * @param orgPass
  41. * @param cryptPass
  42. * @return
  43. * @throws NoSuchAlgorithmException
  44. */
  45. public static boolean checkPassword(String orgPass, String cryptPass) throws NoSuchAlgorithmException {
  46. return MessageDigest.isEqual(
  47. getCryptPassWord(orgPass).getBytes(),
  48. cryptPass.getBytes());
  49. }
  50.  
  51. /**
  52. * 暗号化後のハッシュ値の桁数を取得する
  53. * @return
  54. * @throws NoSuchAlgorithmException
  55. */
  56. public static int getDigestLength() throws NoSuchAlgorithmException {
  57. return getMessageDigetst().getDigestLength();
  58. }
  59.  
  60. /**
  61. * ダイジェストを取得する
  62. * @param val
  63. * @return
  64. * @throws NoSuchAlgorithmException
  65. */
  66. private static byte[] getDigest(byte[] val)
  67. throws NoSuchAlgorithmException {
  68. getMessageDigetst().update(val);
  69. byte[] digest = getMessageDigetst().digest();
  70. resetDigest();
  71. return digest;
  72. }
  73.  
  74. /**
  75. * MessageDigestのインスタンスを取得
  76. * @return
  77. * @throws NoSuchAlgorithmException
  78. */
  79. private static MessageDigest getMessageDigetst() throws NoSuchAlgorithmException {
  80. if (md == null) {
  81. md = MessageDigest.getInstance(DIGEST_ALGORITHM);
  82. }
  83. return md;
  84. }
  85. /**
  86. * MessageDigestのインスタンスを初期化
  87. * @throws NoSuchAlgorithmException
  88. */
  89. private static void resetDigest() throws NoSuchAlgorithmException {
  90. getMessageDigetst().reset();
  91. }
  92. }