Java Tutorial/Security/MD5 Message Digest algorithm

Материал из Java эксперт
Перейти к: навигация, поиск

Check password based on MD5

   <source lang="java">

import java.io.BufferedReader; import java.io.FileReader; import java.security.MessageDigest; public class MainClass {

 public static void main(String args[]) throws Exception {
   String name = "";
   String passwd = "";
   BufferedReader in = new BufferedReader(new FileReader("passwd.txt"));
   while ((name = in.readLine()) != null) {
     passwd = in.readLine();
     if (name.equals(args[0])) {
       break;
     }
   }
   MessageDigest m = MessageDigest.getInstance("MD5");
   m.update(args[1].getBytes("UTF8"));
   byte s[] = m.digest();
   String result = "";
   for (int i = 0; i < s.length; i++) {
     result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
   }
   System.out.println(name.equals(args[0]) && result.equals(passwd));
 }

}</source>





Check password salt based on MD5

   <source lang="java">

import java.security.MessageDigest;

public class MainClass {

 public static void main(String args[]) throws Exception {
   String name = "name";
   String passwd = "password";
   String salts = "12,12,12";
   String salttmp[] = salts.split(",");
   byte salt[] = new byte[salttmp.length];
   for (int i = 0; i < salt.length; i++) {
     salt[i] = Byte.parseByte(salttmp[i]);
   }
   MessageDigest m = MessageDigest.getInstance("MD5");
   m.update(salt);
   m.update("name".getBytes("UTF8"));
   byte s[] = m.digest();
   String result = "";
   for (int i = 0; i < s.length; i++) {
     result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
   }
   System.out.println(result.equals(passwd));
 }

}</source>





creates an MD5 message digest from a file and displays it to the screen BASE64 Encoded.

   <source lang="java">

import java.io.BufferedInputStream; import java.io.FileInputStream; import java.security.MessageDigest; import sun.misc.BASE64Encoder; public class MainClass {

 public static void main(String[] args) throws Exception {
   MessageDigest md = MessageDigest.getInstance("MD5");
   BufferedInputStream in = new BufferedInputStream(new FileInputStream("inputfile.txt"));
   int theByte = 0;
   while ((theByte = in.read()) != -1) {
     md.update((byte) theByte);
   }
   in.close();
   byte[] theDigest = md.digest();
   System.out.println(new BASE64Encoder().encode(theDigest));
 }

}</source>





Creating a Keyed Digest Using MD5

   <source lang="java">

import java.security.MessageDigest; public class Main {

 public static void main(String[] a) throws Exception {
   byte[] buffer = new byte[10000];
   byte[] key = new byte[8];
   MessageDigest md5 = MessageDigest.getInstance("MD5");
   md5.update(buffer);
   byte[] k = md5.digest(key);
 }

}</source>





Encode an MD5 digest into a String.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/**

* Encode an MD5 digest into a String.
*

* The 128 bit MD5 hash is converted into a 32 character long String. * Each character of the String is the hexadecimal representation of 4 bits * of the digest. * * @author Remy Maucherat * @version $Revision: 515 $ $Date: 2008-03-17 22:02:23 +0100 (Mon, 17 Mar 2008) $ */ public final class MD5Encoder { // ----------------------------------------------------- Instance Variables private static final char[] hexadecimal = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}; // --------------------------------------------------------- Public Methods /** * Encodes the 128 bit (16 bytes) MD5 into a 32 character String. * * @param binaryData Array containing the digest * @return Encoded MD5, or null if encoding failed */ public String encode( byte[] binaryData ) { if (binaryData.length != 16) return null; char[] buffer = new char[32]; for (int i=0; i<16; i++) { int low = (int) (binaryData[i] & 0x0f); int high = (int) ((binaryData[i] & 0xf0) >> 4); buffer[i*2] = hexadecimal[high]; buffer[i*2 + 1] = hexadecimal[low]; } return new String(buffer); } }</source>

Get MD5 Base64

   <source lang="java">

/*

* $Header: /cvsroot/mvnforum/mvnforum/contrib/phpbb2mvnforum/src/org/mvnforum/util/MD5.java,v 1.6 2007/01/15 10:27:31 dungbtm Exp $
* $Author: dungbtm $
* $Revision: 1.6 $
* $Date: 2007/01/15 10:27:31 $
*
*
* Copyright (C) 2002-2007 by MyVietnam.net
*
* All copyright notices regarding mvnForum MUST remain 
* intact in the scripts and in the outputted HTML.
* The "powered by" text/logo with a link back to
* http://www.mvnForum.ru and http://www.MyVietnam.net in 
* the footer of the pages MUST remain visible when the pages
* are viewed on the internet or intranet.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
* Support can be obtained from support forums at:
* http://www.mvnForum.ru/mvnforum/index
*
* Correspondence and Marketing Questions can be sent to:
* info at MyVietnam net
*
* @author: 
*/

import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; // The JavaReference.ru Software License, Version 1.0 // Copyright (c) 2002-2005 JavaReference.ru. All rights reserved. // // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. The end-user documentation included with the redistribution, if any, must // include the following acknowlegement: // // "This product includes software developed by the Javareference.ru // (http://www.javareference.ru/)." // // Alternately, this acknowlegement may appear in the software itself, if and // wherever such third-party acknowlegements normally appear. // // 4. The names "JavaReference" and "Javareference.ru", must not be used to // endorse or promote products derived from this software without prior written // permission. For written permission, please contact webmaster@javareference.ru. // // 5. Products derived from this software may not be called "Javareference" nor may // "Javareference" appear in their names without prior written permission of // Javareference.ru. // // THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // JAVAREFERENCE.ru OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Software from this site consists of contributions made by various individuals // on behalf of Javareference.ru. For more information on Javareference.ru, // please see http://www.javareference.ru /**

* @author anandh
*/

public class MD5 {

   static char[] carr = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
   public static String getBase64FromHEX(String input) {
       
       byte barr[] = new byte[16];
       int bcnt = 0;
       for (int i = 0; i < 32; i += 2) {
           char c1 = input.charAt(i);
           char c2 = input.charAt(i + 1);
           int i1 = intFromChar(c1);
           int i2 = intFromChar(c2);
           barr[bcnt] = 0;
           barr[bcnt] |= (byte) ((i1 & 0x0F) << 4);
           barr[bcnt] |= (byte) (i2 & 0x0F);
           bcnt++;
       }
       BASE64Encoder encoder = new BASE64Encoder();
       return encoder.encode(barr);
   }
   public static synchronized String getMD5_Base64(String input) {
       // please note that we dont use digest, because if we
       // cannot get digest, then the second time we have to call it
       // again, which will fail again
       MessageDigest digest = null;
       try {
           digest = MessageDigest.getInstance("MD5");
       } catch (Exception ex) {
           ex.printStackTrace();
       }
       if (digest == null)
           return input;
       // now everything is ok, go ahead
       try {
           digest.update(input.getBytes("UTF-8"));
       } catch (java.io.UnsupportedEncodingException ex) {
           ex.printStackTrace();
       }
       byte[] rawData = digest.digest();
       BASE64Encoder bencoder = new BASE64Encoder();
       return bencoder.encode(rawData);
   }
   private static int intFromChar(char c) {
       char clower = Character.toLowerCase(c);
       for (int i = 0; i < carr.length; i++) {
           if (clower == carr[i]) {
               return i;
           }
       }
       return 0;
   }
   public static void main(String[] args) {
       
       //String password = args[0];
       String password = "test";
       MessageDigest digest = null;
       try {
           digest = MessageDigest.getInstance("MD5");
       } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
       }
       try {
           digest.update(password.getBytes("UTF-8"));
       } catch (UnsupportedEncodingException ex) {
           ex.printStackTrace();
       }
       byte[] rawData = digest.digest();
       StringBuffer printable = new StringBuffer();
       for (int i = 0; i < rawData.length; i++) {
           printable.append(carr[((rawData[i] & 0xF0) >> 4)]);
           printable.append(carr[(rawData[i] & 0x0F)]);
       }
       String phpbbPassword = printable.toString();
       System.out.println("PHPBB           : " + phpbbPassword);
       System.out.println("MVNFORUM        : " + getMD5_Base64(password));
       System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword));
   }

}</source>





