在Android中,對外部存儲進行加密可以通過以下步驟實現:
確定加密范圍:首先,你需要確定哪些文件或文件夾需要進行加密。通常,敏感數據如照片、視頻、聯系人信息等應該被加密。
選擇加密算法:Android提供了多種加密算法,如AES(高級加密標準)。你可以選擇適合的算法來保護你的數據。
使用Android加密API:Android提供了Cipher
類和相關的加密庫,可以用來實現數據的加密和解密。以下是一個簡單的示例,展示如何使用AES算法對數據進行加密:
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.Base64;
public class EncryptionHelper {
private static final String KEY_ALIAS = "myKeyAlias";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static SecretKey getSecretKey(Context context) throws NoSuchAlgorithmException {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
if (!keyStore.containsAlias(KEY_ALIAS)) {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_ECB)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS5)
.build();
keyGenerator.init(keyGenParameterSpec);
keyGenerator.generateKey();
}
return ((KeyStore) keyStore).getKey(KEY_ALIAS, null);
}
public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}
public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.decode(encryptedText, Base64.DEFAULT);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
}
}
存儲加密數據:將加密后的數據存儲在外部存儲中。你可以使用FileOutputStream
將加密后的數據寫入文件。
讀取加密數據:當需要讀取加密數據時,使用相同的密鑰和加密算法進行解密。
考慮外部存儲權限:確保你的應用具有外部存儲的權限。在Android 6.0(API級別23)及以上版本,你需要在運行時請求存儲權限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
在代碼中檢查權限并請求:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
}
通過以上步驟,你可以對外部存儲進行加密,以保護敏感數據的安全。