Java DES、AES、RSA、DM5读取文件加密解密

来源:互联网 发布:linux shell脚本教程 编辑:程序博客网 时间:2024/05/16 08:36

//下面代码是直接读取文件来进行加密解密,算法文件

package Test;
import javax.crypto.KeyGenerator;
import javax.crypto.CipherInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.Key;
import java.io.*;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class jmjm
{ //获取数据
 private  String keyFile = (new StringBuilder()).append("D:\\zy301a_nad_018374_868119_20150501102333_01_sec_0001_1505049414.tar").toString(); 
 public String getFile()
 {return this.keyFile;} 
 public void setFile(String keyFile)
 {
  this.keyFile=keyFile;
 }
//////////////////DES加密解密////////////////
 Key DESkey;
   public jmjm(String str)
   {
     getKey(str);//生成密匙
   }
   /**
    * 根据参数生成KEY
    */
 private void getKey(String strKey)
 {  
  try
  {
         KeyGenerator _generator = KeyGenerator.getInstance("DES");
         _generator.init(new SecureRandom(strKey.getBytes()));
         this.DESkey = _generator.generateKey();
         _generator = null;
     }
  catch (Exception e)
  {
         throw new RuntimeException("Error initializing SqlMap class. Cause: " + e);
     }
 }
 /**
   * 文件file进行加密并保存目标文件destFile中
   * @param file   要加密的文件 
   * @param destFile 加密后存放的文件名
   */
 public void encrypt(String file, String destFile) throws Exception
 {
     Cipher cipher = Cipher.getInstance("DES");
     cipher.init(Cipher.ENCRYPT_MODE, this.DESkey);
     InputStream is = new FileInputStream(file);
     OutputStream out = new FileOutputStream(destFile);
     CipherInputStream cis = new CipherInputStream(is, cipher);
     byte[] buffer = new byte[2048];
     int r;
     while ((r = cis.read(buffer)) > 0)
     {
         out.write(buffer, 0, r);
     }
     cis.close();
     is.close();
     out.close();
   }
 /**
   * 文件采用DES算法解密文件
   * @param file 已加密的文件
   * @param dest解密后存放的文件名
   */
   public void decrypt(String file, String dest) throws Exception
   {
     Cipher cipher = Cipher.getInstance("DES");
     cipher.init(Cipher.DECRYPT_MODE, this.DESkey);
     InputStream is = new FileInputStream(file);
     OutputStream out = new FileOutputStream(dest);
     CipherOutputStream cos = new CipherOutputStream(out, cipher);
     byte[] buffer = new byte[1024];
     int r;
     while ((r = is.read(buffer)) >= 0)
     {
         cos.write(buffer, 0, r);
     }
     cos.close();
     out.close();
     is.close();
   }
   /////////////////////////AES加密解密//////////////////
    private static KeyGenerator kgen;
  private static SecureRandom secureRandom;
  private static SecretKeySpec key;
  private static Cipher cipher;
  /**
   * AES加密算法
   */
  private static void init(String keyWord)
  {
   try
   {
    kgen = KeyGenerator.getInstance("AES");
    secureRandom = SecureRandom.getInstance("SHA1PRNG" ); 
    secureRandom.setSeed(keyWord.getBytes()); 
    kgen.init(128,secureRandom); 
    SecretKey secretKey = kgen.generateKey(); 
    byte[] enCodeFormat = secretKey.getEncoded(); 
    key = new SecretKeySpec(enCodeFormat, "AES"); 
    cipher = Cipher.getInstance("AES");// 创建密码器 
   }
   catch (NoSuchAlgorithmException e)
   {
    e.printStackTrace();
   }
   catch (NoSuchPaddingException e)
   {
    e.printStackTrace();
   }
  }
  
  /********************************对文件进行加密解密*********************************************************/
  /**
   * @param fileName  加密的文件路径
   * @param fileNameEncrypt 加密后的文件路径 当fileNameEncrypt为null时加密文件代替原文件
   * @param keyWord 加密密钥
   */
  public static void encryptFile(String fileName,String fileNameEncrypt, String keyWord)
  { 
   try
   {
    boolean replace = false;
    if(fileNameEncrypt==null || fileNameEncrypt.equals(""))
    {
     fileNameEncrypt = fileName+".tem";
     replace = true;
    }
    init(keyWord);
    cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 
       File file = new File(fileNameEncrypt);
    if (!file.exists())
    file.createNewFile();
    FileInputStream fileinputstream=new FileInputStream(fileName);
    FileOutputStream out = new FileOutputStream(file);
    byte bytes[] = new byte[131072]; //因在断点下载时用到,不能修改 除非 断点下载处修改
    byte enbytes[] = null;
    int line = 0;
    while ((line = fileinputstream.read(bytes)) != -1)
    {
     enbytes = cipher.doFinal(Arrays.copyOfRange(bytes, 0, line));
     out.write(enbytes, 0, enbytes.length);
    }
    out.close();
    fileinputstream.close();   
    if(replace)
    {
     File oldFile  = new File(fileName);
     oldFile.delete();
     File newFile = new File(fileNameEncrypt);
     newFile.renameTo(oldFile);
    }    
   }
   catch (InvalidKeyException e)
   { 
    e.printStackTrace(); 
   }
   catch (UnsupportedEncodingException e)
   { 
       e.printStackTrace(); 
      }
   catch (IllegalBlockSizeException e)
   { 
       e.printStackTrace(); 
   }
   catch (BadPaddingException e)
   { 
       e.printStackTrace(); 
   }
   catch (IOException e)
   {
    e.printStackTrace();
   }
  }  
    /**解密
     * @param content  待解密内容
     * @param keyWord 解密密钥
     * @return  byte[]
     */ 
  public static void decryptFile(String encryptFileName,String decryptFileName, String keyWord)
  {
   try
   { 
    boolean replace = false;
    if(decryptFileName==null || decryptFileName.equals(""))
    {
     decryptFileName = encryptFileName+".tem";
     replace = true;
    }
    init(keyWord);
    cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 
    File file = new File(decryptFileName); //解密后的文件
    if (!file.exists())
    file.createNewFile();
    FileInputStream fileinputstream=new FileInputStream(encryptFileName); //要解密的文件
    FileOutputStream out = new FileOutputStream(file);
    byte bytes[] = new byte[131088]; //因在断点下载时用到,不能修改 除非 断点下载处修改
    byte enbytes[] = null;
    int line = 0;
    while ((line = fileinputstream.read(bytes)) != -1)
    {
     enbytes = cipher.doFinal(Arrays.copyOfRange(bytes, 0, line));
        out.write(enbytes, 0, enbytes.length);
    }
    out.close();
    fileinputstream.close();
    if(replace)
    {
     File oldFile  = new File(encryptFileName);
     oldFile.delete();
     File newFile = new File(decryptFileName);
     newFile.renameTo(oldFile);
    }
   }
   catch (InvalidKeyException e)
   { 
         e.printStackTrace(); 
   }
   catch (IllegalBlockSizeException e)
   { 
        e.printStackTrace(); 
   }
   catch (BadPaddingException e)
   { 
        e.printStackTrace(); 
   }
   catch (IOException e)
   {
    e.printStackTrace();
   }
  }
  /********************************对文件进行加密解密结束*****************************************************/ 
  /**将二进制转换成16进制
   * @param buf
   * @return  String
    */ 
  public static String parseByte2HexStr(byte buf[])
  { 
   StringBuffer sb = new StringBuffer(); 
          for (int i = 0; i < buf.length; i++)
          { 
            String hex = Integer.toHexString(buf[i] & 0xFF); 
            if (hex.length() == 1)
            { 
             hex = '0' + hex; 
            } 
            sb.append(hex.toUpperCase()); 
          } 
          return sb.toString(); 
  }
  /**将16进制转换为二进制
   * @param hexStr
   * @return  byte[]
   */ 
  public static byte[] parseHexStr2Byte(String hexStr)
  { 
   if (hexStr.length() < 1) 
   return null; 
   byte[] result = new byte[hexStr.length()/2]; 
   for (int i = 0;i< hexStr.length()/2; i++)
   { 
    int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);          
    int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); 
    result[i] = (byte) (high * 16 + low); 
   } 
   return result; 
  }   
