Java-文件加密传输(摘要+签名)

摘要:
Java-文件加密传输文件加密传输其实就是将文件以二进制格式进行传输。其中加密文件主要由:源文件二进制文件、源文件数字摘要、数字签名、特征码等等组成。
Java-文件加密传输(摘要+签名)
文件加密传输其实就是将文件以二进制格式进行传输。
其中加密文件主要由:源文件二进制文件源文件数字摘要数字签名特征码等等组成
摘要可确认文件的唯一性,数字签名则是对摘要进行了加密。
本文主要记录使用RSA加密方式
其中生成RSA密钥主要介绍二种方式:
1、安装openssl情况下使用Linux命令生成
2、Java代码实现

一、公私钥生成

1、linux

1、查看openssl版本
openssl version -a
2、生成私钥
openssl genrsa -out rsa_private_key.pem 2048
会生成rsa_private_key.pem私钥文件,私钥文件不能使用
3、生成公钥
openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -puboutopenssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
私钥文件不能使用
4、私钥文件PKCS#8编码
openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem
此处生成的私钥文件方可用于Java

2、Java

importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.security.InvalidKeyException;
importjava.security.KeyFactory;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.NoSuchAlgorithmException;
importjava.security.SecureRandom;

importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.InvalidKeySpecException;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;

importjavax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjavax.crypto.NoSuchPaddingException;

importorg.apache.commons.codec.binary.Base64;

public classRSAEncrypt {
    /*** 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final String PRIVATE_BEGIN = "-----BEGIN PRIVATE KEY-----";
    private static final String PRIVATE_END = "-----END PRIVATE KEY-----";
    private static final String PUBLIC_BEGIN = "-----BEGIN PUBLIC KEY-----";
    private static final String PUBLIC_END = "-----END PUBLIC KEY-----";


    /*** 1、随机生成密钥对
     *
     * @paramfilePath 密钥存放目录
     */
    public voidgenKeyPair(String filePath) {
        //KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = null;
        try{
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch(NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024, newSecureRandom());
        //生成一个密钥对,保存在keyPair中
        KeyPair keyPair =keyPairGen.generateKeyPair();
        //得到私钥
        RSAPrivateKey privateKey =(RSAPrivateKey) keyPair.getPrivate();
        //得到公钥
        RSAPublicKey publicKey =(RSAPublicKey) keyPair.getPublic();
        try{
            //得到公钥字符串
            Base64 base64 = newBase64();
            String publicKeyString = newString(base64.encode(publicKey.getEncoded()));
            //得到私钥字符串
            String privateKeyString = newString(base64.encode(privateKey.getEncoded()));
            //将密钥对写入到文件
            FileWriter pubfw = new FileWriter(filePath + "\publicKey.pem");
            FileWriter prifw = new FileWriter(filePath + "\privateKey.pem");
            BufferedWriter pubbw = newBufferedWriter(pubfw);
            BufferedWriter pribw = newBufferedWriter(prifw);
            pubbw.write(publicKeyString);
            pribw.write(privateKeyString);
            pubbw.flush();
            pubbw.close();
            pubfw.close();
            pribw.flush();
            pribw.close();
            prifw.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /*** 2、从本地文件中读取公钥
     *
     * @parampath 公钥路径
     * @return公钥字符串
     * @throwsException 异常信息
     */
    public String loadPublicKeyByFile(String path) throwsException {
        try{
            BufferedReader br = new BufferedReader(newFileReader(path));
            String readLine = null;
            StringBuilder sb = newStringBuilder();
            while ((readLine = br.readLine()) != null) {
                //去除公钥头部底部
                if (!readLine.equals(PUBLIC_BEGIN) && !readLine.equals(PUBLIC_END)) {
                    sb.append(readLine);
                }
            }
            br.close();
            returnsb.toString();
        } catch(IOException e) {
            throw new Exception("公钥数据流读取错误");
        } catch(NullPointerException e) {
            throw new Exception("公钥输入流为空");
        }
    }

    /*** 3、字符串公钥转公钥对象
     *
     * @parampublicKeyStr 公钥字符串类型
     * @return公钥对象
     * @throwsException 异常信息
     */
    publicRSAPublicKey loadPublicKeyByStr(String publicKeyStr)
            throwsException {
        try{
            Base64 base64 = newBase64();
            byte[] buffer =base64.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = newX509EncodedKeySpec(buffer);
            return(RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch(NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch(InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch(NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /*** 4、从本地文件中读取私钥
     *
     * @parampath 私钥文件路径
     * @return私钥字符串
     * @throwsException 异常信息
     */
    public String loadPrivateKeyByFile(String path) throwsException {
        try{
            BufferedReader br = new BufferedReader(newFileReader(path));
            String readLine = null;
            StringBuilder sb = newStringBuilder();
            while ((readLine = br.readLine()) != null) {
                //去除私钥头部底部
                if (!readLine.equals(PRIVATE_BEGIN) && !readLine.equals(PRIVATE_END)) {
                    sb.append(readLine);
                } else{
                }
            }
            br.close();
            returnsb.toString();
        } catch(IOException e) {
            throw new Exception("私钥数据读取错误");
        } catch(NullPointerException e) {
            throw new Exception("私钥输入流为空");
        }
    }


    /*** 5、字符串公钥转公钥对象
     *
     * @paramprivateKeyStr 私钥字符串类型
     * @return私钥对象
     * @throwsException 异常信息
     */
    publicRSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
            throwsException {
        try{
            Base64 base64 = newBase64();
            byte[] buffer =base64.decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = newPKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return(RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch(NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch(InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch(NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    /*** 6、公钥加密过程
     *
     * @parampublicKey     公钥
     * @paramplainTextData 明文数据
     * @return* @throwsException 加密过程中的异常信息
     */
    public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
            throwsException {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try{
            //使用默认RSA
            cipher = Cipher.getInstance("RSA");
            //cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output =cipher.doFinal(plainTextData);
            returnoutput;
        } catch(NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch(NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch(InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch(IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch(BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /*** 7、私钥加密过程
     *
     * @paramprivateKey    私钥
     * @paramplainTextData 明文数据
     * @return* @throwsException 加密过程中的异常信息
     */
    public byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
            throwsException {
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try{
            //使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output =cipher.doFinal(plainTextData);
            returnoutput;
        } catch(NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch(NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch(InvalidKeyException e) {
            throw new Exception("加密私钥非法,请检查");
        } catch(IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch(BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /*** 8、私钥解密过程
     *
     * @paramprivateKey 私钥
     * @paramcipherData 密文数据
     * @return明文
     * @throwsException 解密过程中的异常信息
     */
    public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
            throwsException {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try{
            //使用默认RSA
            cipher = Cipher.getInstance("RSA");
            //cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output =cipher.doFinal(cipherData);
            returnoutput;
        } catch(NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch(NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch(InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch(IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch(BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }

    /*** 9、公钥解密过程
     *
     * @parampublicKey  公钥
     * @paramcipherData 密文数据
     * @return明文
     * @throwsException 解密过程中的异常信息
     */
    public byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
            throwsException {
        if (publicKey == null) {
            throw new Exception("解密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try{
            //使用默认RSA
            cipher = Cipher.getInstance("RSA");
            //cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output =cipher.doFinal(cipherData);
            returnoutput;
        } catch(NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch(NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch(InvalidKeyException e) {
            throw new Exception("解密公钥非法,请检查");
        } catch(IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch(BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }

    /*** 10、字节数据转十六进制字符串
     *
     * @paramdata 输入数据
     * @return十六进制内容
     */
    public String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = newStringBuilder();
        for (int i = 0; i < data.length; i++) {
            //取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            //取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        returnstringBuilder.toString();
    }
}

二、调用

/*** 生成加密后文件
     *
     * @paramoldFilePath 需要加密文件路径+名称
     * @paramnewFilePath 加密后文件路径+名称
     * @paramprivatePath 私钥文件路径+名称
     */
    public voidfileEncrypt(String oldFilePath, String newFilePath, String privatePath) {
        ByteUtil byteUtil = newByteUtil();

        //文件格式:特征码+原始升级包长度+数字签名长度+原始包内容+数字签名
        byte[] code = byteUtil.intToByteArray(0x9F2308DC);
        RSAEncrypt rsaEncrypt = newRSAEncrypt();
        try{
            //1、特征码写入
            OutputStream out = new FileOutputStream(newFile(newFilePath));
            out.write(code, 0, 4);

            //2、原始升级包长度写入
            byte[] fileByte =byteUtil.File2byte(oldFilePath);
            int L1 =fileByte.length;
            byte[] a =byteUtil.intToByteArray(L1);
            out.write(a, 0, 4);

            //文件摘要生成
            MsgDigestDemo msgDigestDemo = newMsgDigestDemo();
            MessageDigest md5Digest = MessageDigest.getInstance("MD5");
            md5Digest.update(msgDigestDemo.fileBytes(oldFilePath));
            byte[] md5Encoded =md5Digest.digest();
            log.info("==========MD5摘要:{}==========", Base64.encodeBase64URLSafeString(md5Encoded));

            String privateKey =rsaEncrypt.loadPrivateKeyByFile(privatePath);
            RSAPrivateKey privateKeyfile =rsaEncrypt.loadPrivateKeyByStr(privateKey);

            //生成签名(摘要加密过程)
            byte[] signature =rsaEncrypt.encrypt(privateKeyfile, md5Encoded);

            //3、签名长度
            int L2 =signature.length;
            byte[] c =byteUtil.intToByteArray(L2);
            out.write(c, 0, 4);

            //4、原始升级包内容写入
            out.write(fileByte, 0, L1);
            //5、数字签名写入
            out.write(signature, 0, L2);
            out.flush();
            out.close();
        } catch(IOException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

MD5摘要计算

public classMsgDigestDemo {
public byte[] fileBytes(String filePath) {
        try{
            File file = newFile(filePath);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            FileInputStream in = newFileInputStream(file);
            byte[] fileByte = new byte[1024];
            intn;
            while ((n = in.read(fileByte)) != -1) {
                out.write(fileByte, 0, n);
            }
            in.close();
            byte[] data =out.toByteArray();
            out.close();
            returndata;
        } catch(IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

参考:https://www.cnblogs.com/PollyLuo/p/9046610.html

免责声明:文章转载自《Java-文件加密传输(摘要+签名)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Java代码优化总结Office 2003轻松安装下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

java执行linux shell命令,并拿到返回值

1 packagecom.pasier.xxx.util; 2 3 importjava.io.IOException; 4 importjava.io.InputStream; 5 importjava.nio.charset.Charset; 6 7 importorg.slf4j.Logger; 8 importorg.slf4j.LoggerF...

Swift 内存管理详解

Swift内存管理: Swift 和 OC 用的都是ARC的内存管理机制,它们通过 ARC 可以很好的管理对象的回收,大部分的时候,程序猿无需关心 Swift 对象的回收。 注意: 只有引用类型变量所引用的对象才需要使用引用计数器进行管理,对于枚举、结构体等,他们都是值类型的。因此不需要使用引用计数进行管理。 一:理解ARC 1: ARC 自动统计改对象被...

StackExchange.Redis.DLL 操作redis加强版

直接引用StackExchange.Redis.dll这一个dll来操作redis App.config配置 <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime...

delphi 7 mdi子窗体。。。无法更改以命令对象为源的记录集对象的 ActiveConnection 属性。

问题是这样的 我做了一个小程序 把 adoconnection放到了主窗体  连接的是access数据库; 新建了一个子窗体继承自FBase  新建了一个pubulic方法 qrySearch 实现了打开表; formCreate调用了qrySearch方法 ; public procedure qrySearch(cLiuShui: stri...

[爬虫]采用Go语言爬取天猫商品页面

最近工作中有一个需求,需要爬取天猫商品的信息,整个需求的过程如下: 修改后端广告交易平台的代码,从阿里上传的素材中解析url,该url格式如下: https://handycam.alicdn.com/slideshow/26/7ef5aed1e3c39843e8feac816a436ecf.mp4?content=%7B%22items%22%3A%5B...

第三方授权认证(一)实现第三方授权登录、分享以及获取用户资料

转载请注明出处:http://blog.csdn.net/yangyu20121224/article/details/9057257             由于公司项目的需要,要实现在项目中使用第三方授权登录以及分享文字和图片等这样的效果,几经波折,查阅了一番资料,做了一个Demo。实现起来的效果还是不错的,不敢独享,决定写一个总结的教程,供大家互相交...