当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现DES加密与解密,md5加密以及Java实现MD5加密解密类

Java实现DES加密与解密,md5加密以及Java实现MD5加密解密类

2019年07月22日  | 移动技术网IT编程  | 我要评论

很多时候要对秘要进行持久化加密,此时的加密采用md5。采用对称加密的时候就采用des方法了

import java.io.ioexception;
  import java.security.messagedigest;
  import java.security.securerandom;
  import javax.crypto.cipher;
  import javax.crypto.secretkey;
  import javax.crypto.secretkeyfactory;
  import javax.crypto.spec.deskeyspec;
 import sun.misc.basedecoder;
 import sun.misc.baseencoder;
 /**
  * 密匙工具类(包含des加密与md加密)
  * @author mingge
  *
  */
 public class keysutil {
     private final static string des = "des";
     private final static string md = "md";
     private final static string key="opeddsaeaddadbcabf";
     /**
      * md加密算法
      * @param data
      * @return
      */
     public static string mdencrypt(string data) {
       string resultstring = null;
       try {
         resultstring = new string(data);
         messagedigest md = messagedigest.getinstance(md);
         resultstring =bytehexstring(md.digest(resultstring.getbytes()));
       } catch (exception ex) {
       }
       return resultstring;
     }
     private static string bytehexstring(byte[] bytes) {
       stringbuffer bf = new stringbuffer(bytes.length * );
       for (int i = ; i < bytes.length; i++) {
         if ((bytes[i] & xff) < x) {
           bf.append("t");
         }
         bf.append(long.tostring(bytes[i] & xff, ));
       }
       return bf.tostring();
     }
     /**
      * description 根据键值进行加密
      * @param data 
      * @param key 加密键byte数组
      * @return
      * @throws exception
      */
     public static string desencrypt(string data, string key) throws exception {
       if (key==null) {
         key=key;
       }
       byte[] bt = encrypt(data.getbytes(), key.getbytes());
       string strs = new baseencoder().encode(bt);
       return strs;
     }
     /**
      * description 根据键值进行解密
      * @param data
      * @param key 加密键byte数组
      * @return
      * @throws ioexception
      * @throws exception
      */
     public static string desdecrypt(string data, string key) throws ioexception,
         exception {
       if (data == null){
         return null;
       }
       if (key==null) {
         key=key;
       }
       basedecoder decoder = new basedecoder();
       byte[] buf = decoder.decodebuffer(data);
       byte[] bt = decrypt(buf,key.getbytes());
       return new string(bt);
     }
     /**
      * description 根据键值进行加密
      * @param data
      * @param key 加密键byte数组
      * @return
      * @throws exception
      */
     private static byte[] encrypt(byte[] data, byte[] key) throws exception {
       // 生成一个可信任的随机数源
       securerandom sr = new securerandom();
       // 从原始密钥数据创建deskeyspec对象
       deskeyspec dks = new deskeyspec(key);
       // 创建一个密钥工厂,然后用它把deskeyspec转换成secretkey对象
       secretkeyfactory keyfactory = secretkeyfactory.getinstance(des);
       secretkey securekey = keyfactory.generatesecret(dks);
       // cipher对象实际完成加密操作
       cipher cipher = cipher.getinstance(des);
       // 用密钥初始化cipher对象
       cipher.init(cipher.encrypt_mode, securekey, sr);
       return cipher.dofinal(data);
     }
     /**
     * description 根据键值进行解密
     * @param data
     * @param key 加密键byte数组
     * @return
     * @throws exception
     */
     private static byte[] decrypt(byte[] data, byte[] key) throws exception {
       // 生成一个可信任的随机数源
       securerandom sr = new securerandom();
       // 从原始密钥数据创建deskeyspec对象
       deskeyspec dks = new deskeyspec(key);
       // 创建一个密钥工厂,然后用它把deskeyspec转换成secretkey对象
       secretkeyfactory keyfactory = secretkeyfactory.getinstance(des);
       secretkey securekey = keyfactory.generatesecret(dks);
       // cipher对象实际完成解密操作
       cipher cipher = cipher.getinstance(des);
       // 用密钥初始化cipher对象
       cipher.init(cipher.decrypt_mode, securekey, sr);
       return cipher.dofinal(data);
     }
 }

下面在给大家介绍一段代码关于java实现md5加密解密类

java实现md5加密以及解密类,附带测试类,具体见代码。

md5加密解密类——mymd5util,代码如下:

