admin管理员组

文章数量:1633030

一、基础知识

1.异或加密解密方式(推荐)

package com.test;

import java.io.*;

public class test1 {
    private static final int numOfEncAndDec = 0x255;//定义密钥
    private static int dataOfFile = 0;

    /**
     * 加密文件
     * @param srcFile
     * @param encFile
     * @throws Exception
     */
    private static void EncFile(File srcFile, File encFile) throws Exception {
        if(!srcFile.exists()){
            System.out.println("source file not exixt");
            return;
        }

        if(!encFile.exists()){
            System.out.println("encrypt file created");
            encFile.createNewFile();
        }
        InputStream fis  = new FileInputStream(srcFile);
        OutputStream fos = new FileOutputStream(encFile);

        while ((dataOfFile = fis.read()) > -1) {
            fos.write(dataOfFile^numOfEncAndDec);
        }

        fis.close();
        fos.flush();
        fos.close();
    }

    /**
     * 解密文件
     * @param encFile
     * @param decFile
     * @throws Exception
     */
    private static void DecFile(File encFile, File decFile) throws Exception{
        if(!encFile.exists()){
            //加密文件不存在
            return;
        }
        if(!decFile.exists()){
            //创建解密文件
            decFile.createNewFile();
        }

        InputStream fis = new FileInputStream(encFile);
        OutputStream fos = new FileOutputStream(decFile);

        while((dataOfFile = fis.read()) > -1){
            fos.write(dataOfFile^numOfEncAndDec);
        }

        fis.close();
        fos.flush();
        fos.close();
    }

    /**
     * 测试
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        File inputFile = new File("E:\\weaver\\1.txt");
        File outputFile = new File("E:\\weaver\\test\\1.txt");
//        DecFile(outputFile,inputFile);
        EncFile(inputFile,outputFile);
    }
}

2.加密解密PDF文件

仅能用于pdf文件

首先在官网拿到 Spire.PDF for Java jar包

https://www.e-iceblue/Downloads/Spire-PDF-JAVA.html

package com.test;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;
import java.util.EnumSet;
public class test3 {
    public static void main(String[] args) {
//创建PdfDocument实例
        PdfDocument doc = new PdfDocument();
//加载PDF文件
        doc.loadFromFile("E:\\weaver\\1.pdf");
//对文件进行加密
        PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;//设置KeySiz
        String openPassword = "myppt123";//设置文档打开密码
        String permissionPassword = "edit";
        EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
        doc.getSecurity().encrypt(openPassword,permissionPassword,flags, keySize);
//保存文件
        System.out.println(doc.toString());
        doc.saveToFile("E:\\weaver\\test\\tets.pdf");
        doc.close();
    }
}

效果:

3.AESCoder加密解密文件

package weaver.file;

import com.api.doc.util.DocEncryptUtil;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.sm.SM4Utils;

public class AESCoder
{
  private static final String KEY_ALGORITHM = "AES";
  private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

  public static byte[] initSecretKey(String paramString)
  {
    KeyGenerator localKeyGenerator = null;
    try {
      localKeyGenerator = KeyGenerator.getInstance("AES");

      SecureRandom localSecureRandom = SecureRandom.getInstance("SHA1PRNG");
      localSecureRandom.setSeed(paramString.getBytes());
      localKeyGenerator.init(128, localSecureRandom);
    } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
      localNoSuchAlgorithmException.printStackTrace();
      return new byte[0];
    }

    SecretKey localSecretKey = localKeyGenerator.generateKey();
    return localSecretKey.getEncoded();
  }

  private static Key toKey(byte[] paramArrayOfByte)
  {
    return new SecretKeySpec(paramArrayOfByte, "AES");
  }
 /**
  *加密文件
  **/
  public static InputStream encrypt(InputStream paramInputStream, String paramString)
    throws Exception
  {
    if ((paramString.startsWith("sm4start")) && (paramString.endsWith("sm4end"))) {
      localObject = new SM4Utils();
      paramInputStream = ((SM4Utils)localObject).encrypt(paramInputStream, paramString);
      return paramInputStream;
    }
    Object localObject = initSecretKey(paramString);

    Key localKey = toKey(localObject);

    Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    localCipher.init(1, localKey);

    CipherInputStream localCipherInputStream = new CipherInputStream(paramInputStream, localCipher);
    return ((InputStream)localCipherInputStream);
  }
  /**
  *解密文件
  **/
  public static OutputStream encrypt(OutputStream paramOutputStream, String paramString)
    throws Exception
  {
    if ((paramString.startsWith("sm4start")) && (paramString.endsWith("sm4end"))) {
      return paramOutputStream;
    }
    byte[] arrayOfByte = initSecretKey(paramString);

    Key localKey = toKey(arrayOfByte);

    Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    localCipher.init(1, localKey);

    CipherOutputStream localCipherOutputStream = new CipherOutputStream(paramOutputStream, localCipher);

    return localCipherOutputStream;
  }

