WEB开发网
开发学院软件开发Java DES加密、解密例子 阅读

DES加密、解密例子

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示:关于DES加密、解密之类在JE中也有挺多的例子,也不确定这算不算原创,DES加密、解密例子,欢迎学习、感谢拍砖指导! Java代码/***CreatedbyIntelliJIDEA.*User:liangj*/publicclassDesKeyManager{publicfinalstaticStringDEFAULT

关于DES加密、解密之类在JE中也有挺多的例子,也不确定这算不算原创。欢迎学习、感谢拍砖指导!

Java代码  

/** 
 * Created by IntelliJ IDEA. 
 * User: liangj 
 */ 
public class DesKeyManager { 
  public final static String DEFAULT_KEY = "PKCS5Padding"; 
  protected final static String DES = "DES"; 
  protected static String key; 
 
  protected String getKey() { 
    return key; 
  } 
 
  public static void setKey(String key) { 
    DesKeyManager.key = key; 
  } 
} 

Java代码   

import javax.crypto.spec.DESKeySpec; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.SecretKey; 
import javax.crypto.Cipher; 
import java.security.SecureRandom; 
 
/** 
 * Created by IntelliJ IDEA. 
 * User: liangj 
 */ 
public class DesEncrypt extends DesKeyManager { 
  private static DesEncrypt _instance = null; 
 
  private DesEncrypt() { 
 
  } 
 
  public static DesEncrypt getInstance() { 
    if (_instance == null) { 
      _instance = new DesEncrypt(); 
    } 
    return _instance; 
  } 
 
  /** 
   * 加密 
   * @param key 密匙,其长度必须是8的倍数 
   * @param src 数据源 
   * @return 返回加密后的数据 
   * @throws Exception 
   */ 
  private byte[] encrypt(byte[] key, byte[] src) throws Exception { 
    //DES算法需要有一个可信任的随机数源 
    SecureRandom sr = new SecureRandom(); 
    //从原始密匙数据(key)创建DESKeySpec对象 
    DESKeySpec dks = new DESKeySpec(key); 
    //创建一个密匙工厂 
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); 
    //使用密匙工厂把DESKeySpec转换成一个SecretKey对象 
    SecretKey sk = keyFactory.generateSecret(dks); 
    //Cipher对象实际完成加密操作 
    Cipher cipher = Cipher.getInstance(DES); 
    //用密匙初始化Cipher对象 
    cipher.init(Cipher.ENCRYPT_MODE, sk, sr); 
 
    //现在开始对数据源src进行加密 
    return cipher.doFinal(src); 
  } 
 
  /** 
   * 二进制转换成十六进制 
   * @param b 
   * @return 
   */ 
  public String byte2hex(byte[] b) { 
    String hs = ""; 
    String stmp; 
 
    for (byte aB : b) { 
      stmp = (Integer.toHexString(aB & 0XFF)); 
      if (stmp.length() == 1) { 
        hs = hs + "0" + stmp; 
      } else { 
        hs = hs + stmp; 
      } 
    } 
 
    return hs.toLowerCase(); 
  } 
 
  /** 
   * 加密方法 
   * @param src 数据源 
   * @return 
   */ 
  public String encrypt(String src) { 
    try { 
      return byte2hex(encrypt(getKey().getBytes(), src.getBytes())); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
    return null; 
  } 
 
  public String encrypt(byte[] src) { 
    try { 
      return byte2hex(encrypt(getKey().getBytes(), src)); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
    return null; 
  } 
} 

1 2  下一页

Tags:DES 加密 解密

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接