package com.zyg.security.md5; 
import java.io.unsupportedencodingexception; 
import java.security.messagedigest; 
import java.security.nosuchalgorithmexception; 
import java.security.securerandom; 
import java.util.arrays; 
public class mymd5util { 
  private static final string hex_nums_str="0123456789abcdef"; 
  private static final integer salt_length = 12; 
  /** 
   * 将16进制字符串转换成字节数组 
   * @param hex 
   * @return 
   */ 
  public static byte[] hexstringtobyte(string hex) { 
    int len = (hex.length() / 2); 
    byte[] result = new byte[len]; 
    char[] hexchars = hex.tochararray(); 
    for (int i = 0; i < len; i++) { 
      int pos = i * 2; 
      result[i] = (byte) (hex_nums_str.indexof(hexchars[pos]) << 4  
              | hex_nums_str.indexof(hexchars[pos + 1])); 
    } 
    return result; 
  } 
  /** 
   * 将指定byte数组转换成16进制字符串 
   * @param b 
   * @return 
   */ 
  public static string bytetohexstring(byte[] b) { 
    stringbuffer hexstring = new stringbuffer(); 
    for (int i = 0; i < b.length; i++) { 
      string hex = integer.tohexstring(b[i] & 0xff); 
      if (hex.length() == 1) { 
        hex = '0' + hex; 
      } 
      hexstring.append(hex.touppercase()); 
    } 
    return hexstring.tostring(); 
  } 
  /** 
   * 验证口令是否合法 
   * @param password 
   * @param passwordindb 
   * @return 
   * @throws nosuchalgorithmexception 
   * @throws unsupportedencodingexception 
   */ 
  public static boolean validpassword(string password, string passwordindb) 
      throws nosuchalgorithmexception, unsupportedencodingexception { 
    //将16进制字符串格式口令转换成字节数组 
    byte[] pwdindb = hexstringtobyte(passwordindb); 
    //声明盐变量 
    byte[] salt = new byte[salt_length]; 
    //将盐从数据库中保存的口令字节数组中提取出来 
    system.arraycopy(pwdindb, 0, salt, 0, salt_length); 
    //创建消息摘要对象 
    messagedigest md = messagedigest.getinstance("md5"); 
    //将盐数据传入消息摘要对象 
    md.update(salt); 
    //将口令的数据传给消息摘要对象 
    md.update(password.getbytes("utf-8")); 
    //生成输入口令的消息摘要 
    byte[] digest = md.digest(); 
    //声明一个保存数据库中口令消息摘要的变量 
    byte[] digestindb = new byte[pwdindb.length - salt_length]; 
    //取得数据库中口令的消息摘要 
    system.arraycopy(pwdindb, salt_length, digestindb, 0, digestindb.length); 
    //比较根据输入口令生成的消息摘要和数据库中消息摘要是否相同 
    if (arrays.equals(digest, digestindb)) { 
      //口令正确返回口令匹配消息 
      return true; 
    } else { 
      //口令不正确返回口令不匹配消息 
      return false; 
    } 
  } 
  /** 
   * 获得加密后的16进制形式口令 
   * @param password 
   * @return 
   * @throws nosuchalgorithmexception 
   * @throws unsupportedencodingexception 
   */ 
  public static string getencryptedpwd(string password) 
      throws nosuchalgorithmexception, unsupportedencodingexception { 
    //声明加密后的口令数组变量 
    byte[] pwd = null; 
    //随机数生成器 
    securerandom random = new securerandom(); 
    //声明盐数组变量 
    byte[] salt = new byte[salt_length]; 
    //将随机数放入盐变量中 
    random.nextbytes(salt); 
    //声明消息摘要对象 
    messagedigest md = null; 
    //创建消息摘要 
    md = messagedigest.getinstance("md5"); 
    //将盐数据传入消息摘要对象 
    md.update(salt); 
    //将口令的数据传给消息摘要对象 
    md.update(password.getbytes("utf-8")); 
    //获得消息摘要的字节数组 
    byte[] digest = md.digest(); 
    //因为要在口令的字节数组中存放盐,所以加上盐的字节长度 
    pwd = new byte[digest.length + salt_length]; 
    //将盐的字节拷贝到生成的加密口令字节数组的前12个字节,以便在验证口令时取出盐 
    system.arraycopy(salt, 0, pwd, 0, salt_length); 
    //将消息摘要拷贝到加密口令字节数组从第13个字节开始的字节 
    system.arraycopy(digest, 0, pwd, salt_length, digest.length); 
    //将字节数组格式加密后的口令转化为16进制字符串格式的口令 
    return bytetohexstring(pwd); 
  } 
} 

测试类——client,代码如下:

package com.zyg.security.md5; 
import java.io.unsupportedencodingexception; 
import java.security.nosuchalgorithmexception; 
import java.util.hashmap; 
import java.util.map; 
public class client { 
  private static map users = new hashmap(); 
  public static void main(string[] args){ 
    string username = "zyg"; 
    string password = "123"; 
    registeruser(username,password); 
    username = "changong"; 
    password = "456"; 
    registeruser(username,password); 
    string loginuserid = "zyg"; 
    string pwd = "1232"; 
    try { 
      if(loginvalid(loginuserid,pwd)){ 
        system.out.println("欢迎登陆!!!"); 
      }else{ 
        system.out.println("口令错误,请重新输入!!!"); 
      } 
    } catch (nosuchalgorithmexception e) { 
      // todo auto-generated catch block 
      e.printstacktrace(); 
    } catch (unsupportedencodingexception e) { 
      // todo auto-generated catch block 
      e.printstacktrace(); 
    }  
  } 
  /** 
   * 注册用户 
   * 
   * @param username 
   * @param password 
   */ 
  public static void registeruser(string username,string password){ 
    string encryptedpwd = null; 
    try { 
      encryptedpwd = mymd5util.getencryptedpwd(password); 
      users.put(username, encryptedpwd); 
    } catch (nosuchalgorithmexception e) { 
      // todo auto-generated catch block 
      e.printstacktrace(); 
    } catch (unsupportedencodingexception e) { 
      // todo auto-generated catch block 
      e.printstacktrace(); 
    } 
  } 
  /** 
   * 验证登陆 
   * 
   * @param username 
   * @param password 
   * @return 
   * @throws unsupportedencodingexception 
   * @throws nosuchalgorithmexception 
   */ 
  public static boolean loginvalid(string username,string password)  
        throws nosuchalgorithmexception, unsupportedencodingexception{ 
    string pwdindb = (string)users.get(username); 
    if(null!=pwdindb){ // 该用户存在 
        return mymd5util.validpassword(password, pwdindb); 
    }else{ 
      system.out.println("不存在该用户!!!"); 
      return false; 
    } 
  } 
} 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网