  public static InputStream decrypt(InputStream paramInputStream, String paramString)
    throws Exception
  {
    if ((paramString.startsWith("sm4start")) && (paramString.endsWith("sm4end"))) {
      localObject1 = new RecordSet();
      ((RecordSet)localObject1).executeSql("select filesize  from imagefile where aescode='" + paramString + "'");
      if (((RecordSet)localObject1).next()) {
        localObject2 = new SM4Utils();
        paramInputStream = ((SM4Utils)localObject2).decrypt(paramInputStream, paramString, Util.getIntValue(((RecordSet)localObject1).getString("filesize")), "SM4");
        return paramInputStream;
      }
      return null;
    }

    Object localObject1 = initSecretKey(paramString);

    Object localObject2 = toKey(localObject1);

    Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    localCipher.init(2, (Key)localObject2);

    CipherInputStream localCipherInputStream = new CipherInputStream(paramInputStream, localCipher);

    return ((InputStream)(InputStream)localCipherInputStream);
  }



  public static OutputStream decrypt(OutputStream paramOutputStream, String paramString)
    throws Exception
  {
    if ((paramString.startsWith("sm4start")) && (paramString.endsWith("sm4end"))) {
      return paramOutputStream;
    }
    byte[] arrayOfByte = initSecretKey(paramString);

    Key localKey = toKey(arrayOfByte);

    Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    localCipher.init(2, localKey);

    CipherOutputStream localCipherOutputStream = new CipherOutputStream(paramOutputStream, localCipher);

    return localCipherOutputStream;
  }

