EncryptUtil

/**
 *   @(#) EncryptUtil.java
 */
package edu.hust.util.security;

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

/**
 *  HexStringUtil is a util tool for manipulating conversion between hex and string
 */
class HexStringUtil {
     /**
      * hex digits
      */
     private static final String[] hexDigits = {
         "0", "1", "2", "3", "4", "5", "6", "7",
         "8", "9", "a", "b", "c", "d", "e", "f"
     };

     /**
      *   Convert byte array to hex string
      *   @param b byte array
      *   @return hex string
      */
     public static String byteArrayToHexString( byte[] b ) {
          StringBuffer buf = new StringBuffer();
          for( int i = 0; i < b.length; i++) {
               buf.append( byteToHexString( b[i]));
          }
               return buf.toString();
     }
        
    /**
     *    Convert byte to hex String
     *    @param b byte
     *    @return hex String
     */
     private static String byteToHexString( byte b ) {
          int n = b;
          // n < 0 then make n positive
          if( n < 0 )  {
                 n += 256;
          }
          int d1 = n >> 4; // upper bit
          int d2 = n % 16; // lower bit
            
          return hexDigits[d1] + hexDigits[d2];
     }
}

/**
 *    EncryptException is an exception class from exception, handles any exceptions that
 *    may happen in the encryption/descryption.
 */
class EncryptException extends Exception {
   /**
    *  Construct a new EncryptException
    */
    public EncryptException() {
         super();
      }
    
      /**
       *  Construct a new EncryptException
       *  @param msg exception message
       */
      public EncryptException( String msg ) {
       super( msg );
      }
     
      /**
       *  Construct a new EncryptException
       *  @ex exception
       */
      public EncryptException( Throwable ex ) {
       super( ex );
      }
 }

/**
 *  EncryptUtil is a util tool for implementing private key encrypt/decrypt algorithm,
 *  which can handle encrypt and decrypt cases.
 *  @author quickpoint 
 *  @version 1.0 06/22/2005
 */
public class EncryptUtil {
 /**
  * DES algorithm
  */
 public static final String DES = "DES";
 /**
  * DESede algorithm
  */
 public static final String DESede = "DESede";
 /**
  * BlowFish algorithm
  */
 public static final String BLOWFISH = "BlowFish";
    /**
     * SecretKey
     */
    private static SecretKey key = null;
   
    ///
    //                        Encrypt
    ///
    /**
     *  Encrypt with algorithm
     *  @param origin plain text
     *  @algorithm algorithm used in encrypt
     *  @return cipher text( in byte )
     *  @exception EncryptException throws when any exception happed in encryption
     */    
 public static byte[] encrypt( String origin, String algorithm )
        throws  EncryptException
 {
     try {
        // add new secruity algorithm 
     Security.addProvider( new com.sun.crypto.provider.SunJCE());
     KeyGenerator keygen = KeyGenerator.getInstance( algorithm );
        // generate key
        key = keygen.generateKey();
        // doing encryption
        Cipher cipher = Cipher.getInstance( algorithm );
        cipher.init(Cipher.ENCRYPT_MODE, key );
        byte[]  cipherByte = cipher.doFinal( origin.getBytes());
        return cipherByte;
     } catch ( Exception ex ) {
      throw new EncryptException( ex );
     }
 } 
 
 /**
  *  Encrypt with DES
  *  @param origin plain text
  *  @return cipher text( in byte )
  *  @exception EncryptException throws when any exception happed in encryption
  */
 public static byte[] encryptWithDES( String origin)
         throws EncryptException
 {
        return encrypt( origin, EncryptUtil.DES);
 }       
 
 /**
  *  Encrypt with DESede
  *  @param origin plain text
  *  @return cipher text( in byte )
  *  @exception EncryptException throws when any exception happed in encryption
  */
 public static byte[] encryptWithDESede( String origin )
         throws EncryptException
 {
     return encrypt( origin, EncryptUtil.DESede);
 }       
 
 /**
  *  Encrypt with BlowFish
  *  @param origin plain text
  *  @return cipher text( in byte )
  *  @exception EncryptException throws when any exception happed in encryption
  */
 public static byte[] encryptWithBlowFish( String origin )
         throws EncryptException
 {
         return encrypt( origin, EncryptUtil.BLOWFISH);
 }
 