///////////RSA加密解密///////////////////
  static KeyPairGenerator keyPairGen;
  static KeyPair keyPair;
  static RSAPrivateKey privateKey;
  static RSAPublicKey publicKey;
  static
  {
   try
   { keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(512);
    keyPair = keyPairGen.generateKeyPair();
    // Generate keys
    privateKey = (RSAPrivateKey) keyPair.getPrivate();
    publicKey = (RSAPublicKey) keyPair.getPublic();
   }
   catch (NoSuchAlgorithmException e)
   {
    e.printStackTrace();
   }
  } 
  public void encryptFileRSA(jmjm encrypt, String inputFile, String newFile)
  {
   try
   {InputStream is = new FileInputStream(inputFile);
   OutputStream os= new FileOutputStream(newFile);
   byte[] bytes = new byte[53];
   while (is.read(bytes) > 0)
   { byte[] e = encrypt.encryptRSA(jmjm.publicKey, bytes);
    bytes = new byte[53];
    os.write(e, 0, e.length);
   }
   os.close();
   is.close();
//   System.out.println("write success");
   }
   catch (Exception e)
   {e.printStackTrace();}
  }
  public void decryptFileRSA(jmjm encrypt, String newFile2, File newFile)
  { try
   { InputStream is = new FileInputStream(newFile2);
     OutputStream os = new FileOutputStream(newFile);
     byte[] bytes1 = new byte[64];
     while (is.read(bytes1) > 0)
     { byte[] de = encrypt.decryptRSA(jmjm.privateKey, bytes1);
       bytes1 = new byte[64];
     os.write(de, 0, de.length);
     }
    os.close();
    is.close();
//    System.out.println("write success");
   }
   catch (Exception e)
   {e.printStackTrace();
   }
  }
 /** *//*** * Encrypt String. ** * @return byte[]*/
  protected byte[] encryptRSA(RSAPublicKey publicKey, byte[] obj)
  {  if (publicKey != null)
     {
   try
   {Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.ENCRYPT_MODE, publicKey);
   return cipher.doFinal(obj);
   }
   catch (Exception e)
   {e.printStackTrace();}
   }return null;
  }
 /** *//*** * Basic decrypt method ** * @return byte[]*/
  protected byte[] decryptRSA(RSAPrivateKey privateKey, byte[] obj)
  { if (privateKey != null)
   {
    try
    { Cipher cipher = Cipher.getInstance("RSA");
      cipher.init(Cipher.DECRYPT_MODE, privateKey);
      return cipher.doFinal(obj);
    }
    catch (Exception e)
    {e.printStackTrace();}
   }
    return null;
  } 
 //////////////////////////MD5加密解密/////////////////////////////
     static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  
    public static String getMD5(String file,String destFile)
    {
        FileInputStream fis = null;
        OutputStream out=null;
        try
        {
            MessageDigest md = MessageDigest.getInstance("MD5");      
            fis = new FileInputStream(file);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[2048];
            int length = -1;
           // long s = System.currentTimeMillis();          
        // int r;
            while ((length = fis.read(buffer)) != -1)
            {
                md.update(buffer, 0, length);
                out.write(buffer, 0, buffer.length);
            }
            byte[] b = md.digest();
            return byteToHexString(b);          
        }
        catch (Exception ex)
        {      
            ex.printStackTrace();
            return null;
        }
        finally
        {
            try
            {
                fis.close();
                out.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
       
    }
    private static String byteToHexString(byte[] tmp)
    {
        String s;
        char str[] = new char[16 * 2];
        int k = 0;
        for (int i = 0; i < 16; i++)
        {        
            byte byte0 = tmp[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        s = new String(str);
        return s;
    }
    /////////////////////////SHA加密解密//////////////////////////
 public static String getSHA1(File file,File destFile)
 { FileInputStream in = null;
  OutputStream out=null;
  if(!file.isFile())
  {return null;}
  MessageDigest digest=null;
  byte buffer[]=new byte[8192];
  int len;
  try
  { digest=MessageDigest.getInstance("SHA-1");
   in=new FileInputStream(file);
   out=new FileOutputStream(destFile);
    while ((len = in.read(buffer)) != -1)
          {
      digest.update(buffer, 0, len);
              out.write(buffer, 0, buffer.length);
          }
    BigInteger bigInt=new BigInteger(1,digest.digest());
    return bigInt.toString(16);
  }
  catch (Exception e)
  {
   e.printStackTrace();
   return null;
  }
  finally
  {
   try
   {
   in.close();
   out.close();
   }
   catch(Exception e)
   {
    e.printStackTrace();
   }
  }   
 }

}
////测试文件

package Test;

import java.io.File;

public class Testjmjm
{
 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception
 {   //DES加密解密   
  // TODO Auto-generated method stub
  long lStart1 = System.currentTimeMillis();  
     jmjm td = new jmjm("aaa");
     String inputFile=td.getFile();  
     //td.getFile();
     td.encrypt(inputFile, "D:/加密后文件2.doc"); //加密
     long lUseTime1 = System.currentTimeMillis() - lStart1;
     System.out.println("DES加密耗时3:" + lUseTime1/1000.00 + "秒");   
     long lStart2 = System.currentTimeMillis();
     td.decrypt("D:/加密后文件2.doc", "D:/解密后文件2.tar"); //解密
     long lUseTime2 = System.currentTimeMillis() - lStart2;
  System.out.println("DES解密耗时:" + lUseTime2/1000.00 + "秒");
  //AES加密解密
  long lStart3 = System.currentTimeMillis();
  String fileNameEncrypt="D:\\22.txt";
  jmjm.encryptFile(inputFile, fileNameEncrypt, "ABCDEFGHABCDEFGH");
  long lUseTime3 = System.currentTimeMillis() - lStart3;
  System.out.println("AES加密耗时:" + lUseTime3/1000.00 + "秒");
  long lStart4 = System.currentTimeMillis();
  String decryptedFile="D:\\31.tar";
  jmjm.decryptFile(fileNameEncrypt, decryptedFile, "ABCDEFGHABCDEFGH");
  long lUseTime4 = System.currentTimeMillis() - lStart4;
  System.out.println("AES解密耗时:" + lUseTime4/1000.00 + "秒");
  //RSA加密解密
  long lStart5 = System.currentTimeMillis();   
  String newFile = "D:\\222.txt"; 
  td.encryptFileRSA(td, inputFile, newFile);
  long lUseTime5 = System.currentTimeMillis() - lStart5;
  System.out.println("RSA加密耗时:" + lUseTime5/1000.00 + "秒");
  long lStart6 = System.currentTimeMillis();
  File newFile1 = new File("D:\\32.tar");
  td.decryptFileRSA(td, newFile, newFile1);   
  long lUseTime6 = System.currentTimeMillis() - lStart6;
  System.out.println("RSA解密耗时:" + lUseTime6/1000.00 + "秒");   
    //MD5加密
  long lStart7 = System.currentTimeMillis();
     String file1="D:\\22.tar";
     jmjm.getMD5(inputFile,file1);
     long lUseTime7 = System.currentTimeMillis() - lStart7;
     System.out.println("MD5加密耗时:" + lUseTime7/1000.00 + "秒"); 
     //SHA1加密
  long lStart8 = System.currentTimeMillis();
  File file=new File("D:\\zy301a_nad_018374_868119_20150501102333_01_sec_0001_1505049414.tar");   
  File destFile=new File("D:\\2222.txt");   
  jmjm.getSHA1(file, destFile);
  long lUseTime8 = System.currentTimeMillis() - lStart8;
  System.out.println("SHA1加密耗时:" + lUseTime8/1000.00 + "秒");
 }

}

 

1 0
原创粉丝点击