【數據加密】用DES加密字符串

  1. import java.io.*;
  2. import java.security.*;
  3. import javax.crypto.*;
  4. import sun.misc.BASE64Encoder;
  5. public class DES {
  6.  public static byte[] aa;
  7.  public static void main(String[] args) throws Exception {
  8.   if (args.length < 3) {
  9.    System.out.println("Usage: java PwdDES -e|-d passwd input");
  10.    return;
  11.   }
  12.   Key key;
  13.   KeyGenerator generator = KeyGenerator.getInstance("DES");
  14.   generator.init(new SecureRandom(args[1].getBytes()));
  15.   key = generator.generateKey();
  16.   Cipher cipher = Cipher.getInstance("DES");
  17.   if (args[0].indexOf("e") != -1)
  18.    cipher.init(Cipher.ENCRYPT_MODE, key);
  19.   else
  20.    cipher.init(Cipher.DECRYPT_MODE, key);
  21.   System.out.println(new String(args[2].getBytes()));
  22.   System.out.println(crypt(args[2].getBytes(),cipher));
  23.   
  24.   cipher.init(Cipher.DECRYPT_MODE, key);
  25.   System.out.println(crypt(aa,cipher));
  26.  }
  27.  private static String crypt(byte[] bt,Cipher cipher)throws IOException,GeneralSecurityException{
  28.   BASE64Encoder be = new BASE64Encoder();
  29.         byte[] outBytes = new byte[1024];
  30.         int inLength = 0;
  31.         inLength = bt.length;
  32.         if(inLength > 0)
  33.    outBytes = cipher.doFinal(bt,0,inLength);
  34.         else
  35.             outBytes = cipher.doFinal();
  36.         aa = outBytes;
  37.   return new String(outBytes);
  38.     }
  39. }
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章