DES加密

package com.wen;

import java.security.*;
import javax.crypto.*;

/**
 * <p>Title: </p>
 * <p>Description:DES加密 </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class WriteOffDES {
   private String Algorithm = "DES";
   public WriteOffDES() {
      init();
   }
   public void init() {
      Security.addProvider(new com.sun.crypto.provider.SunJCE());
      try {
           keygen = KeyGenerator.getInstance(Algorithm);
           deskey = keygen.generateKey();
           c = Cipher.getInstance(Algorithm);
      }
      catch(NoSuchAlgorithmException ex) {ex.printStackTrace();}
      catch(NoSuchPaddingException ex) {ex.printStackTrace();}
   }

   public byte[] encrypt(String e) {
      try {
           c.init(Cipher.ENCRYPT_MODE, deskey);
           cipherByte = c.doFinal(e.getBytes());
      }
      catch(java.security.InvalidKeyException ex){ex.printStackTrace();}
      catch(javax.crypto.BadPaddingException ex){ex.printStackTrace();}
      catch(javax.crypto.IllegalBlockSizeException ex){ex.printStackTrace();}

      return cipherByte;
   }

   public String decrypt(byte[] d) {
      try {
           c.init(Cipher.DECRYPT_MODE, deskey);
           cipherByte = c.doFinal(d);
      }
      catch(java.security.InvalidKeyException ex){ex.printStackTrace();}
      catch(javax.crypto.BadPaddingException ex){ex.printStackTrace();}
      catch(javax.crypto.IllegalBlockSizeException ex){ex.printStackTrace();}

      return (new String(cipherByte));
   }

   public String byteTohex(byte[] b) {
      String str = "";
      String stmp = "";
      for(int n=0;n<b.length;n++) {
        stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
        if(stmp.length()==1) str = str + "0" + stmp;
        else str = str + stmp;
        if(n<b.length-1) str = str + ":";
      }
      return str.toUpperCase();
    }

    private KeyGenerator keygen;
    private SecretKey deskey;
    private Cipher c;
    private byte[] cipherByte;
}

發佈了41 篇原創文章 · 獲贊 0 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章