 /**
  *  Encrypt with algorithm and convert to string form
  *  @param origin plain text
  *  @param algorithm algorithm used in encryption
  *  @return cipher text( in hex string ) or null
  */
 public static String encryptToString( String origin, String algorithm ) {
  try {
   byte[] cipherByte = encrypt( origin, algorithm);
      return HexStringUtil.byteArrayToHexString( cipherByte);
  } catch ( EncryptException ex) {
   return null;
  }
 }
 
 /**
  *  Encrypt with DES and convert to string form
  *  @param origin plain text
  *  @return cipher text( in hex string ) or null
  */
 public static String encryptToStringWithDES( String origin ) {
  return encryptToString( origin, EncryptUtil.DES);
 }      
 
 /**
  *  Encrypt with DESede and convert to string form
  *  @param origin plain text
  *  @return cipher text( in hex string ) or null
  */
 public static String encryptToStringWithDESede( String origin ) {
  return encryptToString( origin, EncryptUtil.DESede);
 }
 
 /**
  *  Encrypt with BlowFish and convert to string form
  *  @param origin plain text
  *  @return cipher text( in hex string ) or null
  */
 public static String encryptToStringWithBlowFish( String origin ) {
  return encryptToString( origin, EncryptUtil.BLOWFISH);
 }
 
 /
 //                      Descrypt
 /
 
 /**
  *    Descrypt with algorithm
  *    @param cipherByte cipher byte
  *    @param encryptKey encrypt key
  *    @param algorithm  algorithm used in descryption
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static byte[] descrypt( byte[] cipherByte, SecretKey encryptKey, String algorithm )
        throws EncryptException
 {
       try {
   Security.addProvider( new com.sun.crypto.provider.SunJCE());
   Cipher cipher = Cipher.getInstance( algorithm );
   cipher.init( Cipher.DECRYPT_MODE, encryptKey );
   byte[] plainByte = cipher.doFinal( cipherByte );
   return plainByte;
  } catch ( Exception ex ) {
   throw new EncryptException( ex );
  }
 }     
 
 /**
  *    Descrypt with algorithm
  *    @param cipherByte cipher byte
  *    @param algorithm  algorithm used in descryption
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */      
 public static byte[] descrypt( byte[] cipherByte,  String algorithm )
        throws EncryptException
 {
        return descrypt( cipherByte, key, algorithm );
 }
 