  public static byte[] getSMCode(String paramString)
  {
    byte[] arrayOfByte1 = new byte[16];
    try
    {
      while (paramString.length() < 16)
      {
        paramString = paramString + paramString;
      }
      byte[] arrayOfByte2 = paramString.getBytes();
      System.arraycopy(arrayOfByte2, 0, arrayOfByte1, 0, 16);
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
    return arrayOfByte1;
  }

  public static String decrypt(String paramString1, String paramString2) throws Exception {
    try {
      if (paramString2 == null)
      {
        return null;
      }
      byte[] arrayOfByte1 = initSecretKey(paramString2);
      SecretKeySpec localSecretKeySpec = new SecretKeySpec(arrayOfByte1, "AES");
      Cipher localCipher = Cipher.getInstance("AES");
      localCipher.init(2, localSecretKeySpec);
      byte[] arrayOfByte2 = hex2byte(paramString1);
      try {
        byte[] arrayOfByte3 = localCipher.doFinal(arrayOfByte2);
        String str = new String(arrayOfByte3);
        return str;
      } catch (Exception localException2) {
        localException2.printStackTrace();
        return null;
      }
    } catch (Exception localException1) {
      localException1.printStackTrace(); }
    return null;
  }

  public static String encrypt(String paramString1, String paramString2)
    throws Exception
  {
    if (paramString2 == null)
    {
      return null;
    }
    byte[] arrayOfByte1 = initSecretKey(paramString2);
    SecretKeySpec localSecretKeySpec = new SecretKeySpec(arrayOfByte1, "AES");
    Cipher localCipher = Cipher.getInstance("AES");
    localCipher.init(1, localSecretKeySpec);
    byte[] arrayOfByte2 = localCipher.doFinal(paramString1.getBytes());
    return byte2hex(arrayOfByte2).toLowerCase();
  }

  public static byte[] hex2byte(String paramString) {
    if (paramString == null) {
      return null;
    }
    int i = paramString.length();
    if (i % 2 == 1) {
      return null;
    }
    byte[] arrayOfByte = new byte[i / 2];
    for (int j = 0; j != i / 2; ++j) {
      arrayOfByte[j] = (byte)Integer.parseInt(paramString.substring(j * 2, j * 2 + 2), 16);
    }
    return arrayOfByte;
  }

  public static String byte2hex(byte[] paramArrayOfByte) {
    String str1 = "";
    String str2 = "";
    for (int i = 0; i < paramArrayOfByte.length; ++i) {
      str2 = Integer.toHexString(paramArrayOfByte[i] & 0xFF);
      if (str2.length() == 1)
        str1 = str1 + "0" + str2;
      else {
        str1 = str1 + str2;
      }
    }
    return str1.toUpperCase();
  }

  public static String randomKey()
  {
    String str1 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int i = (int)(Math.random() * 16.0D + 16.0D);
    int j = 0;
    String str2 = "";
    while (j < i) {
      int k = (int)(Math.random() * 61.0D);
      if (k <= 61) {
        str2 = str2 + str1.substring(k, k + 1);
        ++j;
      }
    }
    return str2;
  }
}

4.Base64

base64不算加密,当需要加密有图片的文件时并且客户没啥具体需求的情况下可采取此种编码形式。

首先引入hutool工具包

整体代码:

public static void main(String[]args){
    //读文件字节数组
    byte[] bytes=FileUtil.readBytes(filePath:"D:\\Administrator.pdf"):
    String encode=Base64.encode(new File(pathname:"D:\\Administrator.pdf"));

    //写base64编码到temp,pdf
    String tempFilePath "D:\\Administrator\\Desktop\\temp.pdf";
    Fileutil.writeBytes(encode.getBytes(StandardCharsets.UTF_8),tempFilePath);
    
    //读temp.pdf
    byte[]tempBytes Fileutil.readBytes(tempFilePath);
    byte[]decode Base64.decode(tempBytes);
    String resultPath "D:\\Administrator\\Desktop\\result.pdf";
    FileUtil.writeBytes(decode,resultPath);
}

编码:

package com.test;

import cn.hutool.core.io.FileUtil;
import java.io.File;
import java.nio.charset.StandardCharsets;

public class test12 {
    public static void main(String[] args) {
        File thefile = new File("E:\\weaver\\1.pdf");
        //获得文件编码
        String encode = cn.hutool.core.codec.Base64.encode(thefile);
        byte[] bys= encode.getBytes(StandardCharsets.UTF_8);
        //写入文件
        FileUtil.writeBytes(encode.getBytes(StandardCharsets.UTF_8), thefile);
    }
}

解码:

package com.test;

import java.io.*;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
public class test11 {
    public static void main(String[] args) throws IOException {
        //编码前文件
        File thefile = new File("E:\\weaver\\1.pdf");
        //编码后文件
        File newFile = new File("E:\\weaver\\3.pdf");
        //解码
        byte[] tempBytes = FileUtil.readBytes(thefile);
        byte[] decode = Base64.decode(tempBytes);
        //创建编码后文件
        if (!newFile.exists()){
            newFile.createNewFile();
        }
        FileUtil.writeBytes(decode,"E:\\weaver\\3.pdf");
    }
}

二、需求

需求是修改源码,使文件ftp上传之后是加密文件

关键部分源码


