java对文件的加密和解密(txt操作)

一,加密部分

 public static void encrypt(String fileUrl, String key) throws Exception {  
        File file = new File(fileUrl);  
        String path = file.getPath();  
        if(!file.exists()){  
            return;  
        }  
        int index = path.lastIndexOf("\\");  
        String destFile = path.substring(0, index)+"\\"+"abc";  
        File dest = new File(destFile);  
        InputStream in = new FileInputStream(fileUrl);  
        OutputStream out = new FileOutputStream(destFile);  
        byte[] buffer = new byte[1024];  
        int r;  
        byte[] buffer2=new byte[1024];  
        while (( r= in.read(buffer)) > 0) {  
            for(int i=0;i<r;i++)  
            {  
                byte b=buffer[i];  
                buffer2[i]=b==255?0:++b;  
            }  
            out.write(buffer2, 0, r);  
            out.flush();  
        }  
        in.close();  
        out.close();  
        file.delete();  
        dest.renameTo(new File(fileUrl));  
        appendMethodA(fileUrl, key);  
        System.out.println("加密成功");  
    }  

二,解密部分

/** 
     * 解密 
     * @param fileUrl 源文件 
     * @param tempUrl 临时文件 
     * @param ketLength 密码长度 
     * @return 
     * @throws Exception 
     */ 
    public static String decrypt(String fileUrl, String tempUrl, int keyLength) throws Exception{  
        File file = new File(fileUrl);  
        if (!file.exists()) {  
            return null;  
        }  
        File dest = new File(tempUrl);  
        if (!dest.getParentFile().exists()) {  
            dest.getParentFile().mkdirs();  
        }  
   
        InputStream is = new FileInputStream(fileUrl);  
        OutputStream out = new FileOutputStream(tempUrl);  
   
        byte[] buffer = new byte[1024];  
        byte[] buffer2=new byte[1024];  
        byte bMax=(byte)255;  
        long size = file.length() - keyLength;  
        int mod = (int) (size%1024);  
        int div = (int) (size>>10);  
        int count = mod==0?div:(div+1);  
        int k = 1, r;  
        while ((k <= count && ( r = is.read(buffer)) > 0)) {  
            if(mod != 0 && k==count) {  
                r =  mod;  
            }  
   
            for(int i = 0;i < r;i++)  
            {  
                byte b=buffer[i];  
                buffer2[i]=b==0?bMax:--b;  
            }  
            out.write(buffer2, 0, r);  
            k++;  
        }  
        out.close();  
        is.close();  
        return tempUrl;  
    }  

四,密钥

 /** 
     *  
     * @param fileName 
     * @param content 密钥 
     */ 
    public static void appendMethodA(String fileName, String content) {  
        try {  
            // 打开一个随机访问文件流,按读写方式  
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");  
            // 文件长度,字节数  
            long fileLength = randomFile.length();  
            //将写文件指针移到文件尾。  
            randomFile.seek(fileLength);  
            randomFile.writeBytes(content);  
            randomFile.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

五,判断是否加密

 public static String readFileLastByte(String fileName, int keyLength) {  
        File file = new File(fileName);  
        if(!file.exists())return null;  
        StringBuffer str = new StringBuffer();  
        try {  
            // 打开一个随机访问文件流,按读写方式  
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "r");  
            // 文件长度,字节数  
            long fileLength = randomFile.length();  
            //将写文件指针移到文件尾。  
            for(int i = keyLength ; i>=1 ; i--){  
                randomFile.seek(fileLength-i);  
                str.append((char)randomFile.read());  
            }  
            randomFile.close();  
            return str.toString();  
        } catch (IOException e) {  
            e.printStackTrace();    
        }    
        return null;  
    }  

六,测试

 public static void main(String[] args) throws Exception {  
        String path = "E:/4evercai/1.txt";    
        encrypt(path,"4evercai");  //加密    
        decrypt(path,"E:/4evercai/2.txt","4evercai".length());//解密  
    }  

 

  • 5
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中对文本文件进行加密解密操作可以使用加密算法和解密算法来实现。常用的加密算法有DES、AES、RSA等,解密算法则是对应的解密算法。下面是一个简单的示例,使用DES算法对文本文件进行加密解密加密操作: ```java import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.SecureRandom; public class FileEncryptor { public static void encrypt(String key, File inputFile, File outputFile) throws Exception { FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; SecureRandom secureRandom = new SecureRandom(key.getBytes()); DESKeySpec desKeySpec = new DESKeySpec(key.getBytes()); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom); int length; while ((length = inputStream.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, length); if (output != null) { outputStream.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { outputStream.write(output); } inputStream.close(); outputStream.flush(); outputStream.close(); } } ``` 解密操作: ```java import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.SecureRandom; public class FileDecryptor { public static void decrypt(String key, File inputFile, File outputFile) throws Exception { FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; SecureRandom secureRandom = new SecureRandom(key.getBytes()); DESKeySpec desKeySpec = new DESKeySpec(key.getBytes()); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey, secureRandom); int length; while ((length = inputStream.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, length); if (output != null) { outputStream.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { outputStream.write(output); } inputStream.close(); outputStream.flush(); outputStream.close(); } } ``` 示例中使用的是DES算法,可以根据需要替换为其他算法。对于密钥,建议使用安全的方式存储,例如通过密码学哈希函数对其进行散列,以保证安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值