通过提高应用的安全性,您有助于维护用户信任和设备完整性。
本页介绍了若干最佳实践,这些实践对您的应用安全性有显著的积极影响。
强制安全通信
当您保护您的应用与其他应用之间,或您的应用与网站之间交换的数据时,您可以提高应用的稳定性并保护您发送和接收的数据。
保护应用间的通信
为了更安全地在应用之间通信,请使用带有应用选择器的隐式 intent、基于签名的权限和未导出的内容提供程序。
显示应用选择器
如果隐式 intent 可以在用户的设备上启动至少两个可能的应用,请明确显示应用选择器。这种交互策略允许用户将敏感信息传输到他们信任的应用。
Kotlin
val intent = Intent(Intent.ACTION_SEND) val possibleActivitiesList: List<ResolveInfo> = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL) // Verify that an activity in at least two apps on the user's device // can handle the intent. Otherwise, start the intent only if an app // on the user's device can handle the intent. if (possibleActivitiesList.size > 1) { // Create intent to show chooser. // Title is something similar to "Share this photo with." val chooser = resources.getString(R.string.chooser_title).let { title -> Intent.createChooser(intent, title) } startActivity(chooser) } else if (intent.resolveActivity(packageManager) != null) { startActivity(intent) }
Java
Intent intent = new Intent(Intent.ACTION_SEND); List<ResolveInfo> possibleActivitiesList = getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_ALL); // Verify that an activity in at least two apps on the user's device // can handle the intent. Otherwise, start the intent only if an app // on the user's device can handle the intent. if (possibleActivitiesList.size() > 1) { // Create intent to show chooser. // Title is something similar to "Share this photo with." String title = getResources().getString(R.string.chooser_title); Intent chooser = Intent.createChooser(intent, title); startActivity(chooser); } else if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); }
相关信息
应用基于签名的权限
当在您控制或拥有的两个应用之间共享数据时,请使用基于签名的权限。这些权限不需要用户确认,而是检查访问数据的应用是否使用相同的签名密钥进行签名。因此,这些权限提供了更流畅、更安全的用户体验。
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp"> <permission android:name="my_custom_permission_name" android:protectionLevel="signature" />
相关信息
禁止访问应用的内容提供程序
除非您打算将数据从您的应用发送到不归您所有的其他应用,否则请明确禁止其他开发者的应用访问您应用的 ContentProvider
对象。如果您的应用可以安装在运行 Android 4.1.1 (API 级别 16) 或更低版本的设备上,此设置尤其重要,因为在这些 Android 版本上,android:exported
元素的 <provider>
属性默认为 true
。
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp"> <application ... > <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.example.myapp.fileprovider" ... android:exported="false"> <!-- Place child elements of <provider> here. --> </provider> ... </application> </manifest>
在显示敏感信息前请求凭据
当您向用户请求凭据以访问其应用中的敏感信息或高级内容时,请求 PIN/密码/图案或生物识别凭据,例如面部识别或指纹识别。
要详细了解如何请求生物识别凭据,请参阅生物识别身份验证指南。
应用网络安全措施
以下各部分介绍了如何提升您应用的安全性。
使用 TLS 流量
如果您的应用与具有知名、受信任证书颁发机构 (CA) 颁发的证书的 Web 服务器通信,请使用如下 HTTPS 请求:
Kotlin
val url = URL("https://www.google.com") val urlConnection = url.openConnection() as HttpsURLConnection urlConnection.connect() urlConnection.inputStream.use { ... }
Java
URL url = new URL("https://www.google.com"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.connect(); InputStream in = urlConnection.getInputStream();
添加网络安全配置
如果您的应用使用新的或自定义 CA,您可以在配置文件中声明网络的安全性设置。此过程允许您创建配置,而无需修改任何应用代码。
要将网络安全配置文件添加到您的应用,请按以下步骤操作:
- 在应用的清单中声明配置
-
添加 XML 资源文件,位于
res/xml/network_security_config.xml
。通过禁用明文传输,指定特定网域的所有流量都必须使用 HTTPS
<network-security-config> <domain-config cleartextTrafficPermitted="false"> <domain includeSubdomains="true">secure.example.com</domain> ... </domain-config> </network-security-config>
在开发过程中,您可以使用
<debug-overrides>
元素明确允许用户安装的证书。此元素在调试和测试期间会覆盖您应用的关键安全选项,而不会影响应用的发布配置。以下代码段展示了如何在您应用的 network security configuration XML 文件中定义此元素:<network-security-config> <debug-overrides> <trust-anchors> <certificates src="user" /> </trust-anchors> </debug-overrides> </network-security-config>
<manifest ... > <application android:networkSecurityConfig="@xml/network_security_config" ... > <!-- Place child elements of <application> element here. --> </application> </manifest>
相关信息:网络安全配置
创建您自己的信任管理器
您的 TLS 检查器不应接受所有证书。如果您的用例符合以下任一条件,您可能需要设置信任管理器并处理所有 TLS 警告:
- 您正在与具有新 CA 或自定义 CA 签名的证书的 Web 服务器通信。
- 您使用的设备不信任该 CA。
- 您无法使用网络安全配置。
要详细了解如何完成这些步骤,请参阅有关处理未知证书颁发机构的讨论。
相关信息
谨慎使用 WebView 对象
您应用中的 WebView
对象不应允许用户导航到您无法控制的网站。在可能的情况下,使用白名单来限制应用 WebView
对象加载的内容。
此外,除非您完全控制并信任应用 WebView
对象中的内容,否则切勿启用JavaScript 接口支持。
使用 HTML 消息通道
如果您的应用必须在运行 Android 6.0 (API 级别 23) 及更高版本的设备上使用 JavaScript 接口支持,请使用 HTML 消息通道而不是在网站和应用之间通信,如下代码段所示:
Kotlin
val myWebView: WebView = findViewById(R.id.webview) // channel[0] and channel[1] represent the two ports. // They are already entangled with each other and have been started. val channel: Array<out WebMessagePort> = myWebView.createWebMessageChannel() // Create handler for channel[0] to receive messages. channel[0].setWebMessageCallback(object : WebMessagePort.WebMessageCallback() { override fun onMessage(port: WebMessagePort, message: WebMessage) { Log.d(TAG, "On port $port, received this message: $message") } }) // Send a message from channel[1] to channel[0]. channel[1].postMessage(WebMessage("My secure message"))
Java
WebView myWebView = (WebView) findViewById(R.id.webview); // channel[0] and channel[1] represent the two ports. // They are already entangled with each other and have been started. WebMessagePort[] channel = myWebView.createWebMessageChannel(); // Create handler for channel[0] to receive messages. channel[0].setWebMessageCallback(new WebMessagePort.WebMessageCallback() { @Override public void onMessage(WebMessagePort port, WebMessage message) { Log.d(TAG, "On port " + port + ", received this message: " + message); } }); // Send a message from channel[1] to channel[0]. channel[1].postMessage(new WebMessage("My secure message"));
相关信息
提供正确的权限
仅请求应用正常运行所需的最低限度权限。在可能的情况下,当您的应用不再需要权限时,请放弃它们。
使用 intent 延迟权限
在可能的情况下,请勿向应用添加权限以完成可在其他应用中完成的操作。而是使用 intent 将请求延迟到已经具有必要权限的不同应用。
以下示例展示了如何使用 intent 将用户定向到联系人应用,而不是请求 READ_CONTACTS
和 WRITE_CONTACTS
权限:
Kotlin
// Delegates the responsibility of creating the contact to a contacts app, // which has already been granted the appropriate WRITE_CONTACTS permission. Intent(Intent.ACTION_INSERT).apply { type = ContactsContract.Contacts.CONTENT_TYPE }.also { intent -> // Make sure that the user has a contacts app installed on their device. intent.resolveActivity(packageManager)?.run { startActivity(intent) } }
Java
// Delegates the responsibility of creating the contact to a contacts app, // which has already been granted the appropriate WRITE_CONTACTS permission. Intent insertContactIntent = new Intent(Intent.ACTION_INSERT); insertContactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE); // Make sure that the user has a contacts app installed on their device. if (insertContactIntent.resolveActivity(getPackageManager()) != null) { startActivity(insertContactIntent); }
此外,如果您的应用需要执行基于文件的 I/O(例如访问存储或选择文件),则不需要特殊权限,因为系统可以代表您的应用完成这些操作。更好的是,在用户选择特定 URI 的内容后,调用应用会获得对所选资源的权限。
相关信息
在应用之间安全地共享数据
请遵循以下最佳实践,以更安全的方式将应用内容与其他应用共享:
- 根据需要强制执行只读或只写权限。
- 通过使用
FLAG_GRANT_READ_URI_PERMISSION
和FLAG_GRANT_WRITE_URI_PERMISSION
标记,为客户端提供一次性数据访问权限。 - 共享数据时,请使用
content://
URI,而不是file://
URI。FileProvider
实例会为您处理此问题。
以下代码段展示了如何使用 URI 权限授予标志和内容提供程序权限,以在单独的 PDF 查看器应用中显示应用的 PDF 文件:
Kotlin
// Create an Intent to launch a PDF viewer for a file owned by this app. Intent(Intent.ACTION_VIEW).apply { data = Uri.parse("content://com.example/personal-info.pdf") // This flag gives the started app read access to the file. addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) }.also { intent -> // Make sure that the user has a PDF viewer app installed on their device. intent.resolveActivity(packageManager)?.run { startActivity(intent) } }
Java
// Create an Intent to launch a PDF viewer for a file owned by this app. Intent viewPdfIntent = new Intent(Intent.ACTION_VIEW); viewPdfIntent.setData(Uri.parse("content://com.example/personal-info.pdf")); // This flag gives the started app read access to the file. viewPdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Make sure that the user has a PDF viewer app installed on their device. if (viewPdfIntent.resolveActivity(getPackageManager()) != null) { startActivity(viewPdfIntent); }
注意:从可写应用主目录执行文件违反了 W^X 规定。因此,以 Android 10 (API 级别 29) 及更高版本为目标的应用无法在其主目录中的文件上调用 exec()
,只能调用嵌入在应用 APK 文件中的二进制代码。此外,以 Android 10 及更高版本为目标的应用无法在内存中修改使用 dlopen()
打开的文件中的可执行代码。这包括所有带有文本重定位的共享对象 (.so
) 文件。
相关信息: android:grantUriPermissions
安全存储数据
尽管您的应用可能需要访问敏感用户信息,但用户仅在信任您能妥善保护数据的情况下才授予您的应用访问其数据的权限。
将私有数据存储在内部存储中
将所有私有用户数据存储在设备的内部存储中,内部存储是按应用沙盒化的。您的应用不需要请求权限即可查看这些文件,其他应用也无法访问这些文件。作为额外的安全措施,当用户卸载应用时,设备会删除该应用在内部存储中保存的所有文件。
以下代码段演示了将数据写入内部存储的一种方法:
Kotlin
// Creates a file with this name, or replaces an existing file // that has the same name. Note that the file name cannot contain // path separators. val FILE_NAME = "sensitive_info.txt" val fileContents = "This is some top-secret information!" File(filesDir, FILE_NAME).bufferedWriter().use { writer -> writer.write(fileContents) }
Java
// Creates a file with this name, or replaces an existing file // that has the same name. Note that the file name cannot contain // path separators. final String FILE_NAME = "sensitive_info.txt"; String fileContents = "This is some top-secret information!"; try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(getFilesDir(), FILE_NAME)))) { writer.write(fileContents); } catch (IOException e) { // Handle exception. }
以下代码段展示了逆向操作:从内部存储读取数据:
Kotlin
val FILE_NAME = "sensitive_info.txt" val contents = File(filesDir, FILE_NAME).bufferedReader().useLines { lines -> lines.fold("") { working, line -> "$working\n$line" } }
Java
final String FILE_NAME = "sensitive_info.txt"; StringBuffer stringBuffer = new StringBuffer(); try (BufferedReader reader = new BufferedReader(new FileReader(new File(getFilesDir(), FILE_NAME)))) { String line = reader.readLine(); while (line != null) { stringBuffer.append(line).append('\n'); line = reader.readLine(); } } catch (IOException e) { // Handle exception. }
相关信息
根据用例将数据存储在外部存储中
将外部存储用于特定于您应用的大型非敏感文件以及您的应用与其他应用共享的文件。您使用的具体 API 取决于您的应用是设计用于访问应用专用文件还是访问共享文件。
如果文件不包含私有或敏感信息,但仅在您的应用中对用户有价值,请将文件存储在外部存储的应用专用目录中。
如果您的应用需要访问或存储对其他应用有价值的文件,请根据您的用例使用以下 API 之一:
- 媒体文件:要存储和访问在应用之间共享的图片、音频文件和视频,请使用 Media Store API。
- 其他文件:要存储和访问其他类型的共享文件(包括下载文件),请使用存储访问框架。
检查存储卷的可用性
如果您的应用与可移除的外部存储设备交互,请记住,用户可能会在您的应用尝试访问存储设备时将其移除。包含逻辑以验证存储设备是否可用。
检查数据有效性
如果您的应用使用外部存储中的数据,请确保数据内容未被损坏或修改。包含逻辑以处理不再处于稳定格式的文件。
以下代码段包含哈希验证器示例:
Kotlin
val hash = calculateHash(stream) // Store "expectedHash" in a secure location. if (hash == expectedHash) { // Work with the content. } // Calculating the hash code can take quite a bit of time, so it shouldn't // be done on the main thread. suspend fun calculateHash(stream: InputStream): String { return withContext(Dispatchers.IO) { val digest = MessageDigest.getInstance("SHA-512") val digestStream = DigestInputStream(stream, digest) while (digestStream.read() != -1) { // The DigestInputStream does the work; nothing for us to do. } digest.digest().joinToString(":") { "%02x".format(it) } } }
Java
Executor threadPoolExecutor = Executors.newFixedThreadPool(4); private interface HashCallback { void onHashCalculated(@Nullable String hash); } boolean hashRunning = calculateHash(inputStream, threadPoolExecutor, hash -> { if (Objects.equals(hash, expectedHash)) { // Work with the content. } }); if (!hashRunning) { // There was an error setting up the hash function. } private boolean calculateHash(@NonNull InputStream stream, @NonNull Executor executor, @NonNull HashCallback hashCallback) { final MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException nsa) { return false; } // Calculating the hash code can take quite a bit of time, so it shouldn't // be done on the main thread. executor.execute(() -> { String hash; try (DigestInputStream digestStream = new DigestInputStream(stream, digest)) { while (digestStream.read() != -1) { // The DigestInputStream does the work; nothing for us to do. } StringBuilder builder = new StringBuilder(); for (byte aByte : digest.digest()) { builder.append(String.format("%02x", aByte)).append(':'); } hash = builder.substring(0, builder.length() - 1); } catch (IOException e) { hash = null; } final String calculatedHash = hash; runOnUiThread(() -> hashCallback.onHashCalculated(calculatedHash)); }); return true; }
仅将非敏感数据存储在缓存文件中
为了更快地访问非敏感应用数据,请将其存储在设备的缓存中。对于大于 1 MB 的缓存,请使用 getExternalCacheDir()
。对于 1 MB 或更小的缓存,请使用 getCacheDir()
。这两种方法都为您提供包含应用缓存数据的 File
对象。
以下代码段展示了如何缓存您的应用最近下载的文件:
Kotlin
val cacheFile = File(myDownloadedFileUri).let { fileToCache -> File(cacheDir.path, fileToCache.name) }
Java
File cacheDir = getCacheDir(); File fileToCache = new File(myDownloadedFileUri); String fileToCacheName = fileToCache.getName(); File cacheFile = new File(cacheDir.getPath(), fileToCacheName);
注意:如果您使用 getExternalCacheDir()
将应用的缓存放置在共享存储中,用户可能会在您的应用运行时弹出包含此存储的媒体。包含逻辑以妥善处理此用户行为导致的缓存未命中。
警告:这些文件未强制执行安全措施。因此,任何以 Android 10 (API 级别 29) 或更低版本为目标并具有 WRITE_EXTERNAL_STORAGE
权限的应用都可以访问此缓存的内容。
相关信息: 数据和文件存储概览
在私有模式下使用 SharedPreferences
当使用 getSharedPreferences()
创建或访问您应用的 SharedPreferences
对象时,请使用 MODE_PRIVATE
。这样,只有您的应用才能访问共享偏好设置文件中的信息。
如果您想在应用之间共享数据,请勿使用 SharedPreferences
对象。而是按照步骤安全地在应用之间共享数据。
相关信息
保持服务和依赖项最新
大多数应用使用外部库和设备系统信息来完成特殊任务。通过使应用的依赖项保持最新,您可以使这些通信点更安全。
检查 Google Play 服务安全提供程序
注意:本部分仅适用于以安装了 Google Play 服务的设备为目标的应用。
如果您的应用使用 Google Play 服务,请确保它在安装了您应用的设备上已更新。在非 UI 线程上异步执行检查。如果设备未更新,请触发授权错误。
要确定安装了您应用的设备上的 Google Play 服务是否最新,请遵循有关更新安全提供程序以防范 SSL 漏洞利用指南中的步骤。
相关信息
更新所有应用依赖项
在部署您的应用之前,请确保所有库、SDK 和其他依赖项都是最新的:
- 对于第一方依赖项(例如 Android SDK),请使用 Android Studio 中提供的更新工具,例如 SDK Manager。
- 对于第三方依赖项,请检查您的应用使用的库的网站,并安装任何可用的更新和安全补丁。
相关信息: 添加构建依赖项
更多信息
要详细了解如何提高应用的安全性,请查看以下资源: