Java 文件加密

来源:互联网 发布:淘宝c店铺评分低怎么办 编辑:程序博客网 时间:2024/05/04 21:36


好记忆不如烂笔头 ,有些东西,可能简单,但是用到的时候却不一定能立马想起来,所以即便是再简单的知识,写出来,记忆一下还是很好的!


文件加密,可以很好的来判断两个文件是否相等。


废话不说了,直接上代码来看吧,详细的描述都在文件中描述了!



import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.security.MessageDigest;


/**

 * 文件加密

 */

public class EncryptFile {

    

    public static void main(String[] args) {

        File file1 =new File("2.jar");

        String aString = EncryptFile.getMD5(file1);

        System.out.println(aString);

        File file2 =new File("1.jar");

        String bString = EncryptFile.getMD5(file2);

        System.out.println(bString);

    }

    staticcharhexdigits[] = {'0','1', '2','3','4', '5','6','7', '8','9','a', 'b','c','d', 'e','f' };

    public static String getMD5(Filefile) {

        FileInputStream fis = null;

        try {

            MessageDigest md = MessageDigest.getInstance("MD5");

            fis = new FileInputStream(file);

            byte[] buffer =newbyte[2048];

            int length = -1;

            long s = System.currentTimeMillis();

            while ((length =fis.read(buffer)) != -1) {

                md.update(buffer, 0,length);

            }

            byte[] b =md.digest();

            return byteToHexString(b);

        }

        catch (Exception ex) {

            ex.printStackTrace();

            return null;

        }

        finally {

            try {

                fis.close();

            }

            catch (IOException ex) {

                ex.printStackTrace();

            }

        }

    }

    

    private static String byteToHexString(byte[]tmp) {

        String s;

        // 用字节表示就是 16 个字节

        charstr[] =newchar[16 * 2];// 每个字节用 16 进制表示的话,使用两个字符,

        // 所以表示成 16 进制需要 32 个字符

        intk = 0;// 表示转换结果中对应的字符位置

        for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节

            // 转换成 16 进制字符的转换

            byte byte0 =tmp[i];// 取第 i 个字节

            str[k++] =hexdigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换,

            // >>> 为逻辑右移,将符号位一起右移

            str[k++] =hexdigits[byte0 & 0xf];// 取字节中低 4 位的数字转换

        }

        s = new String(str);// 换后的结果转换为字符串

        return s;

    }

  

}



在上来一个用jdk自带的加密方式实现 :

spring 加载实现.

public class DecryptPropertyPlaceholderConfigurerextends PropertyPlaceholderConfigurer {


private String keyPath;


private String[]encryptPropNames;


    @Override

    protected void processProperties(ConfigurableListableBeanFactorybeanFactoryToProcess, Properties props)throws BeansException {

        if (encryptPropNames !=null && encryptPropNames.length > 0 &&props.size() > 0) {

            for (String propName :encryptPropNames) {

                String value = props.getProperty(propName);

                System.out.println( DESEncryptUtil.doEncrypt(value,keyPath));

                props.setProperty(propName, DESEncryptUtil.doEncrypt(value,keyPath));

            }

        }

        super.processProperties(beanFactoryToProcess,props);

    }


   

public void setEncryptPropNames(String[]encryptPropNames) {

        this.encryptPropNames =encryptPropNames;

    }

   

    public void setKeyPath(StringkeyPath) {

        this.keyPath =keyPath;

    }

}


加密工具

@SuppressWarnings("restriction")

public class DESEncryptUtil {



    /**

     * 数据解密

     *

     * @param data

     * @return

     */

    static String doEncrypt(String data,String keyPath) {


        String decryptedData = null;

        try {

            // DES算法要求有一个可信任的随机数源

            SecureRandom sr = new SecureRandom();

            DESKeySpec deskey = new DESKeySpec(ReadFileHandle.readFileByChars(keyPath).getBytes());

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

            SecretKey key = keyFactory.generateSecret(deskey);

            // 解密对象

            Cipher cipher = Cipher.getInstance("DES");

            cipher.init(Cipher.DECRYPT_MODE,key, sr);

            // 把字符串解码为字节数组,并解密

            decryptedData = new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(data)));

        } catch (Exception e) {

            throw new RuntimeException("解密错误,错误信息:",e);

        }

        returndecryptedData;


    }


    /**

     * 数据加密

     * @param data

     * @return

     */

    public static String doDecrypt(Stringdata,String keyPath) {

        String encryptedData = null;

        try {

            // DES算法要求有一个可信任的随机数源

            SecureRandom sr = new SecureRandom();

            DESKeySpec deskey = new DESKeySpec(ReadFileHandle.readFileByChars(keyPath).getBytes());

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

            SecretKey key = keyFactory.generateSecret(deskey);

            // 加密对象

            Cipher cipher = Cipher.getInstance("DES");

            cipher.init(Cipher.ENCRYPT_MODE,key, sr);

            encryptedData = new BASE64Encoder().encode(cipher.doFinal(data.getBytes()));

        } catch (Exception e) {

            throw new RuntimeException("加密错误,错误信息:",e);

        }

        returnencryptedData;

    }


读取 key  信息

public class ReadFileHandle {


    protected staticfinal Log logger = LogFactory.getLog(ReadFileHandle.class);


    /**

     * 读取文本

     *

     * @param fileName

     */

    public static String readFileByChars(StringfileName) {

        File file = new File(fileName);

        InputStreamReader inputReader = null;

        BufferedReader bufferReader = null;

        OutputStream outputStream = null;

        try {

            InputStream inputStream = new FileInputStream(file);

            inputReader = new InputStreamReader(inputStream);

            bufferReader = new BufferedReader(inputReader);


            String line = bufferReader.readLine();

            return line;


        } catch (IOException e) {

            logger.error("文件读取异常!===========================");

            e.printStackTrace();

        } finally {

            if (outputStream !=null) {

                try {

                    outputStream.flush();

                    outputStream.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }


            if (inputReader !=null) {

                try {

                    inputReader.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }


            if (bufferReader !=null) {

                try {

                    bufferReader.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return null;

    }


}





其他用到的地方,后期会进一步补充。。。



0 0
原创粉丝点击