Android 文件加密解密(AES)

private static final String ALGORITHM = "AES";

=========================文件加密=================================

/*** 文件加密* @param secretKey 文件加密密鑰* @param oldFiles 原始文件列表,需要加密的* @param newFiles 構造加密后的文件列表*(選擇多個或者單個)多個文件加密*/
@RequiresApi(api = Build.VERSION_CODES.O)
public  void newEncryptFiles(String secretKey, List<File> oldFiles, List<File> newFiles) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {// 使用密鑰字符串生成秘密密鑰SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);// 獲取 AES 加密算法的實例Cipher cipher = Cipher.getInstance(ALGORITHM);// 使用秘密密鑰初始化密碼 cipher,設置為加密模式cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);//循環復制文件curr = 1;for (int i = 0; i < oldFiles.size(); i++) {File oldFile = oldFiles.get(i);File newFile = newFiles.get(i);long m = oldFiles.get(i).length();int n = (int)(m/100);int s = 0;//每一份的進度// 創建輸入流,讀取源文件try (InputStream inputStream = new FileInputStream(oldFile);// 創建輸出流,寫入加密文件OutputStream outputStream = new FileOutputStream(newFile);// 創建密碼輸出流,連接到輸出流,并使用密碼 cipher 進行加密CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {// 緩沖區大小byte[] buffer = new byte[4096];int bytesRead;// 讀取源文件內容到緩沖區while ((bytesRead = inputStream.read(buffer)) != -1) {// 將加密后的數據寫入加密文件cipherOutputStream.write(buffer, 0, bytesRead);s += 1024;if(s >= n){//進度+1handler.sendEmptyMessage(MSG_COPY_RUNNING);prog ++;s = 0;}}}}}

=========================文件解密=========================

SecretKey secretKeySpec = new SecretKeySpec("sin-17214455-@@@".getBytes(), ALGORITHM);
Cipher cipher = null;
try {cipher = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5Padding");cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);//獲取源加密文件或文件夾路徑File  encryptFile= new File(item.getPath() + File.separator +     item.getEncrypted_name());//獲取目標解密文件或文件夾路徑,解密過后生成的名稱original_nameFile newFile = new File(item.getNewPath(), "original_name");// 創建輸入流,讀取加密文件FileInputStream inputStream = new FileInputStream(encryptFile);// 創建輸出流,寫入解密文件FileOutputStream outputStream = new FileOutputStream(newFile);// 創建密碼輸出流,連接到輸出流,并使用密碼 cipher 進行加密CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);// 緩沖區大小byte[] buffer = new byte[4096];int bytesRead;// 讀取源文件內容到緩沖區while ((bytesRead = cipherInputStream.read(buffer)) != -1) {// 將加密后的數據寫入解密文件outputStream.write(buffer, 0, bytesRead);}outputStream.close();inputStream.close();cipherInputStream.close();if (!newFile.exists()) {newFile.createNewFile();}if (!newFile.getParentFile().exists()) {newFile.getParentFile().mkdirs();}
??//解密到這里就結束了打開文件,這里就根據自己的需求而定。下面是我自己的一個需求。// 打開文件,調用系統的打開選擇的圖片,text文件或者其他 FileUtil.openFile(view.getContext(), newFile, ext);
} catch (IOException e) {throw new RuntimeException(e);
} catch (NoSuchFileToOpenException e) {ToastUtil.errorToast(view.getContext(), e.getMessage());throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);
} catch (InvalidKeyException e) {throw new RuntimeException(e);
}
/*** 調用系統應用打開文件* @param context context* @param file file對象* @param ext 擴展名()* @throws NoSuchFileToOpenException 沒有文件異常*/
public static void openFile(Context context, File file,String ext) throws NoSuchFileToOpenException {if(! file.exists()){throw new NoSuchFileToOpenException("文件不存在");}//根據擴展名,適配相應的typeString type = getType(ext);Intent intent = new Intent();intent.setAction(Intent.ACTION_VIEW);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);Uri contentUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider", file);intent.setDataAndType(contentUri,type);} else {Uri uri = Uri.fromFile(file);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setDataAndType(uri,type);}context.startActivity(intent);
}
/*** 根據擴展名適配打開類型* @param ext 文件擴展名* @return 打開類型*/
public static String getType(String ext) {switch (ext){case "3gp":return "video/3gpp";case "apk":return "application/vnd.android.package-archive";case "asf":return "video/x-ms-asf";case "avi":return "video/x-msvideo";case "bin":return "application/octet-stream";case "bmp":return "image/bmp";case "c":return "text/plain";case "class":return "application/octet-stream";case "conf":return "text/plain";case "cpp":return "text/plain";case "doc":return "application/msword";case "docx":return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";case "xls":return "application/vnd.ms-excel";case "xlsx":return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case "exe":return "application/octet-stream";case "gif":return "image/gif";case "gtar":return "application/x-gtar";case "gz":return "application/x-gzip";case "h":return "text/plain";case "htm":return "text/html";case "html":return "text/html";case "jar":return "application/java-archive";case "java":return "text/plain";case "jpeg":return "image/jpeg";case "jpg":return "image/jpeg";case "js":return "application/x-javascript";case "log":return "text/plain";case "m3u":return "audio/x-mpegurl";case "m4a":return "audio/mp4a-latm";case "m4b":return "audio/mp4a-latm";case "m4p":return "audio/mp4a-latm";case "m4u":return "video/vnd.mpegurl";case "m4v":return "video/x-m4v";case "mov":return "video/quicktime";case "mp2":return "audio/x-mpeg";case "mp3":return "audio/x-mpeg";case "mp4":return "video/mp4";case "mpc":return "application/vnd.mpohun.certificate";case "mpe":return "video/mpeg";case "mpeg":return "video/mpeg";case "mpg":return "video/mpeg";case "mpg4":return "video/mp4";case "mpga":return "audio/mpeg";case "msg":return "application/vnd.ms-outlook";case "ogg":return "audio/ogg";case "pdf":return "application/pdf";case "png":return "image/png";case "pps":return "application/vnd.ms-powerpoint";case "ppt":return "application/vnd.ms-powerpoint";case "pptx":return "application/vnd.openxmlformats-officedocument.presentationml.presentation";case "prop":return "text/plain";case "rc":return "text/plain";case "rmvb":return "audio/x-pn-realaudio";case "rtf":return "application/rtf";case "sh":return "text/plain";case "tar":return "application/x-tar";case "tgz":return "application/x-compressed";case "txt":return "text/plain";case "wav":return "audio/x-wav";case "wma":return "audio/x-ms-wma";case "wmv":return "audio/x-ms-wmv";case "wps":return "application/vnd.ms-works";case "xml":return "text/plain";case "z":return "application/x-compress";case "zip":return "application/x-zip-compressed";case "":default:return "*/*";}
}

在AndroidManiFest注冊fileprovider

<providerandroid:name="androidx.core.content.FileProvider"android:authorities="${applicationId}.fileprovider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" />
</provider>

在res目錄下的xml里面創建files-path

<?xml version="1.0" encoding="utf-8"?>
<paths><files-pathname="files"path="." /><cache-pathname="cache"path="." />
<!--    <external-path-->
<!--        name="external_storage"-->
<!--        path="." />--><external-pathname="file_safe_root_path"path="." /><external-files-pathname="external_files"path="." /><external-cache-pathname="external_cache"path="." /><external-media-pathname="external_media"path="." /><root-pathname="root"path="." /></paths>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/14454.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/14454.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/14454.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

我的文章分類合集目錄

文章目錄 Java相關基礎常規問題類Docker類RabbitMQ類分庫分表 網絡工程相關路由交換、Cisco Packet TracerIP地址 前端相關數據庫 Java相關 基礎 Java開發規范、項目開發流程 SpringBoot整合MyBatis實現增刪改查(簡單,詳細) SpringBoot整合MybatisPlus&#xff08;詳細&#…

【Muduo】TcpConnection類

Muduo網絡庫的TcpConnection類代表了TCP連接的一端&#xff0c;即服務器與遠程對等端之間的連接。TcpConnection類知道自身和對端的InetAddress、封裝了前面講過的Socket類和Channel類&#xff0c;并且保有管理自己的subLoop指針&#xff0c;還有多種事件處理函數和回調&#x…

【搜索】BFS

#include <iostream> #include <cstring> #include <queue>using namespace std;const int N 110;typedef pair<int, int> PII;int n, m; int g[N][N], d[N][N];//存放地圖//存每一個點到起點的距離int bfs() {queue< PII > q;q.push({0, 0});m…

C語言什么是位段?其優點是什么?

一、問題 在內存中&#xff0c;1byte 8bit&#xff0c;即 1 字節等于 8 位。位由兩個值組成&#xff0c;即 0 和 1 。因此&#xff0c;存儲在計算機中的 1 字節&#xff0c;可以看成是8個?進制數字&#xff08;0 和1&#xff09;組成的串。了解了內存空間的最?單位&#xff…

16.js數學方法和進制轉換

數學方法 &#xff08;1&#xff09;Math.random() 默認生成0-1的隨機數 var resMath.random() console.log(res) &#xff08;2&#xff09;Math.round(數字) 取整&#xff1a;正數-四舍五入 負數-5舍6入 var resMath.round(11)console.log(res) //11var res1Math.round(1…

Aerospike設置日志按日期保存及日志保存日期

配置文件位置&#xff1a;/etc/aerospike/aerospike.conf 是Aerospike的主配置文件&#xff0c;其中包含了日志配置以及其他各種設置。 日志配置&#xff1a;在aerospike.conf文件中&#xff0c;找到logging部分進行配置。以下是一個示例配置&#xff1a; logging { # 日志文…

CentOS7安裝內網穿透實現遠程推送鏡像到本地Docker Registry

文章目錄 前言1. 部署Docker Registry2. 本地測試推送鏡像3. Linux 安裝cpolar4. 配置Docker Registry公網訪問地址5. 公網遠程推送Docker Registry6. 固定Docker Registry公網地址 前言 本文主要介紹如何部署Docker Registry 本地鏡像倉庫,簡單幾步結合cpolar內網穿透工具實現…

網絡安全之重發布與路由策略詳解

重發布&#xff1b;import &#xff08;路由導入&#xff09; 將不同方式&#xff08;直連、靜態、缺省、其他協議&#xff09;的路由器重發布進入RIP&#xff0c;OSPF中。 注意&#xff1a;1、華為中不能將缺省路由重發布進入RUO協議&#xff08;思科也是一樣&#xff09;。…

Mac下QT開發環境搭建詳細教程

QT Qt是一個跨平臺的C應用程序框架&#xff0c;用于開發具有圖形用戶界面&#xff08;GUI&#xff09;的應用程序&#xff0c;同時也可用于開發非GUI程序&#xff0c;比如控制臺工具和服務器。Qt是設計成通用、可移植和高效的&#xff0c;它廣泛應用于全球的企業和開發者社區中…

青少年 CTF 練習平臺:Misc(一)

前言 當然&#xff0c;我可以更詳細地介紹一下青少年CTF練習平臺。 青少年CTF練習平臺是一個專為青少年設計的網絡安全競賽和訓練平臺。該平臺由思而聽&#xff08;山東&#xff09;網絡科技有限公司與克拉瑪依市思而聽網絡科技有限公司共同建設&#xff0c;自2018年創建以來…

圖論定理匯總(二)

第六章 平面圖 (一)、平面圖的概念 定義1 如果能把圖 G G G畫在平面上&#xff0c;使得除頂點外&#xff0c;邊與邊之間沒有交叉&#xff0c;稱 G G G可嵌入平面&#xff0c;或稱 G G G是可平面圖。可平面圖 G G G的邊不交叉的一種畫法&#xff0c;稱為 G G G的一種平面嵌入&…

入門四認識HTML

一、HTML介紹 1、Web前端三大核心技術 HTML&#xff1a;負責網頁的架構 CSS&#xff1a;負責網頁的樣式、美化 JS&#xff1a;負責網頁的行動 2、什么是HTML HTML是用來描述網頁的一種語言。 3、Html標簽 單標簽<html> 雙標簽<h>內容</h> 4、標…

spring boot整合j2cache 關閉二級緩存

我們整合了 j2cache 的項目啟動 日志會輸出 一級緩存 二級緩存 一級是 EhCacheProvider 二級是 SpringRedisProvider 如果 我們不想用二級緩存 在 j2cache.properties 中 加上 j2cache.12-cache-open配置 值為 true/false true是啟用二級緩存 false 是不起用 默認 true 所以 …

多輸入多輸出 | Matlab實現GA-CNN遺傳算法優化卷積神經網絡多輸入多輸出預測

多輸入多輸出 | Matlab實現GA-CNN遺傳算法優化卷積神經網絡多輸入多輸出預測 目錄 多輸入多輸出 | Matlab實現GA-CNN遺傳算法優化卷積神經網絡多輸入多輸出預測預測效果基本介紹程序設計參考資料 預測效果 基本介紹 Matlab實現GA-CNN遺傳算法優化卷積神經網絡多輸入多輸出預測&…

微服務技術框架-注冊中心-負載均衡

應用層的負載均衡可以選擇依賴注冊中心&#xff0c;也可以不依賴注冊中心。以下是兩種情況的詳細說明&#xff1a; 1. 不依賴注冊中心的負載均衡 在沒有注冊中心的情況下&#xff0c;應用層負載均衡可以通過配置靜態服務器列表或動態檢測服務器健康狀態來實現。以下是一些常見…

企業防泄密軟件有哪些,哪個排名最好

機密數據的泄密對于企業而言&#xff0c;已成為最大的信息安全威脅之一。近年來企業面對的最大威脅來自于內部&#xff0c;以利益為出發點的互聯網信息犯罪及案件&#xff0c;在世界各地不斷傳出&#xff0c;因此&#xff0c;信息保護與管控將逐漸成為企業信息安全重點部署項目…

VMware 安裝Windows 7 SP1

1.下載鏡像 迅雷&#xff1a;ed2k://|file|cn_windows_7_enterprise_with_sp1_x64_dvd_u_677685.iso|3265574912|E9DB2607EA3B3540F3FE2E388F8C53C4|/ 2.安裝過程 自定義名字&#xff0c;點擊【瀏覽】自定義安裝路徑 點擊【瀏覽】&#xff0c;選擇下載鏡像的路徑 結束啦~

html+css繪制自定義樣式輸入框

效果&#xff1a; 代碼&#xff1a; html部分&#xff1a; <div class"box"> <div class"newbox"><input type"text" required><div class"name">Username</div></div> </div>css部分 …

投骰子——(隨機游戲的控制)

精華點在于&#xff1a;利用封裝&#xff0c;函數之間的良好調用&#xff0c;從而清晰明了的解決問題。 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> # include<stdlib.h> # include<time.h> # include"math.h" # define ARR_LEN 10 # d…

hpc中查看顯存占用,等效nvidia-smi

nvidia-smi在hpc中無法使用&#xff0c; 但是可以通過以下方法查看應用程序占用的顯存 先執行程序&#xff0c;之后 bjobs輸出 可以看到使用的是gpu01節點 之后 ssh gpu01