Hash 32 String

   <source lang="java">

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; public class Strings {

 private static final MessageDigest MESSAGE_DIGEST;
 public static final String[] EMPTY_ARRAY = new String[0];
 static {
     MessageDigest md;
     try {
         md = MessageDigest.getInstance("MD5");
     } catch(NoSuchAlgorithmException err) {
       throw new IllegalStateException();
     }
     MESSAGE_DIGEST = md;
 }
 private static final String HEX_CHARS = "0123456789ABCDEF";
 
 public static String getMD5(String source) {    
     byte[] bytes;
     try {
       bytes = source.getBytes("UTF-8");
     } catch(java.io.UnsupportedEncodingException ue) {
       throw new IllegalStateException(ue);
     }
     byte[] result;
     synchronized(MESSAGE_DIGEST) {
         MESSAGE_DIGEST.update(bytes);
         result = MESSAGE_DIGEST.digest();
     }
     char[] resChars = new char[32];
     int len = result.length;
     for(int i = 0; i < len; i++) {
         byte b = result[i];
         int lo4 = b & 0x0F;
         int hi4 = (b & 0xF0) >> 4;
         resChars[i*2] = HEX_CHARS.charAt(hi4);
         resChars[i*2 + 1] = HEX_CHARS.charAt(lo4);
     }
     return new String(resChars);
 }
 
 public static String getHash32(String source) throws UnsupportedEncodingException {
     String md5 = getMD5(source);
     return md5.substring(0, 8);
 }      
 public static String getHash64(String source) throws UnsupportedEncodingException {
     String md5 = getMD5(source);
     return md5.substring(0, 16);
 }   
 

}</source>





Hash 64 String

   <source lang="java">

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; public class Strings {

 private static final MessageDigest MESSAGE_DIGEST;
 public static final String[] EMPTY_ARRAY = new String[0];
 static {
     MessageDigest md;
     try {
         md = MessageDigest.getInstance("MD5");
     } catch(NoSuchAlgorithmException err) {
       throw new IllegalStateException();
     }
     MESSAGE_DIGEST = md;
 }
 private static final String HEX_CHARS = "0123456789ABCDEF";
 
 public static String getMD5(String source) {    
     byte[] bytes;
     try {
       bytes = source.getBytes("UTF-8");
     } catch(java.io.UnsupportedEncodingException ue) {
       throw new IllegalStateException(ue);
     }
     byte[] result;
     synchronized(MESSAGE_DIGEST) {
         MESSAGE_DIGEST.update(bytes);
         result = MESSAGE_DIGEST.digest();
     }
     char[] resChars = new char[32];
     int len = result.length;
     for(int i = 0; i < len; i++) {
         byte b = result[i];
         int lo4 = b & 0x0F;
         int hi4 = (b & 0xF0) >> 4;
         resChars[i*2] = HEX_CHARS.charAt(hi4);
         resChars[i*2 + 1] = HEX_CHARS.charAt(lo4);
     }
     return new String(resChars);
 }
 
 public static String getHash32(String source) throws UnsupportedEncodingException {
     String md5 = getMD5(source);
     return md5.substring(0, 8);
 }      
 public static String getHash64(String source) throws UnsupportedEncodingException {
     String md5 = getMD5(source);
     return md5.substring(0, 16);
 }   
 

}</source>





MD5 BASE64 checksum for the specified input string.

   <source lang="java">

import javax.swing.JOptionPane; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /**

* MD5 common utils. Check and calculate MD5 BASE64 sum.
* 
* @author Luigi Zurolo - Liscio Luca
* @version 1.1
*/

public class MD5 {

