一、概述
底層算法不做贅述,想要了解自行百度。
RSA屬于非對稱加密,非對稱加密有公鑰和私鑰兩個概念,私鑰自己擁有,不能給別人,公鑰公開。根據(jù)應用的不同,我們可以選擇使用不同的密鑰加密:
- 簽名:使用私鑰加密,公鑰解密。用于讓所有公鑰所有者驗證私鑰所有者的身份并且用來防止私鑰所有者發(fā)布的內(nèi)容被篡改,但是不用來保證內(nèi)容不被他人獲得。
- 加密:用公鑰加密,私鑰解密。用于向公鑰所有者發(fā)布信息,這個信息可能被他人篡改,但是無法被他人獲得。
二、詳細代碼
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class test1 {
/** RSA 算法 */
private static final String RSA = "RSA";
/** BC 提供 */
private static final String BC = "BC";
/** UTF-8 編碼 */
private static final String UTF8 = "UTF-8";
/** 公鑰默認讀取路徑 */
private static final String PUBLIC_KEY_FILE = "D:/RSA/" + "request.key";
/** 私鑰默認讀取路徑 */
private static final String PRIVATE_KEY_FILE = "D:/RSA/" + "response.key";
/** 私鑰 */
private static String prky;
/** 公鑰 */
private static String puky;
/** 讀取文件,以 1M 為單位 */
private static final Integer READER_1M = (2<<9) * 1;
// 加密等級制度
// - 等級越高,加密越嚴格(前提是保護要私鑰且不能丟失)
// - 個人電腦加密等級,不要超出 S3072
// - 加密等級越高,速度越慢。
// - 推薦使用 S1024(速度較快) 或 S2048(相比較而言更安全)
// - S3072(速度太慢),其余更高等級加密不推薦
private static Size S1024;
private static Size S2048;
private static Size S3072;
private static Size S7680;
private static Size S15360;
/** 當前加密等級 */
private static Size thisSize;
static {
// 初始化加密等級
S1024 = Size.create(2 * (2 << 8));
S2048 = Size.create(4 * (2 << 8));
S3072 = Size.create(6 * (2 << 8));
S7680 = Size.create(15 * (2 << 8));
S15360 = Size.create(30 * (2 << 8));
// 加密等級通過修改 thisSize 來指定
thisSize = S1024 ;
}
public static void main(String[] args) {
// 1、生成密鑰對文件,并保存;如果存在,則不生成
createKey();
// 2、加載密鑰
readKeyPair();
// 注:如果密鑰一直變,可以執(zhí)行一次,把密鑰拿出來直接放配置文件中,之后直接讀取使用就行,1 2 步就可以省了
// 3、加密操作
// 將 公鑰字符串 加載為 公鑰對象
RSAPublicKey rsaPublicKey = (RSAPublicKey) loadPublicKey(puky);
// 讀取文件轉(zhuǎn)byte數(shù)組, 如果文件是前端傳過來的,接收是用 MultipartFile 類型接收,轉(zhuǎn)byte數(shù)組之直接 multipartFile.getBytes()
File file1 = new File("D:\\RSA\\RSA測試專用.zip");
byte[] sourceData = handleReadData(file1);
// 使用公鑰進行加密數(shù)據(jù)
byte[] pukyData = encryptByPublicKey(sourceData, rsaPublicKey.getEncoded());
// 創(chuàng)建文件
File pukyfile = new File("D:\\RSA\\RSA測試專用加密.zip");
writeData(pukyfile, pukyData);
// 加密完成,你可以去嘗試找到文件打開試試,會顯示文件損壞的
// 4、解密操作
// 加載私鑰對象
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) loadPrivateKey(prky);
// 讀文件,拿到加密后的文件
File file2 = new File("D:\\RSA\\RSA測試專用加密.zip");
// 轉(zhuǎn)byte數(shù)組
byte[] temp = handleReadData(file2);
// 對加密后的數(shù)據(jù)進行解密
byte[] prkyData = decryptByPrivateKey(temp, rsaPrivateKey.getEncoded());
// 寫入到新文件
File file = new File("D:\\RSA\\RSA測試專用解密.zip");
writeData(file, prkyData);
// 解密完成
}
public static void createKey(){
KeyPair keyPair = generateKeyPair();
saveKeyPair(keyPair);
}
/**
* 生成密鑰對
* @return 密鑰對
*/
public static KeyPair generateKeyPair() {
try {
KeyPairGenerator kpg;
// 添加提供者 BC
// <!-- 加密工具 -->
// <dependency>
// <groupId>org.bouncycastle</groupId>
// <artifactId>bcprov-jdk15on</artifactId>
// <version>1.69</version>
// </dependency>
Security.addProvider(new BouncyCastleProvider());
// 密鑰對實例化,指定算法及提供者
kpg = KeyPairGenerator.getInstance(RSA, BC);
assert kpg!=null : "key generate error.";
// 密鑰對初始化,指定密鑰大小
kpg.initialize(thisSize.getKeySize());
// 獲取生成的密鑰對
return kpg.generateKeyPair();
} catch (Exception e) {
return null;
}
}
/**
* 保存密鑰對
* @param keyPair 密鑰對
*/
private static void saveKeyPair(KeyPair keyPair) {
// 如果密鑰對存在,則終止重寫
// - 如果使用其他密鑰對,導致密鑰不識別,需要更換正確的密鑰對或密鑰等級
// - 因此,建議使用固定等級的密鑰對
// - 即,只換密鑰對,不變等級
if(areKeysPresent()) return;
// 寫入密鑰對文件
writeDataBuffer(new File(PUBLIC_KEY_FILE), loadPublicKey(keyPair.getPublic()));
writeDataBuffer(new File(PRIVATE_KEY_FILE), loadPrivateKey(keyPair.getPrivate()));
}
/**
* 判定 密鑰文件 是否存在
* 暫定邏輯為,必須公鑰密鑰同時存在
* @return
*/
private static boolean areKeysPresent() {
File privateKey = new File(PRIVATE_KEY_FILE);
File publicKey = new File(PUBLIC_KEY_FILE);
return privateKey.exists() && publicKey.exists();
}
/**
* 給文件中寫入數(shù)據(jù)
* @param file 文件對象
* @param content 字符串對象
*/
private static void writeDataBuffer(
File file,
String content
) {
try {
if (file.getParentFile() != null) {
// 建立多級文件夾
file.getParentFile().mkdirs();
}
// 創(chuàng)建新的空文件
file.createNewFile();
FileOutputStream stream = new FileOutputStream(file);
// 以 UTF-8 編碼方式進行寫入
OutputStreamWriter outputStreamWriter =
new OutputStreamWriter(stream, UTF8);
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(content);
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 加載公鑰字符串
* @param publicKey 公鑰對象
* @return 公鑰字符串
*/
private static String loadPublicKey(PublicKey publicKey) {
return keyToString(publicKey);
}
/**
* 加載公鑰對象
* @param key 公鑰字符串
* @return 公鑰對象
*/
private static PublicKey loadPublicKey(String key) {
try {
// 如果讀取字符串為空,則直接拋出
if (key == null) {
throw new RuntimeException("public-key is null.");
}
// 通過 公鑰字節(jié)數(shù)組,指定 算法,再次生成 公鑰對象
// 公鑰 使用 X509EncodedKeySpec
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
java.util.Base64.getDecoder().decode((key.getBytes()))
);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 加載私鑰字符串
* @param privateKey 私鑰對象
* @return 私鑰字符串
*/
private static String loadPrivateKey(PrivateKey privateKey) {
return keyToString(privateKey);
}
/**
* 加載私鑰
* @param key 私鑰字符串
* @return 私鑰對象
*/
private static PrivateKey loadPrivateKey(String key) {
try {
// 如果讀取字符串為空,則直接拋出
assert key!=null : "private-key is null.";
// 通過 私鑰字節(jié)數(shù)組,指定 算法,再次生成 私鑰對象
// 私鑰 使用 PKCS8EncodedKeySpec
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
java.util.Base64.getDecoder().decode((key.getBytes()))
);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 將 Key 對象轉(zhuǎn)換成 字符串
* @param key Key
* @return 字符串
*/
private static String keyToString(Key key) {
try {
byte[] keyBytes = key.getEncoded();
return new String(java.util.Base64.getEncoder().encode(keyBytes), UTF8);
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 讀取密鑰對文件,并賦值給相關(guān)對象的屬性
*/
private static void readKeyPair() {
prky = readDataOnce(PRIVATE_KEY_FILE);
puky = readDataOnce(PUBLIC_KEY_FILE);
}
/**
* 以 UTF-8 讀碼方式,一次性讀取全部數(shù)據(jù)
* - 適用于小型文件
* - 此處使用在讀取完整的密鑰
* @param filePath 文件路徑
* @return 文件內(nèi)容
*/
private static String readDataOnce(String filePath) {
try {
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
System.out.println(new String(bytes, StandardCharsets.UTF_8));
return new String(bytes, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 讀取數(shù)據(jù)(核心)
* @param file 預讀取文件
* @return 文件相關(guān)內(nèi)容的字節(jié)
* @throws IOException 文件訪問異常、權(quán)限異常
*/
private static byte[] handleReadData(File file){
try {
// 以 1M 為單位,進行分段讀取文件,并重組數(shù)據(jù),返回數(shù)據(jù)相關(guān)字節(jié)數(shù)組
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
byte[] tmpBuffer = new byte[READER_1M];
int count;
while ((count = in.read(tmpBuffer)) != -1) {
byteOut.write(tmpBuffer, 0, count);
tmpBuffer = new byte[READER_1M];
}
in.close();
return byteOut.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 通過 公鑰 進行加密操作
*
* @param fileByte 文件字節(jié)數(shù)組
* @param publicKeyByte 公鑰字節(jié)數(shù)組
* @return 加密文件字節(jié)數(shù)組
* @throws Exception 異常
*/
private static byte[] encryptByPublicKey(byte[] fileByte, byte[] publicKeyByte) {
try {
// 指定加密算法
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
// 生成公鑰
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyByte);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 指定配置并初始化
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 進行加密処理
return handleData(cipher, fileByte, Cipher.ENCRYPT_MODE);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 通過 私鑰 進行加密操作
*
* @param dataStr 加密文件字節(jié)數(shù)組
* @param privateKeyByte 私鑰字節(jié)數(shù)組
* @return 文件字節(jié)數(shù)組
* @throws Exception 異常
*/
private static byte[] decryptByPrivateKey(byte[] dataStr, byte[] privateKeyByte) {
try {
// 指定加密算法
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
// 生成私鑰
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyByte);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 指定配置并初始化
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 進行解密処理
return handleData(cipher, dataStr, Cipher.DECRYPT_MODE);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 処理數(shù)據(jù)(核心)
* @param cipher cipher配置對象
* @param fileByte 文件字節(jié)數(shù)組
* @param modeIndex 處理模式
* 選項一、Cipher.ENCRYPT_MODE
* 選項二、Cipher.DECRYPT_MODE
* @return
*/
private static byte[] handleData(Cipher cipher, byte[] fileByte, int modeIndex) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// 進行模式選擇
// - 根據(jù)密鑰大小等級,進行模式選擇的最值
int singleMax = modeIndex == Cipher.DECRYPT_MODE
? thisSize.getDecryptSize() : thisSize.getEncryptSize();
// 獲取數(shù)據(jù)最大長度,并作其余初始化
int inputLen = fileByte.length;
int offSet = 0;
byte[] cache;
int i = 0;
// 分段処理進行 加密/解密 操作 (整個文件全部,如果你要加密的文件不大的話,可以使用這個,我這個業(yè)務是要加密一個500M的壓縮包,所以選擇了下面那個代碼)
// while (inputLen - offSet > 0) {
// if (inputLen - offSet > singleMax) {
// cache = cipher.doFinal(fileByte, offSet, singleMax);
// } else {
// cache = cipher.doFinal(fileByte, offSet, inputLen - offSet);
// }
// out.write(cache, 0, cache.length);
// i++;
// offSet = i * singleMax;
// }
// 部分処理進行 加密/解密 操作
Boolean flag = true;
while (inputLen - offSet > 0) {
if (flag){
if (inputLen - offSet > singleMax) {
cache = cipher.doFinal(fileByte, offSet, singleMax);
} else {
cache = cipher.doFinal(fileByte, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
flag = false;
}else {
if (inputLen - offSet > singleMax){
byte[] bytes = new byte[singleMax];
int i1 = offSet;
int i2 = singleMax ;
System.arraycopy(fileByte,(i1),bytes,0,(i2));
cache = bytes;
out.write(cache, 0, bytes.length);
}else {
int i1 = (inputLen - offSet + 1);
byte[] bytes = new byte[i1];
int i2 = offSet;
int i3 = i1 - 1 ;
System.arraycopy(fileByte,(i2),bytes,0,(i3));
cache = bytes;
out.write(cache, 0, bytes.length);
}
}
i++;
offSet = i * singleMax;
}
// 公共部分了
// 數(shù)據(jù)轉(zhuǎn)換、關(guān)閉資源、并返回已處理數(shù)據(jù)
byte[] data = out.toByteArray();
out.close();
return data;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 給文件中寫入數(shù)據(jù)
* @param file 文件對象
* @param data 數(shù)據(jù)字節(jié)數(shù)組
*/
private static void writeData(File file, byte[] data) {
try {
FileOutputStream out = new FileOutputStream(file);
assert data != null : "write data is null.";
out.write(data);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、執(zhí)行結(jié)果
文章來源:http://www.zghlxwxcb.cn/news/detail-529205.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-529205.html
到了這里,關(guān)于Java代碼實現(xiàn)RSA算法加密解密文件功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!