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

DES加密、解密例子

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示: Java代码importjavax.crypto.spec.DESKeySpec;importjavax.crypto.SecretKeyFactory;importjavax.crypto.SecretKey;importjavax.crypto.Cipher;importjava.secur

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 DesDecrypt extends DesKeyManager { 
  private static DesDecrypt _instance = null; 
 
  private DesDecrypt() { 
 
  } 
 
  public static DesDecrypt getInstance() { 
    if (_instance == null) { 
      _instance = new DesDecrypt(); 
    } 
    return _instance; 
  } 
 
  /** 
   * 解密 
   * @param key 密匙,其长度必须是8的倍数 
   * @param src 经过DES加密的数据源 
   * @return 返回解密后的数据 
   * @throws Exception 
   */ 
  private byte[] decrypt(byte[] key, byte[] src) throws Exception { 
    //需要创建一个可信任的随机数源对象 
    SecureRandom sr = new SecureRandom(); 
    //从原始密匙数据(src)创建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.DECRYPT_MODE, sk, sr); 
 
    //现在开始对数据源src进行解密 
    return cipher.doFinal(src); 
  } 
 
  /** 
   * 十六进制转换成二进制 
   * @param b 
   * @return 
   */ 
  public byte[] hex2byte(byte[] b) { 
    if ((b.length % 2) != 0) { 
      throw new IllegalArgumentException("长度不是偶数"); 
    } 
    byte[] b2 = new byte[b.length / 2]; 
    for (int n = 0; n < b.length; n += 2) { 
      String item = new String(b, n, 2); 
      b2[n / 2] = (byte) Integer.parseInt(item, 16); 
    } 
    return b2; 
  } 
 
  /** 
   * 解密方法 
   * @param src 数据源 
   * @return 
   */ 
  public byte[] decrypt(String src) { 
    try { 
      return decrypt(getKey().getBytes(), hex2byte(src.getBytes())); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
    return null; 
  } 
 
  public byte[] decrypt(byte[] src) { 
    try { 
      return decrypt(getKey().getBytes(), hex2byte(src)); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
    return null; 
  }   
}

上一页  1 2 

Tags:DES 加密 解密

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