  File thefile = new File(filerealpath);
   if (iszip.equals("1")) {
      zin = new ZipInputStream(new FileInputStream(thefile));
      if (zin.getNextEntry() != null) imagefile = new BufferedInputStream(zin);
       } else {
          imagefile = new BufferedInputStream(new FileInputStream(thefile));
       }

     try {
      filepath = fileurl+"/"+rs.getString("imagefileid")+getExe(rs.getString("imagefileid"),rs.getString("imagefilename"));
       succ = ftpClient.uploadFile(imagefile, new File(filepath).getName(), "/" + fileurl);

先是修改成异或加密

imagefile = new BufferedInputStream(new FileInputStream(thefile));
                        byte[] temp = new byte[1024];
                        int len;
                        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                        newlog.info("test5");
                        int dataOfFile = 0;
                        newlog.info("test1");
                        while ((dataOfFile = imagefile.read()) > -1) {
                            out.write(dataOfFile ^ numOfEncAndDec);
                        }
                        newlog.info("test2");
                        byte[] content = out.toByteArray();
                        newlog.info("test3");
                        byteInputStream = new ByteArrayInputStream(content);
                        filepath = fileurl+"/"+rs.getString("imagefileid")+getExe(rs.getString("imagefileid"),rs.getString("imagefilename"));
                    newlog.info("filepath:"+filepath);
                    log.info("test");
                    succ = ftpClient.uploadFile(byteInputStream, new File(filepath).getName(), "/" + fileurl);

然后发现上传pdf文件的时候直接异或会损坏,试图加判断,在上传pdf的时候使用pdf专属加密方式

if ("pdf".equals(fileName.substring(fileName.length() - 3))) {
                        //创建PdfDocument实例
                        PdfDocument doc = new PdfDocument();
//加载PDF文件
                        doc.loadFromFile(filerealpath);
//对文件进行加密
                        PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;//设置KeySize
                        String openPassword = "123";//设置文档打开密码
                        String permissionPassword = "edit";
                        EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
                        doc.getSecurity().encrypt(openPassword,permissionPassword,flags, keySize);
//保存文件
                        imagefile = new BufferedInputStream(new FileInputStream());
                        doc.saveToFile("E:\\weaver\\test\\tets.txt");
                        doc.close();
                    } 

然后发现上传的succ是传参需要文件流,但是此方法只能传PdfDocument实例。转而使用AESCoder加密方法

imagefile = new BufferedInputStream(new FileInputStream(thefile));
imagefile = AESCoder.encrypt(imagefile, "6XMJR9PFOP428");
 filepath = fileurl+"/"+rs.getString("imagefileid")+getExe(rs.getString("imagefileid"),rs.getString("imagefilename"));
succ = ftpClient.uploadFile(imagefile, new File(filepath).getName(), "/" + fileurl);

此种方式过于复杂,最后采取base64编码

//new imageFileManager得到文件
ImageFileManager imageFileManager = new ImageFileManager();
imageFileManager.resetParameter();
imageFileManager.getImageFileInfoById(Integer.parseInt(imagefileid));

//输入流编码
imagefile = ImageFileManager.getInputStreamById(Integer.parseInt(imagefileid));
byte[] bytes = IoUtil.readBytes(imagefile);
String encode = cn.hutool.core.codec.Base64.encode(bytes);
byte[] bys= encode.getBytes(StandardCharsets.UTF_8);
byteInputStream = new ByteArrayInputStream(bys);

//ftp上传
filepath = fileurl+"/"+rs.getString("imagefileid")+getExe(rs.getString("imagefileid"),rs.getString("imagefilename"));
succ = ftpClient.uploadFile(byteInputStream, new File(filepath).getName(), "/" + fileurl);

上传后采用上文提及的base64方法来解码

本文标签: 加密解密简单方式文件Java