 /**
  * MD5 BASE64 checksum for the specified input string.
  * 
  * @param input -
  *          Specified input string
  * @return String - MD5 BASE64 sum
  */
 public static String checkMD5(String input) {
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     md.update(input.getBytes());
     byte[] enc = md.digest();
     String md5Sum = new sun.misc.BASE64Encoder().encode(enc);
     return md5Sum;
   } catch (NoSuchAlgorithmException nsae) {
     System.out.println(nsae.getMessage());
     return null;
   }
 }

}</source>





MD5 hashing: Encodes a string

   <source lang="java">

/*

* Copyright (c) JForum Team
* All rights reserved.
* 
* Redistribution and use in source and binary forms, 
* with or without modification, are permitted provided 
* that the following conditions are met:
* 
* 1) Redistributions of source code must retain the above 
* copyright notice, this list of conditions and the 
* following  disclaimer.
* 2)  Redistributions in binary form must reproduce the 
* above copyright notice, this list of conditions and 
* the following disclaimer in the documentation and/or 
* other materials provided with the distribution.
* 3) Neither the name of "Rafael Steil" nor 
* the names of its contributors may be used to endorse 
* or promote products derived from this software without 
* specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
* IN CONTRACT, STRICT LIABILITY, OR TORT 
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
* 
* This file creation date: Mar 29, 2003 / 1:15:50 AM
* The JForum Project
* http://www.jforum.net
*/

import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;

/**

* Encodes a string using MD5 hashing 
* 
* @author Rafael Steil
* @version $Id: MD5.java,v 1.7 2006/08/23 02:13:44 rafaelsteil Exp $
*/

public class MD5 {

 /**
  * Encodes a string
  * 
  * @param str String to encode
  * @return Encoded String
  * @throws NoSuchAlgorithmException
  */
 public static String crypt(String str)
 {
   if (str == null || str.length() == 0) {
     throw new IllegalArgumentException("String to encript cannot be null or zero length");
   }
   
   StringBuffer hexString = new StringBuffer();
   
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     md.update(str.getBytes());
     byte[] hash = md.digest();
     
     for (int i = 0; i < hash.length; i++) {
       if ((0xff & hash[i]) < 0x10) {
         hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
       }       
       else {
         hexString.append(Integer.toHexString(0xFF & hash[i]));
       }       
     }
   }
   catch (NoSuchAlgorithmException e) {
     throw new RuntimeException("" + e);
   }
   
   return hexString.toString();
 }

}</source>





MD5 MessageDigest your message

   <source lang="java">

import java.io.FileInputStream; import java.security.DigestInputStream; import java.security.MessageDigest; public class MainClass {

 public static void main(String args[]) throws Exception {
   MessageDigest m = MessageDigest.getInstance("MD5");
   FileInputStream fin = new FileInputStream(args[0]);
   DigestInputStream din = new DigestInputStream(fin, m);
   din.on(false);
   int b;
   while ((b = din.read()) != -1) {
     if (b == "X") {
       din.on(true);
     }
   }
   byte s[] = m.digest();
   for (int i = 0; i < s.length; i++) {
     System.out.print( Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6));
   }
 }

}</source>





MD5 String

   <source lang="java">

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; public class Strings {

 private static final MessageDigest MESSAGE_DIGEST;
 public static final String[] EMPTY_ARRAY = new String[0];
 static {
     MessageDigest md;
     try {
         md = MessageDigest.getInstance("MD5");
     } catch(NoSuchAlgorithmException err) {
       throw new IllegalStateException();
     }
     MESSAGE_DIGEST = md;
 }
 private static final String HEX_CHARS = "0123456789ABCDEF";
 
 public static String getMD5(String source) {    
     byte[] bytes;
     try {
       bytes = source.getBytes("UTF-8");
     } catch(java.io.UnsupportedEncodingException ue) {
       throw new IllegalStateException(ue);
     }
     byte[] result;
     synchronized(MESSAGE_DIGEST) {
         MESSAGE_DIGEST.update(bytes);
         result = MESSAGE_DIGEST.digest();
     }
     char[] resChars = new char[32];
     int len = result.length;
     for(int i = 0; i < len; i++) {
         byte b = result[i];
         int lo4 = b & 0x0F;
         int hi4 = (b & 0xF0) >> 4;
         resChars[i*2] = HEX_CHARS.charAt(hi4);
         resChars[i*2 + 1] = HEX_CHARS.charAt(lo4);
     }
     return new String(resChars);
 }
 
 public static String getHash32(String source) throws UnsupportedEncodingException {
     String md5 = getMD5(source);
     return md5.substring(0, 8);
 }      
 public static String getHash64(String source) throws UnsupportedEncodingException {
     String md5 = getMD5(source);
     return md5.substring(0, 16);
 }   
 

}</source>





