免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2052 | 回复: 0
打印 上一主题 下一主题

基于jdk1.5的简单的md5加密解密算法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-02-28 10:12 |只看该作者 |倒序浏览
需求:从文本读入明文,加密成密文保存在文件out.txt中。在某处需要时从文件中读入密文,和用户输入的明文的哈希后的结果进行比较,如果相等则表示用户输入的明文正确。

明文文件:password.properties. 在classpath的根目录上
文件内容:
       #user and password input text
lts.login.user.text = admin
lts.login.password.text = welcome
密文文件:out.txt. 在classpath的根目录上。
写入后文件的内容:
       lts.user.cipher=!#/)zW??C?J_J?_?
lts.password.cipher=@?NY??????_???
我是统一放在res source folder下。

读取明文信息:
package com.ldd600.login.encrypt;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
*
* Add your class description here...
*
* @author ldd600
* @version 1.0, 2008-2-28
*/
public class FileDisposer {
       private static final String FILENAME = "password.properties";
      
       private static final String LOGIN_USER_KEY = "lts.login.user.text";
      
       private static final String LOGIN_PASSWORD = "lts.login.password.text";
      
       public static final FileDisposer FILE_DISPOSER_INSTANCE = new FileDisposer();
      
       public static final String LINE_SEPARATOR = System.getProperty("line.separator");
      
       private String userText;
      
       private String passwordText;
      
       private Properties infoText = new Properties();;
      
       private FileDisposer() {
              ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
              if(classLoader == null) {
                     classLoader = ClassLoader.getSystemClassLoader();
              }
              InputStream infoStream = classLoader.getResourceAsStream(FILENAME);
              try {
                     infoText.load(infoStream);
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              this.userText = infoText.getProperty(LOGIN_USER_KEY);
              this.passwordText = infoText.getProperty(LOGIN_PASSWORD);
       }

       public String getUserText() {
              return userText;
       }


       public String getPasswordText() {
              return passwordText;
       }
      
      
}

获得哈希值并保存到out.txt中:
package com.ldd600.login.encrypt;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
*
* Add your class description here...
*
* @author ldd600
* @version 1.0, 2008-2-28
*/
public class CipherGenerator {
    public static final String LOGIN_USER_CIPHER_KEY = "lts.user.cipher";
    public static final String LOGIN_PASS_CIPHER_KEY = "lts.password.cipher";
    /**
     * Convert a byte array of 8 bit characters into a String.
     *
     * @param bytes
     *                the array containing the characters
     * @param length
     *                the number of bytes to process
     * @return a String representation of bytes
     */
    public static String byteArrToString(byte[] bytes, int length) {
       char[] chars = new char[length];

       for (int i = 0; i != chars.length; i++) {
           chars = (char) (bytes & 0xff);
       }

       return new String(chars);
    }

    /**
     * Convert a byte array of 8 bit characters into a String.
     *
     * @param bytes
     *                the array containing the characters
     * @param length
     *                the number of bytes to process
     * @return a String representation of bytes
     */
    public static String byteArrToString(byte[] bytes) {
       return byteArrToString(bytes, bytes.length);
    }

    /**
     * Convert the passed in String to a byte array by taking the bottom 8
     * bits of each character it contains.
     *
     * @param string
     *                the string to be converted
     * @return a byte array representation
     */
    public static byte[] toByteArray(String string) {
       byte[] bytes = new byte[string.length()];
       char[] chars = string.toCharArray();

       for (int i = 0; i != chars.length; i++) {
           bytes = (byte) chars;
       }

       return bytes;
    }

    /**
     * Get a input string's hash value using md5 message digest algorithm
     * with utf-8 encode type
     *
     * @param input
     *                input string to get its hash value
     * @return input string's hash value
     */
    public static String getHashValue(String input) {
       if (null == input || input.trim().equals("")) {
           return input;
       }
       byte[] newPass = new byte[] {};
       try {
           newPass = input.getBytes("UTF-8");
       } catch (UnsupportedEncodingException e) {
           newPass = toByteArray(input);
       }

       MessageDigest hash;
       try {
           hash = MessageDigest.getInstance("MD5");
       } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
           throw new RuntimeException("not exsit md5 algorithm");
       }
       hash.update(newPass);
       byte[] cipherPass = hash.digest();
       try {
           input = new String(cipherPass, "UTF-8");
       } catch (UnsupportedEncodingException e) {
           input = byteArrToString(cipherPass);
       }
       return input;
    }
   
    public static void writeFile(String fileName, String text) throws IOException {
       File outputFile = new File(fileName);
       PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
       out.print(text);
       out.close();
    }

    public static void main(String[] args) throws IOException {
       FileDisposer disposer = FileDisposer.FILE_DISPOSER_INSTANCE;
       String userText = disposer.getUserText();
       String passText = disposer.getPasswordText();
       StringBuffer sb = new StringBuffer("lts.user.cipher=");
       sb.append(getHashValue(userText));
       sb.append(FileDisposer.LINE_SEPARATOR);
       sb.append("lts.password.cipher=");
       sb.append(getHashValue(passText));
       String fileName = "res/out.txt";
       writeFile(fileName, sb.toString());
    }
}


简单的测试程序(读取密文比较时可参考该测试程序):
package com.ldd600.lts.login.encrypt;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import junit.framework.TestCase;

/**
*
* Add your class description here...
*
* @author ldd00
* @version 1.0, 2008-2-28
*/
public class CipherGeneratorTest extends TestCase {
    private String userCipher;
   
    private String passCipher;
   
    @Override
    protected void setUp() throws Exception {
       Properties props = new Properties();
       ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
       if(classLoader == null) {
           classLoader = ClassLoader.getSystemClassLoader();
       }
       InputStream infoStream = classLoader.getResourceAsStream("out.txt");
       BufferedReader bfReader = new BufferedReader(new InputStreamReader(infoStream));
       props.load(infoStream);
       this.userCipher = props.getProperty("lts.user.cipher");
       this.passCipher = props.getProperty("lts.password.cipher");
       bfReader.close();
    }
   
    public void testEncrypt() throws UnsupportedEncodingException {
       String userText = FileDisposer.FILE_DISPOSER_INSTANCE.getUserText();
       String passText = FileDisposer.FILE_DISPOSER_INSTANCE.getPasswordText();
       assertEquals(new String(CipherGenerator.getHashValue(userText).getBytes(), "UTF-8"), userCipher);
       assertEquals(new String(CipherGenerator.getHashValue(passText).getBytes(), "UTF-8"), passCipher);
    }
   
}



注意:整个过程中需要注意字符编码的问题。上述例子中统一使用UTF-8编码。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/19897/showart_485627.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP