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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
pto.BadPaddingException;
pto.Cipher;
pto.IllegalBlockSizeException;
pto.NoSuchPaddingException;
import dec.binary.Base64;
public class RSAEncrypt {
/
**
* 字节数据转字符串专⽤集合
*/
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、随机⽣成密钥对
*
* @param filePath 密钥存放⽬录
*/
public void genKeyPair(String filePath) {
// KeyPairGenerator类⽤于⽣成公钥和私钥对,基于RSA算法⽣成对象
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = Instance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
/
/ 初始化密钥对⽣成器,密钥⼤⼩为96-1024位
keyPairGen.initialize(1024, new SecureRandom());
// ⽣成⼀个密钥对,保存在keyPair中
KeyPair keyPair = ateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) Private();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) Public();
try {
// 得到公钥字符串
Base64 base64 = new Base64();
String publicKeyString = new Encoded()));
// 得到私钥字符串
String privateKeyString = new Encoded()));
// 将密钥对写⼊到⽂件
FileWriter pubfw = new FileWriter(filePath + "\\publicKey.pem");
FileWriter prifw = new FileWriter(filePath + "\\privateKey.pem");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(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、从本地⽂件中读取公钥
*
* @param path 公钥路径
* @return公钥字符串
* @throws Exception 异常信息
*/
public String loadPublicKeyByFile(String path) throws Exception {
java源代码加密
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
/
/ 去除公钥头部底部
if (!readLine.equals(PUBLIC_BEGIN) && !readLine.equals(PUBLIC_END)) {                    sb.append(readLine);
}
}
br.close();
String();
} catch (IOException e) {
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥输⼊流为空");
}
}
/**
* 3、字符串公钥转公钥对象
*
* @param publicKeyStr 公钥字符串类型
* @return公钥对象
* @throws Exception 异常信息
*/
public RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
throws Exception {
try {
Base64 base64 = new Base64();
byte[] buffer = base64.decode(publicKeyStr);
KeyFactory keyFactory = Instance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) atePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("⽆此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥⾮法");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 4、从本地⽂件中读取私钥
*
* @param path 私钥⽂件路径
* @return私钥字符串
* @throws Exception 异常信息
*/
public String loadPrivateKeyByFile(String path) throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
//去除私钥头部底部
if (!readLine.equals(PRIVATE_BEGIN) && !readLine.equals(PRIVATE_END)) {                    sb.append(readLine);
} else {
}
}
br.close();
String();
} catch (IOException e) {
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e) {
throw new Exception("私钥输⼊流为空");
}
}
/**
* 5、字符串公钥转公钥对象
*
* @param privateKeyStr 私钥字符串类型
* @return私钥对象
* @throws Exception 异常信息
*/
public RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
throws Exception {
try {
Base64 base64 = new Base64();
byte[] buffer = base64.decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = Instance("RSA");
return (RSAPrivateKey) atePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("⽆此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥⾮法");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
}
}
/**
* 6、公钥加密过程
*
* @param publicKey    公钥
* @param plainTextData 明⽂数据
* @return
* @throws Exception 加密过程中的异常信息
*/
public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
throws Exception {
if (publicKey == null) {
throw new Exception("加密公钥为空, 请设置");
}
Cipher cipher = null;
try {
/
/ 使⽤默认RSA
cipher = Instance("RSA");
// cipher= Instance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
return output;
} 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、私钥加密过程
*
* @param privateKey    私钥
* @param plainTextData 明⽂数据
* @return
* @throws Exception 加密过程中的异常信息
*/
public byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
if (privateKey == null) {
throw new Exception("加密私钥为空, 请设置");
}
Cipher cipher = null;
try {
/
/ 使⽤默认RSA
cipher = Instance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(plainTextData);
return output;
} 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、私钥解密过程
*
* @param privateKey 私钥
* @param cipherData 密⽂数据
* @return明⽂
* @throws Exception 解密过程中的异常信息
*/
public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("解密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使⽤默认RSA
cipher = Instance("RSA");
// cipher= Instance("RSA", new BouncyCastleProvider());            cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
return output;
} 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、公钥解密过程
*
* @param publicKey  公钥
* @param cipherData 密⽂数据
* @return明⽂
* @throws Exception 解密过程中的异常信息
*/
public byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
throws Exception {
if (publicKey == null) {
throw new Exception("解密公钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使⽤默认RSA
cipher = Instance("RSA");
// cipher= Instance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(cipherData);
return output;
} 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、字节数据转⼗六进制字符串
*
* @param data 输⼊数据
* @return⼗六进制内容
*/
public String byteArrayToString(byte[] data) {
StringBuilder stringBuilder = new StringBuilder();
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(' ');
}
}
String();
}
}
⼆、调⽤
  /**
* ⽣成加密后⽂件
*
* @param oldFilePath 需要加密⽂件路径+名称
* @param newFilePath 加密后⽂件路径+名称
* @param privatePath 私钥⽂件路径+名称
*/
public void fileEncrypt(String oldFilePath, String newFilePath, String privatePath) {
ByteUtil byteUtil = new ByteUtil();
//⽂件格式:特征码+原始升级包长度+数字签名长度+原始包内容+数字签名
byte[] code = byteUtil.intToByteArray(0x9F2308DC);
RSAEncrypt rsaEncrypt = new RSAEncrypt();
try {
//1、特征码写⼊
OutputStream out = new FileOutputStream(new File(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 = new MsgDigestDemo();
MessageDigest md5Digest = Instance("MD5");
md5Digest.update(msgDigestDemo.fileBytes(oldFilePath));
byte[] md5Encoded = md5Digest.digest();
log.info("==========MD5摘要:{}==========", deBase64URLSafeString(md5Encode
d));            String privateKey = rsaEncrypt.loadPrivateKeyByFile(privatePath);
RSAPrivateKey privateKeyfile = rsaEncrypt.loadPrivateKeyByStr(privateKey);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。