MD5 your password

   <source lang="java">

import java.security.MessageDigest; public class MainClass {

 public static void main(String args[]) throws Exception {
   String name = "name";
   String passwd = "password";
   MessageDigest m = MessageDigest.getInstance("MD5");
   m.update(passwd.getBytes("UTF8"));
   byte s[] = m.digest();
   String result = "";
   for (int i = 0; i < s.length; i++) {
     result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
   }
   System.out.println(name);
   System.out.println(result);
 }

} /*name 5f4dcc3b5aa765d61d8327deb882cf99*/</source>





Password Authenticator

   <source lang="java">

import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.security.MessageDigest; import java.util.Arrays; public class MainClass {

 public static void main(String[] args) throws Exception {
   authenticatePassword("password");
 }
 private static void authenticatePassword(String password) throws Exception {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   FileInputStream fis = new FileInputStream("password");
   int theByte = 0;
   while ((theByte = fis.read()) != -1) {
     baos.write(theByte);
   }
   fis.close();
   byte[] hashedPasswordWithSalt = baos.toByteArray();
   baos.reset();
   byte[] salt = new byte[12];
   System.arraycopy(hashedPasswordWithSalt, 0, salt, 0, 12);
   MessageDigest md = MessageDigest.getInstance("MD5");
   md.update(salt);
   md.update(password.getBytes("UTF8"));
   byte[] digest = md.digest();
   byte[] digestInFile = new byte[hashedPasswordWithSalt.length - 12];
   System.arraycopy(hashedPasswordWithSalt, 12, digestInFile, 0,
       hashedPasswordWithSalt.length - 12);
   System.out.println(Arrays.equals(digest, digestInFile));
 }

}</source>





Password Storage Example

   <source lang="java">

import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; public class MainClass {

 public static void main(String[] args) throws Exception {
   createPassword("password");
 }
 private static void createPassword(String password) throws Exception {
   SecureRandom random = new SecureRandom();
   byte[] salt = new byte[12];
   random.nextBytes(salt);
   MessageDigest md = MessageDigest.getInstance("MD5");
   md.update(salt);
   md.update(password.getBytes("UTF8"));
   byte[] digest = md.digest();
   FileOutputStream fos = new FileOutputStream("password");
   fos.write(salt);
   fos.write(digest);
   fos.close();
 }

}</source>





Set password salt

   <source lang="java">

import java.security.MessageDigest; import java.util.Random; public class MainClass {

 public static void main(String args[]) throws Exception {
   String name = "name";
   String passwd = "password";
   Random rand = new Random();
   byte[] salt = new byte[12];
   rand.nextBytes(salt);
   MessageDigest m = MessageDigest.getInstance("MD5");
   m.update(salt);
   m.update(passwd.getBytes("UTF8"));
   byte s[] = m.digest();
   String result = "";
   for (int i = 0; i < s.length; i++) {
     result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
   }
   System.out.println(name);
   for (int i = 0; i < salt.length; i++) {
     System.out.print(salt[i] + ",");
   }
   System.out.println(result);
 }

} /*name 72,83,-8,78,-82,125,0,-37,-116,-83,-72,27,460a21b49082e5268a4016bfa2e2885c*/</source>