 /**
  *    Descrypt with DES
  *    @param cipherByte cipher byte
  *    @param encryptKey encrypt key
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static byte[] descryptWithDES( byte[] cipherByte, SecretKey encryptKey )
        throws EncryptException
 {
  return descrypt( cipherByte, encryptKey, EncryptUtil.DES );
 }
 
 /**
  *    Descrypt with MD5
  *    @param cipherByte cipher byte
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static byte[] descryptWithDES( byte[] cipherByte )
        throws EncryptException
 {
  return descrypt( cipherByte, EncryptUtil.DES);
 }
 
 /**
  *    Descrypt with DESede
  *    @param cipherByte cipher byte
  *    @param encryptKey encrypt key
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static byte[] descryptWithDESede( byte[] cipherByte, SecretKey encryptKey )
        throws EncryptException
 {
     return descrypt( cipherByte, encryptKey, EncryptUtil.DESede);        
 }
 
 /**
  *    Descrypt with DESede
  *    @param cipherByte cipher byte
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static byte[] descryptWithDESede( byte[] cipherByte )
        throws EncryptException
 {
     return descrypt( cipherByte, EncryptUtil.DESede); 
 }  
 
 /**
  *    Descrypt with BlowFish
  *    @param cipherByte cipher byte
  *    @param encryptKey encrypt key
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static byte[] descryptWithBlowFish( byte[] cipherByte, SecretKey encryptKey )
        throws EncryptException
    {
     return descrypt( cipherByte, encryptKey, EncryptUtil.BLOWFISH);        
    }
 
 /**
  *    Descrypt with BlowFish
  *    @param cipherByte cipher byte
  *    @return plain text( in byte )
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static byte[] descryptWithBlowFish( byte[] cipherByte)
        throws EncryptException
 {
     return descrypt( cipherByte, EncryptUtil.BLOWFISH);  
 }         
 
 /**
  *    Descrypt with algorithm and convert to string form
  *    @param cipherByte cipher byte
  *    @param encryptKey encrypt key
  *    @param algorithm  algorithm used in descryption
  *    @return plain text( in string ) or null
  *    @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToString( byte[] cipherByte, SecretKey secretKey, String algorithm ) {
  try {
   byte[] plainByte = descrypt( cipherByte, secretKey, algorithm );
      return HexStringUtil.byteArrayToHexString( plainByte ); 
  } catch ( EncryptException ex ) {
   return null;
  }
 }
 
 /**
  *     Descrypt with algorithm and convert to string form
  *     @param cipherByte cipher byte
  *     @param algorithm algorithm used in descryption
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToString( byte[] cipherByte, String algorithm ) {
     return descryptToString( cipherByte, key, algorithm );
 }
 
 /**
  *     Descrypt with algorithm and convert to string form
  *     @param cipherStr cipher string
  *     @param algorithm algorithm used in descryption
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToString( String cipherStr, String algorithm ) {
     return descryptToString( cipherStr.getBytes(), algorithm ); 
 }
 
 /**
  *     Descrypt with DES and convert to string form
  *     @param cipherByte cipher byte
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToStringWithDES( byte[] cipherByte ) {
  return descryptToString( cipherByte, EncryptUtil.DES);
 }
   
 /**
  *     Descrypt with DES and convert to string form
  *     @param cipherStr cipher string
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
    public static String descryptToStringWithDES( String cipherStr ) {
     return descryptToStringWithDES( cipherStr.getBytes());
    } 
   
 /**
  *     Descrypt with DESede and convert to string form
  *     @param cipherByte cipher byte
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToStringWithDESede( byte[] cipherByte ) {
  return descryptToString( cipherByte, EncryptUtil.DESede);
 }
 
 /**
  *     Descrypt with DESede and convert to string form
  *     @param cipherStr cipher string
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToStringWithDESede( String cipherStr ) {
  return descryptToStringWithDESede( cipherStr.getBytes());
 }
 
 /**
  *     Descrypt with BlowFish and convert to string form
  *     @param cipherByte cipher byte
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToStringWithBlowFish( byte[] cipherByte ) {
  return descryptToString( cipherByte, EncryptUtil.BLOWFISH);
 }
 
 /**
  *     Descrypt with BlowFish and convert to string form
  *     @param cipherStr cipher string
  *     @return plain text( in string ) or null
  *     @exception EncryptException throws when any exception happened in descryption
  */
 public static String descryptToStringWithBlowFish( String cipherStr ) {
  return descryptToStringWithBlowFish( cipherStr.getBytes());
 }
 
 //
 //             SecretKey handler
 //
 /**
  *    Store secret key to file
  *    @param fileName name of file
  */
 public static void storeKeyToFile( String fileName ) {
  try {
   ObjectOutputStream out = new ObjectOutputStream(
                                 new FileOutputStream( fileName ));
   out.writeObject( key );
   out.close();                       
  } catch ( IOException ex ) {
   ex.printStackTrace();
  }
 }
 
 /**
  *    Store secret key to file
  *    @param fileName name of file
  *    @param secretKey secret key to be stored
  */
 public static void storeKeyToFile( String fileName, SecretKey secretKey ) {
  key = secretKey;
  storeKeyToFile( fileName );
 }
 
 /**
  *    Restore secret key from file and assgign to variable key
  *    @param fileName name of file
  *    @return true if success ,or else return false
  */
 public static boolean restoreKeyFromFile( String fileName ) {
  key = attainKeyFromFile( fileName );
  return ( null != key );
 }
 
 /**
  *    Attain secret key from file
  *    @param fileName name of file
  *    @return secret key or null   
  */
 private static SecretKey attainKeyFromFile( String fileName ) {
  SecretKey secretKey = null;
  try {
   ObjectInputStream in = new ObjectInputStream(
                                 new FileInputStream( fileName));
   secretKey = (SecretKey)in.readObject();                             
      in.close();
  } catch (IOException ioex ) {
   ioex.printStackTrace();
  } catch ( ClassNotFoundException classNotFoundEx ) {
   classNotFoundEx.printStackTrace();
  }
      return secretKey;
 }
 
 // main , just for test
 public static void main( String[] args ) {
            try {
             String cipherText = "quickpoint";
             String fileName = "key.txt";
             byte[] cipherByte = encryptWithDES( cipherText);
             storeKeyToFile( fileName );
             
                boolean success = restoreKeyFromFile( fileName );
                if( success ) {
                byte[] plainByte = descryptWithDES( cipherByte );
                System.out.println( new String( plainByte ) );
                }
            } catch (EncryptException ex  ) {
             ex.printStackTrace();
            }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值