一、概述
该项目实现了用户的本地文件经过AES加密,生成所有人可见的加密文件,其他人只有输入指定的密钥才能将该加密文件下载到本地的目的。
二、加密函数与解密函数
private void encryptFile(String inputFile, String outputFile, String secretKey,String algorithm)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
IOException, IllegalBlockSizeException, BadPaddingException {
// 读取文件内容到inputBytes中
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
inputStream.close();
// 创建加密器
Cipher cipher = Cipher.getInstance(algorithm);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 对文件内容进行加密
byte[] outputBytes = cipher.doFinal(inputBytes);
// 将加密后的内容写入到输出文件
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
outputStream.close();
}
private void decryptFile(String inputFile, String outputFile, String secretKey,String algorithm)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
IOException, IllegalBlockSizeException, BadPaddingException {
// 读取加密文件内容
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) new File(inputFile).length()];
inputStream.read(inputBytes);
inputStream.close();
// 创建AES解密器
Cipher cipher = Cipher.getInstance(algorithm);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// 对加密文件内容进行解密
byte[] outputBytes = cipher.doFinal(inputBytes);
// 将解密后的内容写入到输出文件
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
outputStream.close();
}
三、加密与解密过程
1.本地文件内容
2.加密后的内容
3.加密代码
//创建公共文件
publicFile = new File("src/MultiSecureDoc/EncryptedFiles/"+localFile.getName());
try {
//加密
encryptFile(localFile.getPath(),publicFile.getPath(),secretKey,"AES");
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | IOException |IllegalBlockSizeException | BadPaddingException ex) {
throw new RuntimeException(ex);
}
4.解密代码
//判断密码
if(unlockingUI.key.equals(secretKey)){//secretKey为密钥
//targetFile为希望将加密文件下载到何处
File targetFile = new File("src/MultiSecureDoc/DecryptedFiles/"+ publicFile.getName());
try {
//解密
decryptFile(publicFile.getPath(), targetFile.getPath(), secretKey,"AES");
//成功后用记事本打开
Runtime.getRuntime().exec("notepad "+targetFile.getPath());
System.out.println("File decrypted successfully.");
} catch (NoSuchPaddingException | NoSuchAlgorithmException |
InvalidKeyException |IOException | IllegalBlockSizeException |
BadPaddingException runTime_e) {
runTime_e.printStackTrace();
}
}
5.解密文件