<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wan Xiao on Medium]]></title>
        <description><![CDATA[Stories by Wan Xiao on Medium]]></description>
        <link>https://medium.com/@wanxiao1994?source=rss-2069902eeca1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qNpEYNzHlQ6SH6Z5</url>
            <title>Stories by Wan Xiao on Medium</title>
            <link>https://medium.com/@wanxiao1994?source=rss-2069902eeca1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:16:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wanxiao1994/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Technical Principles of Reading Bank Card Numbers Using Android NFC]]></title>
            <link>https://medium.com/@wanxiao1994/technical-principles-of-reading-bank-card-numbers-using-android-nfc-6ab2880206e8?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ab2880206e8</guid>
            <category><![CDATA[icc]]></category>
            <category><![CDATA[emv]]></category>
            <category><![CDATA[apdu]]></category>
            <category><![CDATA[contactless]]></category>
            <category><![CDATA[nfc]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 14:08:58 GMT</pubDate>
            <atom:updated>2024-12-20T15:31:18.874Z</atom:updated>
            <content:encoded><![CDATA[<p>If your Android device supports NFC, simply place your bank card against the back of the phone, and the app can retrieve your card number and expiration date.</p><h3>Introduction</h3><p>Many e-commerce apps require users to bind a bank card for payment purposes. To minimize the hassle of manual input, OCR is often used to extract and autofill card information from the physical card. Nowadays, some apps like Grab and Shopee offer an even more convenient option: using NFC to autofill bank card information.</p><p>If your Android phone supports NFC, and your bank card — whether debit or credit — supports contactless payments, you can experience this impressive feature where the phone automatically identifies your card number and expiration date.</p><p>I created a demo app with one of its features being the ability to identify your bank card using NFC. You can download it from Google Play and try it out:</p><p><a href="https://play.google.com/store/apps/details?id=com.github.wonshaw.apilab">https://play.google.com/store/apps/details?id=com.github.wonshaw.apilab</a></p><p>This article will delve into the technical principles and implementation details behind this feature.</p><h3>Contactless Payment Cards</h3><p>If you take a closer look at your bank card, you might notice a symbol resembling a horizontal Wi-Fi signal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*FaexR7SO8IhVbnqiM9YdoA.png" /><figcaption>There is a contactless symbol in the top-right corner.</figcaption></figure><p>This indicates that your bank card is a contactless payment card. You only need to hold the card close to a POS terminal to complete the payment — there’s no need to swipe the card or insert it into the POS terminal.</p><p>If your card is a UnionPay card with the “QuickPass” printed on it, then it is also a contactless card.</p><p>When you hold your bank card near a POS terminal for payment, the machine communicates with your card via NFC (Near-Field Communication) technology to complete the transaction.</p><h3>EMVCo</h3><p>When you use your bank card to make a payment on a restaurant’s POS terminal, the process feels intuitive. However, behind the scenes, there is a relatively complex system at work.</p><p>You are the cardholder; the bank that issued your card is called the issuing bank; the merchant also has a bank account for receiving payments, usually set up with an acquiring bank. The acquiring bank and the issuing bank are connected through a card network. The card network is responsible for routing transaction requests and coordinating clearing services to ensure funds flow securely from the issuing bank to the acquiring bank and eventually settle in the merchant’s account.</p><p>Your bank card’s ability to work in most parts of the world and be correctly recognized by POS terminals from various manufacturers is largely thanks to a global organization called EMVCo, which was established by major card networks. EMVCo introduced a set of technical specifications known as the EMV specifications. Most bank cards, especially those bearing the logos of major card networks, adhere to these specifications. These specifications unify the data structure and security protocols of chip cards, ensuring compatibility across POS terminals and payment systems from different manufacturers, thereby enhancing the global usability of bank cards.</p><p>Cards that comply with EMV specifications are often referred to as EMV cards.</p><h3>Communication Between Android Devices and EMV Cards</h3><p>Contactless communication between POS terminals and EMV cards is achieved through NFC technology.</p><p>In reality, the device communicating with the POS terminal doesn’t have to be a physical EMV card. As long as it can interact with the POS terminal using a recognized protocol, it can function as a substitute. This is the principle behind products like Apple Pay and Google Pay. Essentially, these products use the phone to emulate an EMV card, communicating with the POS terminal via NFC to complete the payment process. However, they do not directly emulate the original card you’ve added. Instead, they use a virtual card tied to the device for payments. This virtual card has its own card number and expiration date, and from the perspective of the POS terminal, it is indistinguishable from a regular card. As a result, you can use Apple Pay or Google Pay with any terminal that supports contactless EMV card payments.</p><p>Beyond card emulation, NFC in smartphones can also operate in card reader mode. In this mode, an Android device functions similarly to a POS terminal, generating a radio frequency field to power nearby EMV cards and facilitating communication with them.</p><p>Theoretically, by implementing the communication protocols and data exchange processes defined in the EMV specifications through the phone’s NFC capabilities, we can simulate a POS terminal on a smartphone to communicate with EMV cards. To achieve this, it is crucial to understand the specific definitions of contactless communication protocols in the EMV specifications.</p><h3>Related Standards and Specifications</h3><p>This article provides enough detail to help you understand the technical aspects, but here’s a list of the key standards and specifications involved:</p><h4>ISO/IEC 14443</h4><p>NFC communication between mobile devices and EMV cards is governed by the ISO/IEC 14443 series of standards. EMV cards are typically Type A cards as defined in ISO/IEC 14443. Fortunately, the Android NFC API already implements the ISO/IEC 14443 standard, so we only need to focus on the application layer protocol and don’t have to worry about lower-level transmission protocols. Therefore, reading this standard is not necessary.</p><h4>ISO/IEC 7816–4</h4><p>Communication between EMV cards and POS terminals uses the APDU (Application Protocol Data Unit) command and response format at the application layer. However, the EMV specification already provides detailed descriptions of the APDU commands relevant to EMV, so there’s no need to separately study ISO/IEC 7816–4.</p><h4>ISO/IEC 8825–1</h4><p>The data exchanged in EMV card communication extensively uses BER-TLV encoding rules. The EMV specification thoroughly explains the TLV formats used, so it’s not necessary to study ISO/IEC 8825–1 separately.</p><h4>EMV Contactless Specifications</h4><p>Interacting with contactless EMV cards requires consulting the EMV contactless specifications. The following key documents are particularly relevant:</p><ul><li>Book A: Architecture and General Requirements</li><li>Book B: Entry Point Specification</li><li>Book C-n: Kernel Specification</li></ul><h4>EMV Integrated Circuit Card Specifications</h4><p>Although mobile devices and EMV cards communicate via contactless methods, the application layer protocols are fundamentally the same as those defined in the EMV Contact specifications. Therefore, the following EMV Contact specifications are also relevant:</p><ul><li>Book 1: Application Independent ICC to Terminal Interface Requirements</li><li>Book 3: Application Specification</li><li>Book 4: Cardholder, Attendant, and Acquirer Interface<br>Requirements</li></ul><p>Next, I will introduce the theoretical knowledge needed to implement Android NFC functionality for reading EMV card numbers and expiration dates.</p><h3>Interaction Process Between POS Terminals and EMV Cards</h3><p>The interaction process between a POS terminal and an EMV card is shown in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EubIllHQ-0C33vzGxl5l3g.png" /></figure><ol><li><strong>Pre-processing</strong>: In this stage, the POS terminal is configured with necessary parameters and prepares data for subsequent steps. For example, the merchant inputs the transaction amount.</li><li><strong>Protocol Activation</strong>: During this phase, the POS terminal displays the transaction amount and prompts the customer to bring the card near the reader. Simultaneously, the POS terminal uses the reader to detect the EMV card and establish a connection.</li><li><strong>Combination Selection</strong>: After establishing a connection with the card, the terminal selects an application from the card and determines which kernel to use for the transaction.</li><li><strong>Kernel Activation</strong>: The appropriate kernel is activated to process the transaction. Different card networks (e.g., Visa, Mastercard) have distinct transaction logic, requiring different kernels.</li><li><strong>Kernel Processing</strong>: The transaction is processed by the activated kernel, which corresponds to the specific card network’s transaction logic.</li><li><strong>Outcome Processing</strong>: Based on the results from Kernel Processing, the terminal determines the next steps, such as approving or declining the transaction.</li></ol><p>In the transaction process between a POS terminal and an EMV card, the POS terminal reads data from the chip card to retrieve the card number (Primary Account Number, PAN) and expiration date. Retrieving the expiration date is to perform an initial check to verify whether the card is still valid. Retrieving the card number is crucial as it is essential transaction data, used to route the transaction to the correct card network and issuing bank, identify the account involved in the transaction, and serve as an important input for generating dynamic transaction data.</p><h3>NFC Methodology for Retrieving EMV Card Numbers</h3><p>The interaction between the POS terminal and the EMV card occurs during a transaction. To communicate with the EMV card and retrieve the card number and expiration date, we essentially need to control the Android NFC hardware to simulate a POS terminal interacting with the EMV card.</p><p>We will not initiate a transaction like a POS terminal does; instead, we will terminate the process immediately after obtaining the card number and expiration date. We also do not have the capability to initiate a transaction. In general, only EMVCo-certified POS terminals can truly initiate transactions. Although most of these POS terminals also run on Android systems, they have undergone modifications in both hardware and software to comply with EMVCo specifications.</p><p>To simulate a POS terminal interacting with an EMV card, the simulation approach for each step of the POS terminal’s transaction process is as follows:</p><p>To simulate an Android phone as a POS terminal for transactions with an EMV card, the simulation approach for each step of the POS terminal’s transaction process is as follows:</p><ol><li><strong>Pre-processing</strong>: We can directly hard-code the parameters into the code, so there is no need to simulate this step separately.</li><li><strong>Protocol Activation</strong>: The Android NFC hardware already handles the connection with the EMV card for us, so we do not need to focus on this step.</li><li><strong>Combination Selection</strong>: This step requires implementation. It involves two selection commands: selecting PPSE and selecting AID.</li><li><strong>Kernel Activation</strong>: This step can be skipped because we are not implementing a complete kernel.</li><li><strong>Kernel Processing</strong>: This step requires implementation but only to retrieve the card number and expiration date. There is no need to handle unrelated steps. It involves the GPO command and READ RECORD command.</li><li><strong>Outcome Processing</strong>: This step can be ignored.</li></ol><p>Simulating a POS terminal with a smartphone to communicate with an EMV card, the transmission layer is managed by the Android NFC hardware, so we do not need to worry about it. The application layer, however, requires manual implementation. The following section will introduce the protocols and conventions that the application layer relies on. You can skip this part for now and revisit it later when you need to understand the protocols.</p><p>In the EMV specifications, a POS terminal is referred to as a terminal, and this term will be used in the following sections.</p><h3>APDU</h3><p>As mentioned earlier, the application layer protocol between the terminal and the EMV card is based on APDU (Application Protocol Data Unit). The terminal sends APDU commands to the EMV card, and the EMV card replies with APDU responses.</p><h4>APDU Command</h4><p>An APDU command consists of a 4-byte command header and an optional variable-length command body. Its structure is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*vYbbor30uzzYqAyFtFjZeg.png" /></figure><p>Each field of the APDU command is as follows:</p><p><strong>CLA</strong>: 1 byte, indicates the instruction class.<br><strong>INS</strong>: 1 byte, specifies the instruction code.<br><strong>P1</strong>: 1 byte, instruction parameter 1.<br><strong>P2</strong>: 1 byte, instruction parameter 2.<br><strong>Lc</strong>: 0 or 1 byte, represents the length of the Data field in bytes.<br><strong>Data</strong>: The data part of the instruction, variable length, with a length specified by Lc.<br><strong>Le</strong>: 0 or 1 byte, indicates the maximum number of bytes expected in the response. If no data is expected, it can be omitted. If set to 0, the maximum allowed response data length is 256 bytes.</p><h4>APDU Response</h4><p>An APDU response consists of an optional response body and a 2-byte trailer. Its structure is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Nd1jz0sJWTMKhjLQtMm9eg.png" /></figure><p>Its fields are as follows:</p><p><strong>Data</strong>: The data in the response, with a variable length. The transmission layer does not explicitly return its length, but since the response length provided to the application layer is definite, subtracting the 2-byte trailer length gives the length of Data. If no data is present, this field can be omitted.<br><strong>SW1</strong>: 1 byte, command processing status, indicating the overall status of command execution.<br><strong>SW2</strong>: 1 byte, command processing qualifier, providing additional details about the specific status indicated by SW1.</p><p>SW1 and SW2 together determine the status of the APDU response.</p><p>When SW1 = 0x90 and SW2 = 0x00, it indicates that the command was executed successfully. Before parsing any APDU response, always check if SW1 and SW2 indicate success.</p><h3>BER-TLV</h3><p>In APDU, most of the data is represented as BER-TLV (Basic Encoding Rules — Tag-Length-Value) objects. It consists of two or three consecutive fields:</p><ol><li><strong>Tag (T):</strong> The tag field comprises one or more consecutive bytes and represents a class, type, and number. In the EMV specifications, the tag field is encoded in 1 or 2 bytes.</li><li><strong>Length (L):</strong> The length field comprises one or more consecutive bytes and indicates the length of the subsequent field, which is the value. In the EMV specifications, the length field for data transmitted between the card and the terminal is encoded in 1 or 2 bytes.</li><li><strong>Value (V):</strong> The value field represents the value of the data object. If the length field L = ‘00’, the value field does not exist.</li></ol><p>BER-TLV data objects can be categorized into two types:</p><ul><li><strong>Primitive Data Object:</strong> Its value represents a single data element. The structure is T-L-V.</li><li><strong>Constructed Data Object:</strong> Its value contains one or more primitive or constructed data objects. The value field of a constructed data object is referred to as a template. Simply put, the value part of a TLV can consist of multiple consecutive TLVs. The structure is T-L-TLV1-TLV2-…-TLVn.</li></ul><h4>Tag Encoding Method</h4><p>A Tag can consist of one or more bytes.</p><p>If the lowest 5 bits of the first byte in the Tag are all ‘1’ (0bXXX11111), it indicates that the Tag is not a single-byte Tag and requires subsequent bytes to complete it.</p><p>For the subsequent bytes of a multi-byte Tag:</p><ul><li>If the most significant bit is ‘1’ (0b1XXXXXXX), it means there are more bytes contributing to the Tag.</li><li>If the most significant bit is ‘0’ (0b0XXXXXXX), it indicates that this is the final byte of the multi-byte Tag.</li></ul><h4>Length Encoding Method</h4><p>A Length field can also consist of one or more bytes.</p><p>If the most significant bit of the first byte is ‘0’ (0b0XXXXXXX), it is single-byte encoded. The length of the value field is directly indicated by the remaining 7 bits, with a range of [0, 127].</p><p>If the MSB of the first byte is ‘1’ (0b1XXXXXXX), it is multi-byte encoded. The remaining 7 bits of the first byte indicate how many subsequent bytes are part of this Length. These subsequent bytes form a big-endian binary number representing the length of the value field.</p><h3>Data Element Format Conventions in EMV Specifications</h3><p>The EMV specifications use the following data element formats. When processing data, it must be handled according to the type conventions.</p><h4>a (alphabetic data)</h4><p>Each byte contains a single character. Allowed characters are only letters (a to z and A to Z).</p><h4>an (alphanumeric data)</h4><p>Each byte contains a single character. Allowed characters are letters (a to z and A to Z) and digits (0 to 9).</p><p>Exception: For the Payment Account Reference, only uppercase letters (A to Z) and digits (0 to 9) are allowed.</p><h4>ans (alphanumeric special data)</h4><p>Each byte contains a single character. The permitted characters and their coding are shown in the <em>Common Character Set</em> table in EMV <em>Book 4 Annex B</em>.</p><p>Exception: The permitted characters for Application Preferred Name are the non-control characters defined in the ISO/IEC 8859 part designated in the <em>Issuer Code Table Index</em> associated with the Application Preferred Name.</p><h4>b (binary data)</h4><p>Unsigned binary numbers or bit combination data.</p><p>Examples:</p><ul><li>The Application Transaction Counter (ATC) is defined as “b” and has a length of two bytes. If the ATC value is 19, it is stored as hexadecimal 00 13.</li><li>Some data treats each bit of one or more bytes as a status indicator, referred to as bit combination data.</li></ul><h4>cn (compressed numeric data)</h4><p>Each byte contains two numeric characters (with values ranging from hexadecimal &#39;0&#39; to &#39;9&#39;). These data elements are left-aligned and padded with trailing hexadecimal &#39;F&#39;.</p><p>Example<strong>:</strong><br>The value 1234567890123 is stored as hexadecimal 12 34 56 78 90 12 3F FF with a length of 8 bytes.</p><h4>n (numeric data)</h4><p>Each byte contains two numeric characters (with values ranging from hexadecimal &#39;0&#39; to &#39;9&#39;). These numbers are right-aligned and padded with leading hexadecimal zeros.</p><p>Example: The <em>Amount, Authorised</em> field is defined as &quot;n 12&quot; with a length of 6 bytes. The value 12345 is stored as hexadecimal 00 00 00 01 23 45.</p><h4>var. (variable data)</h4><p>Variable length, can contain any combination of bits.</p><h3>DOL</h3><p>Sometimes, the terminal needs to construct a list of data elements according to the requirements of the EMV card and pass it to the card. To minimize the internal processing on the EMV card, this list is not encoded in TLV format but is rather a single field constructed by concatenating multiple data elements.</p><p>Since TLV encoding is not used, the terminal and EMV card must follow some conventions to assemble and parse the fields. In this case, the EMV card provides a DOL (Data Object List). The DOL specifies the data and the length of the data that should be included in the field.</p><p>The format is as follows:<br>Tag1-Length1-Tag2-Length2-…-TagN-LengthN</p><p>The Tag is 1 byte or 2 bytes long and follows the aforementioned TLV encoding method. It represents the Tag of the data that the EMV card requires from the terminal.</p><p>After each Tag, the Length is always 1 byte, representing the length of the data that the EMV card requires from the terminal, measured in bytes.</p><p>Through the DOL, the EMV card can request the terminal to provide the data objects that the EMV card wants to know, but it is limited to primitive data objects.</p><p>The terminal will assemble the data according to the DOL and directly encode it in the following format:<br>Value1 (length = Length1) — Value2 (length = Length2) — … — ValueN (length = LengthN)</p><p>Since the data must be provided according to the EMV card’s requirements, the order and length must strictly match. Therefore, when the terminal assembles the data based on the DOL, it must follow these rules:</p><h4>Unknown Tag or Constructed Data Object</h4><p>If the Tag of a data object identified in the DOL is unknown to the terminal or if it represents a constructed data object, the terminal should provide placeholder data consisting of all hexadecimal zeros, based on the specified length.</p><h4>Optional Static Data Missing</h4><p>If a data object in the list is meaningful to the terminal but the corresponding optional static data is missing from the terminal, the corresponding portion in the command field should be filled with all hexadecimal zeros.</p><h4>Length Less Than Actual Data Length</h4><p>If the length specified in the DOL entry is smaller than the actual length of the data object:</p><ul><li>For numeric data (n), the leftmost bytes of the data element shall be truncated.</li><li>For other types of data, the rightmost bytes of the data shall be truncated for any other format.</li></ul><h4>Length Greater Than Actual Data Length</h4><p>If the length specified in the DOL entry is greater than the actual length of the data object:</p><ul><li>For numeric data (n): Pad with leading hexadecimal zeros.</li><li>For compressed numeric data (cn): Pad the tail with hexadecimal FF.</li><li>For other types of data (an, ans, or b): Pad the tail with hexadecimal zeros.</li></ul><h4>Data Not Applicable to the Current Transaction</h4><p>If a data object in the list is meaningful to the terminal but the data it represents is not applicable to the current transaction, the corresponding portion of the command field should be filled with all hexadecimal zeros.</p><p>With the knowledge and concepts we’ve covered so far, we can now proceed to implement the NFC functionality to read the EMV card number and expiration date.</p><h3>Selecting PPSE</h3><p>Selecting PPSE (Proximity Payment System Environment) is part of the Combination Selection step. This is the first command used to retrieve the list of applications available on the EMV card.</p><p>To construct the SELECT command to choose the file named <em>2PAY.SYS.DDF01</em>, which is a fixed filename for contactless payment environments, we use the following parameters:</p><p><strong>CLA</strong>: ‘00’<br><strong>INS</strong>: ‘A4’<br><strong>P1</strong>: ‘04’, Select by name<br><strong>P2</strong>: ‘00’, Select the first or only file<br><strong>Lc</strong>: Depends on the length of Data<br><strong>Data</strong>: ‘2PAY.SYS.DDF01’ as a ByteArray<br><strong>Le</strong>: ‘00’</p><p>The structure of the data field in the SELECT PPSE response is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7eKY8zCCPPMYMRYCFZjSA.png" /></figure><p>Here, we do not need to worry about 9F3E and 9F3F. When these appear, additional processing is required, but they will not be present in the responses for bank debit or credit cards.</p><p>Our goal is to select an ADF Name (Application Definition File Name) from a Directory Entry.</p><p>The Application Priority Indicator in the Directory Entry determines the priority of the application. In the context of contactless transactions, the high 4 bits of the Application Priority Indicator can be ignored, and the lower 4 bits are treated as a hexadecimal value. If the value is not 0x0, then:</p><ul><li>0x1 represents the highest priority,</li><li>0xF represents the lowest priority. If the value is 0x0, it is considered 0xF. If this field is absent, it is also considered 0xF.</li></ul><p>This way, we can select the Directory Entry with the highest priority. If multiple entries have the same priority, we can select one based on the situation. The ADF Name of this entry will be the input for our SELECT AID command.</p><h3>Selecting AID</h3><p>Selecting the AID (Application Identifier) is also part of the Combination Selection step. After selecting the PPSE, we continue by selecting an application on the EMV card.</p><p>To construct the SELECT command for choosing the application, one of the parameters will be the ADF Name obtained from the previous step. The command structure is as follows:</p><p><strong>CLA</strong>: ‘00’<br><strong>INS</strong>: ‘A4’<br><strong>P1</strong>: ‘04’ (Select by name)<br><strong>P2</strong>: ‘00’ (Select the first or only file)<br><strong>Lc</strong>: Depends on the length of Data<br><strong>Data</strong>: ByteArray of the ADF Name obtained from the PPSE response<br><strong>Le</strong>: ‘00’ (No response data length required)</p><p>The structure of the data field in the SELECT AID response is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zh76s9texiOEbXoZBBlB5g.png" /></figure><p>In the SELECT AID response, we need to parse the PDOL (Processing Options Data Object List), which is identified by 0x9F38. The PDOL is essentially a DOL (Data Object List), but it is specifically used in the subsequent GPO (Get Processing Options) command, so it is referred to as PDOL.</p><p>Additionally, we need to temporarily store the DF Name (Dedicated File Name), with tag 0x9F06, as it might be required for constructing the PDOL data in later steps.</p><h3>GPO Command</h3><p>The GPO (GET PROCESSING OPTIONS) command is part of the Kernel Processing step. The first command in the kernel of major card networks is typically the GPO. From this point forward, we are simulating the Kernel Processing step.</p><p>Based on the PDOL obtained from the previous SELECT AID command, we can construct the PDOL data. The construction method follows the same approach as described in the DOL section. If the PDOL data is missing or if the EMV card’s required PDOL data is not provided, the subsequent GPO command will fail immediately.</p><p>To understand what data might appear in the PDOL, you can refer to the EMV specifications, where the data is derived from the Terminal’s Tag. With the exception of 0x9F06, which is retrieved after selecting the AID, the other data can be constructed in advance.</p><p>When constructing PDOL data, it is essential to follow the sequence given by the EMV card’s PDOL, and adhere to the truncation and padding rules based on different data types.</p><p>The GPO command structure is as follows:</p><p><strong>CLA</strong>: ‘80’<br><strong>INS</strong>: ‘A8’<br><strong>P1</strong>: ‘00’<br><strong>P2</strong>: ‘00’<br><strong>Lc</strong>: Depends on the length of Data<br>Data: The PDOL data that was constructed based on the EMV card’s requirements<br><strong>Le</strong>: ‘00’</p><p>The GPO command has two possible response data formats. Both formats need to be handled correctly, as the EMV card may return the response in either of the two formats:</p><h4>Format 1</h4><p>Format 1 is a basic data object with Tag 0x80, i.e., a TLV.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*FkOSRHc_ORU_aYvijV8ZsA.png" /></figure><p>The AIP (Application Interchange Profile) occupies two bytes, which we do not need to focus on. What we need to parse is the AFL (Application File Locator).</p><h4>Format 2</h4><p>Format 2 is a constructed data object with Tag 0x77, meaning it is a TLV that may contain multiple TLVs but must include the AIP (Application Interchange Profile) and AFL (Application File Locator).</p><p>In the case of Format 2, the response may also include:</p><ul><li>Track 2 Equivalent Data (0x57)</li><li>Application Primary Account Number (0x5A)</li><li>Application Expiration Date (0x5F24)</li></ul><p>These fields can be directly parsed to retrieve the card number and expiration date.</p><h3>READ RECORD</h3><p>If the Track 2 Equivalent Data (0x57) or Application Primary Account Number (0x5A) and Application Expiration Date (0x5F24) are directly obtained through the GPO command, this step can be skipped.</p><p>If the above information is not directly obtained through the GPO command, we must use the READ RECORD command to traverse and read the files on the EMV card to locate this information. The parameters for the READ RECORD command need to be parsed from the AFL.</p><h4>Parsing the AFL</h4><p>The AFL is a list, where each element consists of 4 bytes. The content of these 4 bytes is as follows:</p><p><strong>Byte 1</strong>: The high 5 bits represent the SFI (Short File Identifier). The low 3 bits can be ignored.</p><p><strong>Byte 2</strong>: Represents the first record number to be read under the given SFI. This byte cannot be set to zero.</p><p><strong>Byte 3</strong>: Represents the last record number to be read under the given SFI. The value should be greater than or equal to the value in Byte 2. When the value of Byte 3 is greater than Byte 2, all records from the record number in Byte 2 to the record number in Byte 3 (inclusive) must be read. When Byte 3 equals Byte 2, only the record number specified in Byte 2 should be read.</p><p><strong>Byte 4</strong>: This byte is not necessary for us and can be ignored.</p><p>This way, we obtain the AFL list, where each element contains:</p><ul><li>An SFI (Short File Identifier),</li><li>A starting record number,</li><li>An ending record number.</li></ul><p>The starting and ending record numbers can be the same.</p><p>For each element in the AFL list, and for each record number in that element’s range, the READ RECORD command should be executed.</p><h4>READ RECORD Command</h4><p>The READ RECORD command is constructed as follows, with the key points that it does not require Lc and Data:</p><p><strong>CLA</strong>: ‘00’<br><strong>INS</strong>: ‘B2’<br><strong>P1</strong>: Record number<br><strong>P2</strong>: The high 5 bits correspond to the SFI’s high 5 bits. The low 3 bits are set to ‘100’, which indicates that P1 is the record number.<br><strong>Le</strong>: ‘00’</p><p>The response to the READ RECORD command will be a constructed data object with Tag 0x70. This means that the Value part of the response is a series of TLVs. Within this series of TLVs, we need to search for the following data elements:</p><ul><li>Track 2 Equivalent Data (0x57)</li><li>Application Primary Account Number (0x5A)</li><li>Application Expiration Date (0x5F24)</li></ul><p>During the process of reading and parsing the records, once we collect the EMV card number (PAN) and the expiration date, the READ RECORD traversal can be terminated.</p><p>Assuming we have now obtained the Track 2 Equivalent Data (0x57) or Application Primary Account Number (0x5A) and Application Expiration Date (0x5F24), the next step is to parse them.</p><h3>Track 2 Equivalent Data</h3><p>The Track 2 Equivalent Data (0x57) contains both the card number and expiration date, allowing us to obtain the desired result in one go.</p><p>The format is as follows:</p><p>PAN (n, var. up to 19)<br>Hex ‘D’<br>Expiration date (n 4)<br>Other data</p><p>Both the PAN (card number) and expiration date are numeric data. The PAN can have up to 19 digits, with a hexadecimal ‘D’ separating the card number from the expiration date. The expiration date consists of 4 digits, formatted as YYMM.</p><h3>Application Primary Account Number</h3><p>Application Primary Account Number (0x5A) contains only the PAN (card number).</p><p>The format is as follows:</p><p>cn var (up to 19)</p><p>The PAN is compressed numeric data, with a maximum of 19 digits. The data length can be up to 10 bytes. As mentioned earlier, for compressed numeric data, the digits are left-aligned, so there may be an additional 0xF at the end, which should be discarded.</p><h3>Application Expiration Date</h3><p>Application Expiration Date (0x5F24) contains only the expiration date data.</p><p>The format is as follows:</p><p>n 6 (YYMMDD)</p><p>The expiration date is numeric data, consisting of 6 digits. The date format is YYMMDD.</p><p>Now, you should have a clear understanding of the technical principles behind reading the EMV card number via NFC. The steps outlined above are applicable to contactless EMV cards from major card networks.</p><p>中文版：</p><p><a href="https://medium.com/@wanxiao1994/android-nfc%E8%AF%BB%E5%8F%96%E9%93%B6%E8%A1%8C%E5%8D%A1%E5%8F%B7%E7%9A%84%E6%8A%80%E6%9C%AF%E5%8E%9F%E7%90%86-5d9750f2a172">Android NFC读取银行卡号的技术原理</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ab2880206e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android NFC读取银行卡号的技术原理]]></title>
            <link>https://medium.com/@wanxiao1994/android-nfc%E8%AF%BB%E5%8F%96%E9%93%B6%E8%A1%8C%E5%8D%A1%E5%8F%B7%E7%9A%84%E6%8A%80%E6%9C%AF%E5%8E%9F%E7%90%86-5d9750f2a172?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9750f2a172</guid>
            <category><![CDATA[contactless]]></category>
            <category><![CDATA[icc]]></category>
            <category><![CDATA[apdu]]></category>
            <category><![CDATA[nfc]]></category>
            <category><![CDATA[emv]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 12:04:40 GMT</pubDate>
            <atom:updated>2024-12-20T15:31:16.143Z</atom:updated>
            <content:encoded><![CDATA[<p>如果你的手机支持 NFC，只需要将你的银行卡贴在手机背面，App 就可以获取到你的银行卡号和过期日期。</p><h3>引言</h3><p>许多电商 App 中，都需要用户绑定银行卡用于支付。为了减少用户输入的麻烦，一般使用 OCR 提取银行卡上的信息做自动填充。如今部分 App 如 Grab、Shopee 会提示你使用 NFC 自动填充银行卡信息。</p><p>如果你的 Android 手机支持 NFC，同时你的银行卡、无论是储蓄卡还是信用卡、支持非接触式支付，你就可以体验这一神奇的功能，手机自动识别你的银行卡号和过期日期。</p><p>我做了一个 demo，其中一个功能就是使用 NFC 识别你的银行卡，你可以从 Google Play 下载体验：</p><p><a href="https://play.google.com/store/apps/details?id=com.github.wonshaw.apilab">https://play.google.com/store/apps/details?id=com.github.wonshaw.apilab</a></p><p>本文将介绍这一功能背后的技术原理和实现细节。</p><h3>非接触式支付卡</h3><p>如果你观察你的银行卡，上面往往会有一个放倒的 Wi-Fi 信号一样的标志：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*FaexR7SO8IhVbnqiM9YdoA.png" /><figcaption>右上角有 contactless 标志</figcaption></figure><p>这个就代表你的银行卡是一张非接触式支付卡，只需要将卡片靠近 POS 机就可以完成支付，不需要“刷”卡，也不需要将卡片插入 POS 机。</p><p>如果你的卡是银联卡，上面印有 QuickPass 的字样，则你的银联卡也是非接触式卡。</p><p>当你将你的银行卡靠近 POS 机以付款时，POS 机与你的卡通过 NFC（Near-field communication，近场通信）通信，以完成交易。</p><h3>EMVCo</h3><p>当你拿着你的银行卡，在一家餐馆的 POS 机上刷卡时，一切都很符合直觉，但这背后其实有一套相对复杂的流程。</p><p>你是持卡人；你的卡片所属的银行叫发卡行；商户也有自己的银行账户用来收款，一般商户的银行账号设立在收单行；收单行和发卡行之间需要通过卡组织网络连接；卡组织负责路由交易请求并协调清算服务，确保资金从发卡行安全地流向收单行并最终结算到商户账户。</p><p>你的银行卡之所以可以在全球大多数地区使用，并能被不同制造商的 POS 机正确识别，是因为主流卡组织联合建立了一个叫 EMVCo 的组织，EMVCo 推出了一系列技术规范。大多数银行卡，特别是印有主流卡组织标志的卡，都遵循 EMV 规范，这些规范统一了芯片卡的数据结构和安全协议，确保不同厂商的 POS 机和支付系统能够兼容使用，进一步提升了银行卡的全球适用性。</p><p>这些遵循 EMV 规范的卡，也可以叫 EMV 卡。</p><h3>Android 设备与 EMV 卡通信</h3><p>POS 机与 EMV 卡的非接触式通信是通过 NFC 进行的。</p><p>实际上，与 POS 机通信的并不需要真的是一张 EMV 实体卡，只要它能以 POS 机认可的协议与 POS 机交互即可，这就是 Apple Pay、Google Pay 等产品的原理。它们本质上就是用手机模拟一张 EMV 卡，通过 NFC 与 POS 机通信，完成支付流程。不过，它们并不直接模拟你添加的原始卡片，而是使用一个与设备绑定的虚拟卡进行支付。这个虚拟卡也有卡号和有效期，对 POS 机来说和普通卡并无区别，所以只要是支持刷非接触 EMV 卡的机器，你都能用 Apple Pay 或者 Google Pay。</p><p>手机 NFC 除了可以模拟卡片，还能以读卡器模式工作，此时 Android 设备类似一台 POS 机，会产生射频场给靠近的 EMV 卡供电并与其通信。</p><p>理论上，只要通过手机 NFC 实现 EMV 规范中定义的通信协议和数据交互流程，我们就可以用手机模拟一台 POS 机与 EMV 卡通信。为此我们必须了解 EMV 规范对非接触通信协议的具体定义。</p><h3>相关的标准和规范文件</h3><p>阅读本文足以让你了解其中的技术细节，但这里还是列举一下涉及的主要标准和规范文件。</p><h4>ISO/IEC 14443</h4><p>手机与 EMV 卡通过 NFC 通信，涉及 ISO/IEC 14443 系列标准，EMV 卡一般为 ISO/IEC 14443 标准中的 A 型卡。但好在 Android 提供的 NFC API 已经为我们实现了 ISO/IEC 14443 标准，我们只需要关注应用层协议即可，无需关心传输协议及以下的部分，因此我们无需阅读这个标准。</p><h4>ISO/IEC 7816–4</h4><p>EMV 卡与 POS 机的通信，应用层使用 APDU（Application Protocol Data Unit）命令与响应格式。不过 EMV 规范中本身对 APDU 已经有比较详尽的描述，我们也只需要关注 EMV 相关的 APDU，因此无需单独阅读 ISO/IEC 7816–4。</p><h4>ISO/IEC 8825–1</h4><p>EMV 卡通信中的数据部分大量使用 BER-TLV 编码规则，但 EMV 规范中已经对其用到的 TLV 编码格式有较为详尽的描述，因此无需单独阅读 ISO/IEC 8825–1。</p><h4>EMV <strong>Contactless Specifications</strong></h4><p>与非接触式 EMV 卡的交互流程，需要参考 EMV 非接触式规范，主要参考如下几个规范文件：</p><ul><li>Book A: Architecture and General Requirements</li><li>Book B: Entry Point Specification</li><li>Book C-n: Kernel Specification</li></ul><h4>EMV <strong>Integrated Circuit Card Specifications</strong></h4><p>虽然手机和 EMV 卡是非接触式通信，但其应用层协议和接触式规范中定义的基本相同，因此我们还是需要读 EMV 接触式规范，主要阅读如下几个规范：</p><ul><li>Book 1: Application Independent ICC to Terminal Interface Requirements</li><li>Book 3: Application Specification</li><li>Book 4: Cardholder, Attendant, and Acquirer Interface<br>Requirements</li></ul><p>接下来介绍要实现 Android NFC 读取 EMV 卡号和过期日期的所需了解的理论知识。</p><h3>POS 机与 EMV 卡交互流程</h3><p>一台 POS 机与 EMV 卡的交互流程如下图所示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EubIllHQ-0C33vzGxl5l3g.png" /></figure><ol><li>Pre-processing（预处理）：一般是配置 POS 机的参数，准备好数据，以便后续步骤使用，比如商户需要输入消费金额。</li><li>Protocol Activation（协议激活）：这一阶段，一方面会显示金额，提示消费者将卡片靠近读卡器，另一方面 POS 机也会使用读卡器来尝试发现 EMV 卡，与其建立连接。</li><li>Combination Selection（组合选择）：与卡片建立连接后，会选择卡片上的应用程序，以及决定使用什么内核进行交易。</li><li>Kernel Activation（内核激活）：激活对应的内核，由内核来处理交易。不同卡组织的交易逻辑不同，对应不同的内核。</li><li>Kernel Processing（内核处理）：由对应卡组织的内核来处理交易。</li><li>Outcome Processing（结果处理）：根据 Kernel Processing 的结果，决定下一步，例如是批准交易，还是拒绝。</li></ol><p>在 POS 机与 EMV 卡的交易流程中，POS 机会通过读取芯片卡的数据，获取卡号（Primary Account Number，PAN）、过期日期等信息。获取过期日期是为了初步检查卡片是否仍在有效期内。获取卡号是因为它是交易的重要数据，用于路由交易到正确的卡组织和发卡行，同时标识交易的账户，并作为动态数据生成的重要输入。</p><h3>NFC 获取 EMV 卡号的思路</h3><p>POS 机和 EMV 卡的交互是在执行交易。我们要与 EMV 卡通信获取卡号、过期日期，本质上就是要控制 Android NFC 硬件模拟一台 POS 机与 EMV 卡交互。</p><p>我们不会像 POS 机一样发起交易，而是在我们获取到卡号、过期日期后，就直接终止了。我们也没有能力发起交易，一般情况下，只有经过 EMVCo 认证的 POS 机才能真正发起交易，尽管这些 POS 机大多也是运行在 Android 系统上，但这些设备在软硬件上均做了一些改动，以适应 EMVCo 的规范。</p><p>为了模拟 POS 机与 EMV 卡交互，POS 机交易流程的每个步骤的模拟方案如下：</p><ol><li>Pre-processing：我们直接将参数硬编码在代码里即可，无需单独模拟。</li><li>Protocol Activation：Android NFC 硬件已经帮我们实现了和 EMV 卡的连接，因此我们无需特别关注这个步骤。</li><li>Combination Selection：这一步需要我们实现，涉及两个选择命令，选择 PPSE 和 选择 AID。</li><li>Kernel Activation：我们可以忽略这一步，因为我们并没有实现完整内核。</li><li>Kernel Processing：这一步需要我们实现，但只需要获取到卡号、过期日期即可，无需实现无关的步骤。涉及 GPO 命令和 READ RECORD 指令</li><li>Outcome Processing：这一步无需处理。</li></ol><p>模拟 POS 机与 EMV 卡通信，传输层由 Android NFC 硬件负责，我们无需关心；应用层需要我们自行处理。下面介绍应用层所依赖的协议和约定，你也可以跳过这一部分，之后需要了解协议的时候再回过来看这一部分。</p><p>EMV 规范中，将 POS 机称之为终端（Terminal），下文也将使用这一称呼。</p><h3>APDU</h3><p>前面说到，终端与 EMV 卡的应用层协议，是基于 APDU（Application Protocol Data Unit）的。终端向 EMV 卡发出 APDU 命令，EMV 卡答复 APDU 响应。</p><h4>APDU 命令</h4><p>APDU 命令由 4 字节的命令头和一个可选的变长命令体组成，其结构如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*vYbbor30uzzYqAyFtFjZeg.png" /></figure><p>它的各个字段如下所示：</p><p><strong>CLA</strong>：1 字节，指令类别<br><strong>INS</strong>：1 字节，指令代码<br><strong>P1</strong>：1 字节，指令参数 1<br><strong>P2</strong>：1 字节，指令参数 2<br><strong>Lc</strong>：0 字节或者 1 字节，代表 Data 的字节长度<br><strong>Data</strong>：指令中的数据部分，可变长度，长度为 Lc<br><strong>Le</strong>：0 字节或 1 字节，希望响应返回的数据的最大字节数。如果不需要返回数据，则省略。如设置为 0，则允许返回的数据的最大长度为 256 字节。</p><h4>APDU 响应</h4><p>APDU 响应由一个可选的响应体和 2 字节的尾部组成，其结构如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Nd1jz0sJWTMKhjLQtMm9eg.png" /></figure><p>它的各个字段如下所示：</p><p><strong>Data</strong>：响应中的数据，长度为变长，传输层不会明确返回它的长度，但由于传输层提供给应用层的响应的长度是明确的，减去尾部的长度 2 字节，即可得到 Data 的长度。如果没有数据，这一部分可以省略<br><strong>SW1</strong>：1 字节，命令处理状态，表明命令处理的总体状态<br><strong>SW2</strong>：1 字节，命令处理限定符，表明命令处理的具体状态，是对 SW1 的补充说明</p><p>SW1 和 SW2 共同决定了 APDU 响应的状态。</p><p>当 SW1 = 0x90，SW2 = 0x00 时，代表指令执行是成功的，解析任何 APDU 响应前，都需要先检查 SW1 和 SW2 是成功的。</p><h3>BER-TLV</h3><p>APDU 中数据大部分都是 BER-TLV（Basic Encoding Rules — Tag-Length-Value）数据对象。其由两个或三个连续字段组成：</p><ol><li>标签（T）：标签字段由一个或多个连续字节组成，表示一个类、类型和编号。EMV 规范中标签字段编码占 1 或 2 个字节。</li><li>长度（L）：长度字段由一个或多个连续字节组成，表示后续字段，也就是值的长度。EMV 规范中，卡片和终端间传输的数据，长度字段编码占 1 或 2 个字节。</li><li>值（V）：值字段表示数据对象的值。如果长度字段 L = ‘00’，则不存在值字段。</li></ol><p>BER-TLV 数据对象可以分为两类：</p><ul><li>基本数据对象：它的值就是一个数据元素。结构为 T-L-V。</li><li>构造型数据对象：它的值包含一个或多个基本数据对象或构造型数据对象。构造型数据对象的值字段称为模板。简单来说就是 TLV 的值部分可以是多个连续 TLV 组成的。结构为 T-L-TLV1-TLV2-…-TLVn。</li></ul><h4>Tag 编码方式</h4><p>Tag 可以由一个或多个字节组成，如果 Tag 的第一个字节的低 5 位全为 ‘1’（0bXXX11111），则代表它并不是一个单字节的 Tag，还需要查看后续字节，共同组成 Tag。</p><p>Tag 的非第一个字节的部分：</p><ul><li>如果最高位为 ‘1’（0b1XXXXXXX），则代表它后面还有组成这个 Tag 的字节。</li><li>如果最高位为 ‘0’（0b0XXXXXXX），则代表它是这个多字节 Tag 的最后一个字节。</li></ul><h4>Length 编码方式</h4><p>Length 可以由一个或多个字节组成，如果 Length 的第一个字节的最高位为 ‘0’ （0b0XXXXXXX），则为单字节编码的长度，值字段的长度由其低 7 位直接表示，范围 [0, 127]。</p><p>如果 Length 的第一个字节的最高位为 ‘1’ （0b1XXXXXXX），则为多字节编码的长度，第一个字节的低 7 位表示后续还有多少个字节属于这个 Length。后续的字节组成一个大端表示的二进制数，表示值字段的长度。</p><h3>EMV 规范中的数据类型</h3><p>EMV 规范中数据有其数据类型，在解析、组装数据时需要按照数据类型来操作。</p><h4>a（字母型数据）</h4><p>每个字节包含一个字符。允许的字符仅为字母（a 到 z 和 A 到 Z）。</p><h4>an（字母数字型数据）</h4><p>每个字节包含一个字符。允许的字符为字母（a 到 z 和 A 到 Z）和数字（0 到 9）。</p><p>例外情况：Payment Account Reference（支付账户参考）仅允许大写字母（A 到 Z）和数字（0 到 9）。</p><h4>ans（字母数字特殊型数据）</h4><p>每个字节包含一个字符。允许的字符及其编码见 Book 4 Annex B 的 Common Character Set table（通用字符集表）。</p><p>例外情况：Application Preferred Name（应用首选名称）允许的字符为 ISO/IEC 8859 标准中定义的非控制字符，具体由与应用首选名称相关的 Issuer Code Table Index（发卡机构代码表索引）指定。</p><h4>b（二进制型数据）</h4><p>无符号二进制数，或位组合数据。</p><p>示例：<br>二进制数：应用事务计数器（ATC）定义为“b”，长度为两字节。如果 ATC 值为 19，存储为十六进制 00 13。<br>位组合数据：有一些数据是把一个或多个字节的每一位当作状态指示用的，这种称为位组合数据。</p><h4>cn（压缩数字型数据）</h4><p>每个字节包含两个数字字符（值范围为十六进制 ‘0’–’9&#39;）。<br>这些数据元素左对齐，并用尾随的十六进制 ‘F’ 填充。</p><p>示例：<br>值 1234567890123 存储为十六进制 12 34 56 78 90 12 3F FF，长度为 8 字节。</p><h4>n（数字型数据）</h4><p>每个字节包含两个数字字符（值范围为十六进制 ‘0’–’9&#39;）。<br>这些数字右对齐，并用前导的十六进制零填充。</p><p>示例：<br>Amount, Authorised（授权金额）定义为“n 12”，长度为 6 字节。值 12345 存储为十六进制 00 00 00 01 23 45。</p><h4>var.（可变型数据）</h4><p>可变长度，可以包含任何位组合。</p><h3>DOL</h3><p>有时，终端需要按照 EMV 卡的要求构建一个数据元素列表，并将其传递给卡片。为了尽量减少 EMV 卡内部的处理，这种列表不是 TLV 编码的，而是将多个数据元素串联起来构建的单一字段。</p><p>由于没有使用 TLV 编码，终端和 EMV 卡之间必须通过某种约定来组装和解析字段，这种情况下 EMV 卡会提供 DOL（Data Object List，数据对象列表） ，DOL 指定了要包含在字段中的数据和数据的长度。</p><p>其格式如下：</p><p>Tag1-Length1-Tag2-Length2-…-TagN-LenghN</p><p>其中 Tag 长度为 1 字节或 2 字节，遵循前述 TLV 的编码方式，代表 EMV 卡需要终端提供的数据的 Tag。</p><p>每个 Tag 后面的 Length 统一为一个字节，代表 EMV 卡需要终端提供的该数据的长度，单位为字节。</p><p>通过 DOL，EMV 卡可以要求终端提供 EMV 卡想要知道的数据对象，但仅限基本数据对象。</p><p>终端会根据 DOL 组装数据，直接编码为如下格式：<br>Value1(长度为Length1)-Value2(长度为Length2)-…-ValueN(长度为LengthN)</p><p>因为这里需要按照 EMV 卡的要求给出数据，顺序和长度必须严格匹配，所以终端在根据 DOL 组装数据时，需要遵循如下规则：</p><h4>Tag 未知或为构造型数据对象</h4><p>如果 DOL 中标识的数据对象的 Tag 对终端未知，或者它表示一个构造型数据对象，终端应根据指定的长度提供全为十六进制零的占位数据元素。</p><h4>可选静态数据缺失</h4><p>如果列表中的数据对象对终端有意义，但它表示的可选静态数据在终端中缺失，则命令字段中对应该数据对象的部分应填充全十六进制零。</p><h4>长度小于实际数据长度</h4><p>如果 DOL 条目中指定的长度小于实际数据对象的长度</p><ul><li>对于 数字型数据（n），截断左侧字节，保留右侧字节。</li><li>对于其他格式的数据，截断右侧字节，保留左侧字节。</li></ul><h4>长度大于实际数据长度</h4><p>如果 DOL 条目中指定的长度大于实际数据对象的长度：</p><ul><li>数字型数据（n）：使用前导十六进制零填充。</li><li>压缩数字数据（cn）：尾部填充十六进制 FF。</li><li>其他格式数据（an、ans 或 b）：尾部填充十六进制零</li></ul><h4>数据不适用于当前交易</h4><p>如果列表中的数据对象对终端有意义，但它表示的数据不适用于当前交易，则命令字段中对应该数据对象的部分应填充全十六进制零。</p><p>有了前面的知识储备和思路，现在我们可以着手实现 NFC 读取 EMV 卡号、过期日期的功能。</p><h3>选择 PPSE</h3><p>选择 PPSE（Proximity Payment System Environment）属于 Combination Selection 步骤。这是第一个命令，用来获取 EMV 卡上可用的应用列表。</p><p>构造 SELECT 命令，选择名称为 2PAY.SYS.DDF01 的文件，这个文件名对非接触式支付环境是固定的。</p><p><strong>CLA</strong>：’00&#39;<br><strong>INS</strong>：’A4&#39;<br><strong>P1</strong>：’04&#39;，根据名称选择<br><strong>P2</strong>：’00&#39;，选择首个或唯一一个<br><strong>Lc</strong>：取决于 Data<br><strong>Data</strong>：‘2PAY.SYS.DDF01’ 的 ByteArray<br><strong>Le</strong>：’00&#39;</p><p>选择 PPSE 的响应中数据部分结构如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7eKY8zCCPPMYMRYCFZjSA.png" /></figure><p>这里我们并不需要关心 9F3E 和 9F3F，出现它们时，需要做额外处理，但银行的借记卡、信用卡响应里不会有它们。</p><p>我们的目标是选择一个 Directory Entry 中的 ADF Name（Application Definition File Name）。</p><p>Directory Entry 中 Application Priority Indicator 决定了它的优先级。非接触式下，Application Priority Indicator 的高 4 位可以忽略，低 4 位视为一个 16 进制数，其不为 0x0 时，0x1 代表最高优先级，0xF 代表最低优先级；为 0x0 时视为 0xF；如果没有这个字段，视为 0xF。</p><p>这样我们可以选择一个最高优先级的 Directory Entry，如果存在多个并列的，则可以根据情况选择其中一个。它的 ADF Name 是我们 选择 AID 命令的输入。</p><h3>选择 AID</h3><p>选择 AID（Application Identifier）也属于 Combination Selection 步骤。在选择 PPSE 后，继续选择 EMV 卡上的一个应用。</p><p>这里需要构造 SELECT 命令，其中一个参数为上一个指令中获得的 ADF Name：</p><p><strong>CLA</strong>：’00&#39;<br><strong>INS</strong>：’A4&#39;<br><strong>P1</strong>：’04&#39;，根据名称选择<br><strong>P2</strong>：’00&#39;，选择首个或唯一一个<br><strong>Lc</strong>：取决于 Data<br><strong>Data</strong>：选择 PPSE 获得的 ADF Name 的 ByteArray<br><strong>Le</strong>：’00&#39;</p><p>选择 AID 的响应中数据部分结构如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zh76s9texiOEbXoZBBlB5g.png" /></figure><p>选择 AID 响应中我们需要解析 PDOL（0x9F38），全称 Processing Options Data Object List，它其实就是一个 DOL，只不过是用在下面的 GPO 指令中，所以叫 PDOL。</p><p>此外，需要将 DF Name（Dedicated File Name）的值以 0x9F06 为 Tag 暂存下来，后续步骤构造 PDOL 数据可能会用到。</p><h3>GPO 指令</h3><p>GPO（GET PROCESSING OPTIONS）指令属于 Kernel Processing 步骤，主流卡组织 Kernel 第一条命令都是 GPO。从现在开始都是在模拟 Kernel Processing 步骤。</p><p>根据上一条指令获取到的 PDOL，我们可以构造一个 PDOL 数据，构造方法和 DOL 一节中描述的相同。如果缺少 PDOL 数据，或者未提供 EMV 卡所要求的 PDOL 数据，后续的 GPO 指令将直接失败。</p><p>如果想知道 PDOL 中可能出现什么数据，可以查看 EMV 规范中，数据来源为 Terminal 的 Tag。这些数据中除了 0x9F06，是在选择 AID 后获取到的，其他的都可以提前构造好。</p><p>在构造 PDOL 数据时，需要根据 EMV 卡给出的 PDOL 的顺序，以及不同数据类型的截断、填充规则正确构造。</p><p>构造 GPO 命令。</p><p><strong>CLA</strong>：’80&#39;<br><strong>INS</strong>：’A8&#39;<br><strong>P1</strong>：’00&#39;<br><strong>P2</strong>：’00&#39;<br><strong>Lc</strong>：取决于 Data<br><strong>Data</strong>：构造的 PDOL 数据<br><strong>Le</strong>：’00&#39;</p><p>GPO 响应数据有两种格式，两种格式都需要正确处理，因为我们并不知道 EMV 卡会以哪种格式返回。</p><h4>格式 1</h4><p>格式 1 为一个 Tag 为 0x80 的基本数据对象，即一个 TLV。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*FkOSRHc_ORU_aYvijV8ZsA.png" /></figure><p>其中 AIP（Application Interchange Profile）占用两个字节，我们不关心。我们要解析的是 AFL（Application File Locator）。</p><h4>格式 2</h4><p>格式 2 为一个 Tag 为 0x77 的构造型数据对象，即一个 TLV 里面可能有多个 TLV，但一定包括 AIP（Application Interchange Profile）和 AFL（Application File Locator）</p><p>在格式 2 的情况下，响应中还可能带有 Track 2 Equivalent Data（0x57），Application Primary Account Number（0x5A），Application Expiration Date（0x5F24），可以直接解析出卡号和过期日期。</p><h3>READ RECORD</h3><p>如果通过 GPO 指令直接获取到 Track 2 Equivalent Data（0x57）或 Application Primary Account Number（0x5A）和 Application Expiration Date（0x5F24），则可以跳过这个步骤。</p><p>在没有直接通过 GPO 指令获取到上述信息的情况下，我们必须通过 READ RECORD 指令来遍历读取 EMV 卡上的文件，以找到这些信息。READ RECORD 指令的参数需要解析 AFL 来得到。</p><h4>解析 AFL</h4><p>AFL 为一个列表，这个列表中每个元素的内容都是 4 个字节。这 4 个字节的内容如下：</p><ol><li>第 1 字节：高 5 位表示 SFI（Short File Identifier，短文件标识符），低 3 位可以忽略。</li><li>第 2 字节：表示该 SFI 下要读取的第一个或唯一一个记录号（Record number）。这个字节不能设置为零。</li><li>第 3 字节：表示该 SFI 下要读取的最后一个记录号。其值应大于或等于第 2 个字节的值。当第 3 个字节的值大于第 2 个字节时，应读取从第 2 个字节记录号到第 3 个字节记录号（包含它们）的所有记录。当第 3 个字节的值等于第 2 个字节时，仅读取第 2 个字节编码的记录号。</li><li>第 4 字节：对我们来说用不到，可以忽略。</li></ol><p>这样我们就获得了 AFL 列表，列表中每个元素包含一个 SFI，一个起始记录号，一个结束记录号。起始和结束记录号可以相等。</p><p>对于 AFL 列表中的每一个元素，以及每一个元素的每一个记录号，都执行 READ RECORD 指令。</p><h4>READ RECORD 指令</h4><p>构造 READ RECORD 命令，注意它没有 Lc 和 Data。</p><p><strong>CLA</strong>：’00&#39;<br><strong>INS</strong>：’B2&#39;<br><strong>P1</strong>：记录号<br><strong>P2</strong>：高 5 位对应 SFI 高 5 位，低 3 位为 100，代表 P1 为记录号<br><strong>Le</strong>：’00&#39;</p><p>READ RECORD 响应为 Tag 为 0x70 的构造型数据对象，即它的值为一系列 TLV，在这一系列 TLV 中查找我们要的数据 Track 2 Equivalent Data（0x57）或 Application Primary Account Number（0x5A）和 Application Expiration Date（0x5F24）。</p><p>在这个不断读取解析的过程中，如果收集到了 EMV 卡号和过期日期，则终止这个 READ RECORD 的遍历读取动作。</p><p>假设现在我们已经拿到了 Track 2 Equivalent Data（0x57）或 Application Primary Account Number（0x5A）和 Application Expiration Date（0x5F24），接下来是解析它们。</p><h3>Track 2 Equivalent Data</h3><p>Track 2 Equivalent Data（0x57）中同时包含卡号和过期日期，可以一次性得到我们想要的结果。</p><p>其格式为：</p><p>卡号（n, var. (up to 19)）<br>十六进制 ‘D’<br>过期日期（n 4）<br>其他数据</p><p>卡号和过期日期均为数字型数据，卡号最多有 19 个数字，中间有一个十六进制的‘D’分割，过期日期为 4 个数字，格式为 YYMM。</p><h3>Application Primary Account Number</h3><p>Application Primary Account Number（0x5A）仅包含卡号数据。</p><p>其格式为：</p><p>cn var（. up to 19）</p><p>卡号为压缩数字型数据，卡号本身数字最多 19 个，数据长度最大为 10 字节，前面说过，压缩数字型数据，数字会左对齐，所以其末尾可能会有一个额外的 0xF，需要丢弃掉。</p><h3>Application Expiration Date</h3><p>Application Expiration Date（0x5F24）仅包含过期日期数据。</p><p>其格式为：</p><p>n 6（YYMMDD）</p><p>过期日期为数字型数据，6 个数字，日期格式为 YYMMDD。</p><p>到这里，你已经明白了通过 NFC 读取 EMV 卡号的技术原理。上述步骤，对主流卡组织的非接触式 EMV 卡均有效。</p><p>English version:</p><p><a href="https://medium.com/@wanxiao1994/technical-principles-of-reading-bank-card-numbers-using-android-nfc-6ab2880206e8">Technical Principles of Reading Bank Card Numbers Using Android NFC</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9750f2a172" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview and Insights on Passkeys and Public Key-Based Biometric Authentication Solutions]]></title>
            <link>https://medium.com/@wanxiao1994/introduction-and-reflections-on-passkeys-and-public-key-based-biometric-authentication-solutions-b3120536ea8c?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3120536ea8c</guid>
            <category><![CDATA[webauthn]]></category>
            <category><![CDATA[biometrics]]></category>
            <category><![CDATA[passkey]]></category>
            <category><![CDATA[keystore]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 17:28:14 GMT</pubDate>
            <atom:updated>2024-10-18T02:58:25.186Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, I want to clarify that I have not yet delved deeply into Passkeys. Additionally, since the implementation of Passkeys is not open source, my conclusions are based only on various standard documents and available introductions.</p><h3>What are Passkeys</h3><p>Passkeys are a solution based on public key cryptography that enables passwordless login.</p><p>Traditionally, user authentication has relied on users remembering their passwords, often requiring strong, complex passwords. However, most people struggle to remember multiple strong passwords, leading to password reuse or patterns that are easy to guess. As a result, breaches on certain websites or phishing attacks can lead to password leaks, allowing hackers to impersonate users.</p><p>Autofill frameworks and password managers emerged to help users store and sync passwords automatically, which improved security to some extent. As long as password-based authentication is still in use, it’s difficult to fully defend against phishing attacks, and the need to transmit passwords or some variation of them over the internet remains unavoidable.</p><h3>Simplified process overview</h3><p>Passkeys eliminate the need for passwords by using public key cryptography. Here’s a simplified overview of how it works.</p><h4>Registration</h4><p>The user first needs to register.</p><p>During registration, the server provides a random challenge, along with the user ID and other relevant information.</p><p>The client receives this data from the server and independently generates a pair of cryptographic keys. The private key is securely stored on the client, and the client signs the challenge digest using the private key. It then sends the signed digest and the public key back to the server.</p><p>The server verifies the signature using the received public key, confirming that the client indeed holds the corresponding private key.</p><p>The server then stores the public key, linking it to the user’s ID, and the registration process is complete.</p><h4>Authentication</h4><p>When the user needs to authenticate, the client initiates a request to the server, providing the user’s ID.</p><p>The server responds with a random challenge.</p><p>The client’s authenticator combines the caller’s origin, the server’s challenge, and other information to generate clientDataJSON. The user’s private key signs the hash of clientDataJSON, and the signature is sent to the server.</p><p>The server then uses the public key associated with the user’s ID to verify the signature. If the verification is successful, authentication is complete.</p><p>Throughout this process, the user’s private key is never transmitted over the network. The public key, which is meant to be public, is safe to transmit, and the signature of the digest cannot be used to reverse-engineer the private key. Even if an attacker intercepts the communication, they still cannot access the private key. Additionally, the entire communication process is protected by protocols like TLS. Since the server doesn’t store the user’s private key, even if it is compromised, the attacker cannot obtain the private key.</p><p>As long as the user’s device securely stores the private key, it becomes extremely difficult for an attacker to impersonate the user during authentication.</p><h3>Passkeys Standard Documentation</h3><p>Passkeys are a specific implementation of the FIDO2 standard, which consists of three key components:</p><ol><li><strong>W3C WebAuthn</strong>: This is a set of standards co-developed by W3C and FIDO, designed to provide a more secure and passwordless authentication method for web environments. Browsers that support this standard are capable of using Passkeys. Since the standard is also applicable to apps, Passkeys can be supported by apps if the system offers similar APIs. It’s important to note that whether in-browser web applications or apps running directly on the operating system, they both require support from the operating system and hardware to function properly.</li><li><strong>CTAP2 (Client-to-Authenticator Protocol)</strong>: CTAP2 enables the use of external authenticators (such as FIDO security keys or mobile devices) via USB, NFC, or BLE (Bluetooth Low Energy) to authenticate on FIDO2-enabled browsers and operating systems. This allows for a passwordless, two-factor, or multi-factor authentication experience. This external authenticator is referred to as a <em>roaming authenticator.</em> Through this standard, two key Passkeys features are enabled:<br><strong>a</strong>. When trying to log in on an iPhone, and your Passkey is stored on an Android phone, you can scan a QR code displayed on the iPhone with the Android phone, allowing the Android phone to authenticate on behalf of the iPhone.<br><strong>b</strong>. You can use an external hardware key, similar to a bank security token, to authenticate by plugging it into your phone or computer. A typical example of such a product is Yubikey.</li><li><strong>CTAP1</strong>: This is essentially a rebranding of FIDO U2F (Universal 2nd Factor). FIDO U2F devices, and those based on CTAP2, serve different purposes. U2F devices offer a lower level of security and only provide a second factor in multi-factor authentication (MFA). In other words, after entering a password, the user would insert a U2F device (like a security token) to provide an additional layer of authentication. It cannot replace the primary factor and only supplements it to enhance security. CTAP1 is included in the FIDO2 standard mainly to ensure compatibility with existing U2F devices and to provide a transition path, as U2F currently offers adequate security. However, if you’re focusing solely on Passkey implementation and do not need to support legacy U2F devices, this standard can be largely ignored.”</li></ol><h3>How many roles are there in the Passkeys system?</h3><p>Currently Recommended Standard: <a href="https://www.w3.org/TR/2021/REC-webauthn-2-20210408/">https://www.w3.org/TR/2021/REC-webauthn-2-20210408/</a><br>According to the “Conformance” section of the standard, there are three roles in the Passkeys system:</p><ol><li><strong>User Agents</strong>: Typically refers to browsers or clients that correctly implement the WebAuthn API and effectively communicate with both the server and the authenticator.</li><li><strong>Authenticator</strong>: The WebAuthn API relies on authenticators for key pair generation and usage. Authenticators can be implemented in the operating system beneath the user agent, in external hardware, or through a combination of both.</li><li><strong>Relying Party</strong>: This is the server behind the website or client, responsible for correctly handling and verifying data received from the client and the authenticator.</li></ol><p>Typically, what developers need to do is call the WebAuthn API from the front end using the User Agent and securely pass the relevant information to their server. The developer’s server, acting as the Relying Party, is responsible for verifying the received information.</p><p>The WebAuthn API is usually provided by browsers or the operating system. Authenticators are often integrated directly into the operating system, in which case they are called <em>platform authenticators</em>. Alternatively, they can be integrated into external hardware, such as a USB security token, in which case they are referred to as <em>roaming authenticators</em>.</p><p>Authenticators are responsible for safeguarding the user’s private key and using it for signing. Purely software-based Authenticators often lack sufficient security, so most modern authenticators rely on hardware for security. Examples include Secure Enclave on iOS, Trusted Execution Environment (TEE) on Android, and newer hardware security modules like StrongBox Keymaster.</p><h3>The Relationship Between Passkeys and WebAuthn</h3><p>Passkeys are an implementation based on the WebAuthn standard. Currently, both Chrome and Safari use “Passkeys” in the pop-up prompts when the WebAuthn API is invoked, so in practice, the distinction between Passkeys and WebAuthn is not always clear-cut.</p><p>However, one significant difference between Passkeys and WebAuthn is that WebAuthn defines two modes for storing private keys: one on the device and the other encrypted on the Relying Party’s server. The mode where the private key is stored on the device is referred to as a <em>discoverable credential</em>, and only discoverable credentials can be called Passkeys.</p><p>Reference: <a href="https://www.w3.org/TR/2021/REC-webauthn-2-20210408/#sctn-credential-storage-modality">https://www.w3.org/TR/2021/REC-webauthn-2-20210408/#sctn-credential-storage-modality</a></p><h3><strong>Passkeys availability across Android versions</strong></h3><p>On devices without Google Play services, Android 14 is required. Passkeys rely on the Credential Manager to manage Passkeys, which is a new feature introduced in Android 14.</p><p>If you’re using Jetpack Credential Manager, devices with Google Play services only require Android 9, as Credential Manager support is provided through Google Play services.</p><p>As of May 1, 2024, the distribution of devices is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liZyb7MWLoZYB1mN-Go8Sw.png" /></figure><p>You might wonder why Google Play services provide compatibility down to Android 9.</p><p>This is because Android 9.0 officially introduced several key features:</p><p>A unified biometric authentication API (BiometricPrompt) was introduced, replacing the old FingerprintManager API. However, this change is not critical, as Passkeys don’t necessarily rely on biometric authentication.</p><p>Android 9 supports hardware security modules like <em>StrongBox Keymaster</em>. While Android 6 introduced the TEE (Trusted Execution Environment), which is isolated from the Android system, it still relies on the SoC, making its security dependent on the chip manufacturer. StrongBox Keymaster, on the other hand, is entirely isolated as a dedicated security hardware component. It handles key management and encryption/decryption operations more securely, much like Apple’s Secure Enclave on iOS.</p><p>Additionally, Android 9 supports secure key import.</p><p>Although the hardware security module in Android 9 is optional, many of these technologies only became standardized and mature starting with Android 9, which is why Passkeys support begins with this version.</p><h3><strong>Common Misunderstandings and Questions about Passkeys</strong></h3><h4>Do Passkeys never leave the user’s device?</h4><p>I’ve heard people say more than once that “Passkeys never leave the user’s device.” This is completely a misconception.</p><p>The original FIDO explanation can be found at <a href="https://fidoalliance.org/how-fido-works/">https://fidoalliance.org/how-fido-works/</a>.</p><blockquote>Public key is sent to the online service and associated with the user’s account. Any information about the local authentication method (such as biometric measurements or templates) never leave the local device.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGYWEZMi5B5FPiCpjgPGrA.png" /></figure><p>The statement refers to the fact that any information related to local authentication methods never leaves the device. In other words, your PIN, Face ID, Touch ID — none of these ever leave your device. This is an industry consensus; Face ID, lock screen passwords, and similar credentials need to be set up individually on each device.</p><p>Additionally, the WebAuthn standard describes two ways to store private keys, one of which is:</p><blockquote>By encrypting (i.e., wrapping) the credential private key such that only this authenticator can decrypt (i.e., unwrap) it and letting the resulting ciphertext be the credential ID for the public key credential source. The credential ID is stored by the Relying Party and returned to the authenticator via the allowCredentials option of get(), which allows the authenticator to decrypt and use the credential private key.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8VJ9U1l1_bq8OoPp1EUWA.png" /></figure><p>The standard allows the encrypted private key to be stored by the Relying Party, as long as it ensures that only the Authenticator knows how to decrypt it. This shows that Passkeys can indeed leave the user’s device, but only in an encrypted form.</p><p>Finally, the FIDO Passkey FAQ includes the following question:</p><blockquote>Isn&#39;t it unsafe for passkeys to leave the device and be synced to other devices?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhwWhnfmEOUu7A47Ma1vtQ.png" /></figure><p><a href="https://fidoalliance.org/faqs/#PasskeysFAQs">FAQ - FIDO Alliance</a></p><p>The response is quite long, so I’ll just quote a few sections:</p><blockquote>Passkey syncing is end-to-end encrypted and sync providers have strong account security protections.</blockquote><blockquote>If the cryptographic key is bound to the user’s computer or mobile device, then every time the user gets a new device, the RP would have to fall back to other methods of authentication (typically a knowledge-based credential such as a password). In practice, this often means that the first sign-in on a new device will be both inconvenient <em>and </em>phishable.</blockquote><blockquote>Passkeys solve this issue because they are available on the user’s device if and when the user needs them — starting from the very first sign-in to a website from that device.</blockquote><blockquote>Phishing-resistance is a core design goal of FIDO Authentication. This goal is achieved at sign-in whether or not the cryptographic keys are bound to hardware.</blockquote><p>FIDO believes that Passkey synchronization is an important improvement in convenience. For Passkeys to replace passwords, they must surpass passwords in speed, convenience, and security. Passwords can be synced across a user’s devices. If Passkeys were bound to specific hardware, users would need to go through the registration process again when logging into a new device. This process can be inconvenient and susceptible to phishing attacks, which would undermine the security and usability of the Passkeys solution.</p><p>The response also clearly states that Passkey synchronization is end-to-end encrypted, and the service providers responsible for synchronization must offer strong account security protection.</p><h4>Do Passkeys use biometric authentication only?</h4><p>In the Passkeys system, user authentication is handled by the Authenticator, which is usually integrated into the operating system. The Authenticator uses the local authentication methods available on the device, which don’t necessarily have to be biometric. PINs or patterns can also be used.</p><p>The Relying Party can request to skip user verification, but whether it’s actually enforced depends on the implementation of the Authenticator.</p><h4>How is end-to-end encryption achieved in Passkey synchronization?</h4><p>Some people may wonder how end-to-end encryption is achieved during Passkey synchronization, especially since services like iCloud and Google only know certain characteristics of our account passwords. If account password characteristics alone were used, end-to-end encryption wouldn’t be possible.</p><p>Actually, it’s quite simple. As mentioned earlier, there is a category of information that truly never leaves the device — data used for local user verification. One such piece of information is something the user explicitly knows and can accurately reproduce: the PIN. In a way, the pattern used to unlock a phone is also a form of PIN.</p><p>A key can be derived from the user’s PIN using techniques like adding random salts or key stretching, allowing a very long key to be derived from a short PIN. This key can then be used to encrypt the Passkey. The encrypted Passkey, along with all the random salts used during the key derivation process, is uploaded to the server. Later, when setting up a new device, the key can be reconstructed by entering the PIN of the old device, enabling the Passkey to be decrypted.</p><p>It’s important to note that the server storing this synchronization data could potentially carry out man-in-the-middle attacks or brute force attacks. Since there’s no such thing as a completely online, end-to-end encrypted solution that requires no prior authentication, we have no choice but to trust the service provider that offers Passkey synchronization.</p><p>Typically, when end-to-end encryption is enabled, users are required to enter their old device’s PIN or a synchronization password on the new device in order to access the synchronized data.</p><h4>Why not sign the challenge directly?</h4><p>The Authenticator signs the hash of clientDataJSON, rather than directly signing the challenge or the hash of the challenge. This is primarily to prevent man-in-the-middle attacks because, in Passkey verification, much of the information in clientDataJSON is truthfully reported by the Authenticator. The server can verify the clientDataJSON to ensure the request’s origin is correct.</p><p>Hashing clientDataJSON is to avoid the need for signing the lengthy application layer data; it is only necessary to protect the integrity of clientDataJSON from tampering. Signing the challenge or its hash only prevents replay attacks and cannot prevent man-in-the-middle attacks.</p><h4>Are Passkeys considered MFA?</h4><p>Passkeys can be considered MFA (multi-factor authentication) when user verification is required.</p><p>Multi-factor authentication typically requires verification of two out of the following three factors:</p><ul><li><strong>Knowledge</strong>: Something the user knows, such as their username and password.</li><li><strong>Possession</strong>: Something the user possesses, such as a separate device, security token, ID card, or bank card.</li><li><strong>Inherent</strong>: Biometric characteristics, such as facial recognition, fingerprint, or voice recognition.</li></ul><p>Since the Passkey is stored on the user’s device, signing the challenge digest proves that the user possesses the Passkey corresponding to the public key. At the same time, the Relying Party requires the Authenticator to verify the user’s identity. The Authenticator does this through local verification methods, which may include something the user knows (such as a PIN) or something inherent (such as biometrics), thus fulfilling either a knowledge factor or an inherence factor. Therefore, when user verification is part of the Passkey process, the overall authentication can be considered two-factor authentication (MFA).</p><p>However, whether the user verification part of this multi-factor authentication can be considered a reliable factor is, in my opinion, open to debate. I will explain the reasons in more detail later.</p><h4>Can the Authenticator falsify user verification results?</h4><p>Since the user verification step is performed by the Authenticator, and it typically only reports whether verification was performed or not, the Relying Party does not know the exact verification method or the user’s actual characteristics.</p><p>An untrustworthy or faulty Authenticator could indeed compromise the security of Passkeys. To address this, the Passkeys system includes an <em>Attestation</em> mechanism, primarily during the registration phase. The Authenticator has its own private key and provides Attestation and certificates, allowing the Relying Party to verify the Authenticator’s identity and confirm its authenticity and security. This is similar to the trust chain mechanism in HTTPS certificates.</p><h4>What if the Passkey synchronization service provider is compromised?</h4><p>What if a service provider that syncs user Passkeys, like iCloud or Google Password Manager, is attacked? Or if a user’s iCloud account or Gmail is hacked?</p><p>This isn’t a unique concern. These service providers also sync passwords stored on user devices. If you’re worried about platform account breaches leaking Passkeys, then you should already be concerned about the potential leakage of synced passwords.</p><p>We have to trust that Apple and Google will do their best to ensure that only users who have passed multi-factor authentication can access their accounts and that end-to-end encryption is properly implemented to protect both synced passwords and Passkeys.</p><h4>Can Passkeys exclude PIN as a verification method?</h4><p>You might want to require Passkeys to verify users solely through biometric authentication, but that’s not possible — the specific verification method is determined by the Authenticator.</p><p>Some people might want to exclude PINs because they believe biometric authentication is more secure. However, this is a misconception. From the perspective of accurately proving a user’s identity, knowledge-based factors are often the most reliable. For example, identical twins can sometimes bypass Face ID, leading to unauthorized access.</p><h3>When are Passkeys most applicable?</h3><p>Generally, Passkeys are most suitable for login and registration. If your login page already allows Autofill frameworks to help users fill in or remember passwords, switching to Passkeys will provide a more secure experience.</p><p>Passkeys could also be considered for use in other scenarios, such as payment passwords, but keep in mind that many current Passkey UI prompts display terms like “login,” which may create a bit of confusion for users. Additionally, Passkeys are not entirely equivalent to payment passwords, so it’s important to carefully evaluate the switch beforehand.</p><h3>Can Passkeys replace payment passwords?</h3><p>If your password is akin to a payment password, like a payment PIN, this type of PIN typically isn’t stored in iCloud or Google Password Manager.</p><p>If you’re considering replacing a payment PIN with a Passkey, you may need to clarify some concepts. In my opinion, Passkeys cannot fully replace a payment PIN.</p><h4>What do Passkeys actually verify?</h4><p>Since Passkeys are synced across platforms like iCloud and Gmail, they essentially belong to the owners of those platform accounts.</p><p>In actual use, you’ll notice that the Authenticator only verifies the identity of the device owner. This might seem contradictory — Passkeys are the assets of the platform account owner, so why is the device owner being verified?</p><p>In reality, this isn’t contradictory. When the platform account owner logs into their account on the device and enables syncing, it means the platform account owner trusts the device and allows it to use the passwords and Passkeys stored in their platform account. Meanwhile, the device’s Authenticator only trusts the device owner.</p><p>Thus, each time the Authenticator needs to use a Passkey, it only verifies the device owner’s identity. Verifying the device owner is much simpler than verifying the platform account owner’s identity.</p><p>If the device owner’s biometric characteristics change in the future, such as adding a new fingerprint, the Authenticator will still allow the device owner to use the Passkey because only the device owner can modify the stored biometrics.</p><p>So, the trust chain of Passkeys looks like this:</p><p>Platform account owner ==trusts<strong>==&gt;</strong> the device ==trusts<strong>==&gt;</strong> the device owner.</p><p>Although Passkeys verify the device owner, this verification is based on an underlying trust chain, which is why it only needs to verify the device owner. However, the risk arises if the device owner transfers the device to someone else without logging out of the platform account. In that case, the new person would be able to use the Passkey on that device.</p><p>Earlier, I mentioned that Passkeys constitute multi-factor authentication, but the user verification part only verifies the device owner. Often, we hope to verify the original owner who obtained the Passkey. Due to the trust chain, the current device owner and the original Passkey owner might not be equivalent in the Passkey system.</p><p>In summary, verifying a Passkey means verifying the person who owns the Passkey, which is the owner of a platform account. However, the platform account owner can authorize the device owner to use their Passkey by logging into their account on the device.</p><h4>What does the payment PIN verify?</h4><p>The payment PIN verifies the person who knows the PIN. Whoever can correctly enter the PIN is recognized as the trusted individual. Clearly, only the person who set the PIN knows what it is. In the payment process, the payment system trusts the person who owns the account and knows the payment PIN.</p><p>Therefore, the security level of the payment PIN is higher than that of a Passkey. Using a Passkey is like putting your payment PIN in a room, and whoever holds the key to that room can initiate the payment. On the other hand, with a payment PIN, the PIN is stored in your memory, and no one but you can initiate the payment.</p><p>Many banking apps now support biometric authentication for login. You may notice a distinctive feature: if your biometrics change (such as when you switch to a new phone or add a new fingerprint), the banking app will immediately disable biometric login, requiring you to re-enable it. This is significantly different from the trust chain of Passkeys.</p><p>In the banking scenario, the trust relationship between the bank and the user is one-to-one and direct. The bank needs to ensure that it is trusting a very specific individual — the person who passed identity verification and who had the matching biometrics at that moment. If the biometrics change, the bank cannot continue to trust the same device owner, as it may now be a different person.</p><p>If Passkeys were to replace the payment PIN, the trust chain of Passkeys would be introduced into the payment process. However, when a financial institution trusts user A, it cannot allow that trust to extend further down a chain. By verifying a Passkey, the bank cannot be certain that the current user is the original owner, A, and not a new owner of the device that stores the Passkey.</p><p>While many banks around the world are exploring the use of Passkeys, I believe that, for the time being, Passkeys are not yet suitable for use in the context of payment PIN verification.</p><h3>How biometric authentication for login/payment works in banking apps</h3><p>Although I believe Passkeys are not yet suitable for use in banking apps, biometric authentication systems based on the principles of Passkeys are quite secure. This is the solution commonly used in current banking apps.</p><p>I refer to it as an public key encryption-based biometric authentication solution.</p><p>The principle is similar to that of Passkeys: the client generates a key pair, the private key is kept secure, and the public key is sent to the server for verification. The key difference is that the app directly uses APIs like KeyStore to generate the key pair, specifying that the user must authenticate before the private key can be used, and also specifying that the key pair should be invalidated if biometric data changes. On Android, the corresponding API is setInvalidatedByBiometricEnrollment.</p><p>Since KeyStore-like APIs are used, the generation and use of the keys are handled within KeyStore, possibly in a secure hardware module. The app cannot access the private key at any point, only the public key. As a result, the app cannot export the private key, so there’s no concern about syncing keys — it simply isn’t possible.</p><p>Compared to Passkeys, this solution is evidently more secure because it only trusts the device owner who registered their biometrics at the moment the key pair was generated.</p><p>Additionally, the signing process is also done by KeyStore. The app merely provides the data to be signed, and KeyStore signs it using the private key before returning it to the app. KeyStore ensures that the signing can only proceed after the user has been verified, guaranteeing that someone other than the device owner cannot complete the digital signature process.</p><h3>Availability of public key encryption-based biometric authentication across Android versions</h3><p>For the same reasons as Passkeys, it is recommended to implement this solution only on devices running Android 9 and above to minimize compatibility issues.</p><p>However, there is an additional consideration: the Android CDD (Compatibility Definition Document) defines different biometric security levels for biometric authenticators. The highest level is <em>BIOMETRIC_STRONG (Class 3)</em>, and only biometric authenticators with this strength can be used in conjunction with KeyStore.</p><p>This means that even if a device has a biometric authenticator, it needs to be checked for strength before enabling it.</p><p>In Android’s tiered authentication model, the primary method of authentication is still knowledge-based, such as PIN, pattern, or password. Biometrics belong to the second tier, which is more convenient but less secure. The third tier involves possession-based factors, relying on what the user owns or their environment. The major drawback of possession-based authentication is that it doesn’t fully represent the user’s identity.</p><p>From the perspective of the Android system, using a lock screen password to authenticate the user is more secure than biometric authentication. This is why BiometricPrompt integrates lock screen password verification.</p><p>iOS follows a similar tiered design, where passwords are considered the most secure, while biometrics add convenience. In critical steps, iOS still requires password verification. However, in terms of biometric security, iOS is generally more secure than nearly all Android devices.</p><p>Using biometrics inherently involves a trade-off between security and convenience. This is why it’s necessary to immediately invalidate the key if the biometrics change, in an attempt to maintain user identity accuracy while improving convenience.</p><p>Reference Link<br><a href="https://developers.google.com/identity/passkeys">https://developers.google.com/identity/passkeys</a><br><a href="https://developer.android.com/identity/sign-in/credential-manager">https://developer.android.com/identity/sign-in/credential-manager</a><br><a href="https://www.w3.org/TR/2021/REC-webauthn-2-20210408/">https://www.w3.org/TR/2021/REC-webauthn-2-20210408/</a><br><a href="https://fidoalliance.org/faqs/#PasskeysFAQs">https://fidoalliance.org/faqs/#PasskeysFAQs</a><br><a href="https://source.android.com/docs/security/features/biometric">https://source.android.com/docs/security/features/biometric</a><br><a href="https://security.googleblog.com/2020/09/lockscreen-and-authentication.html">https://security.googleblog.com/2020/09/lockscreen-and-authentication.html</a></p><p>中文版：</p><p><a href="https://medium.com/@wanxiao1994/passkeys-%E5%8F%8A%E5%9F%BA%E4%BA%8E%E9%9D%9E%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86%E7%9A%84%E7%94%9F%E7%89%A9%E7%89%B9%E5%BE%81%E9%AA%8C%E8%AF%81%E6%96%B9%E6%A1%88%E4%BB%8B%E7%BB%8D%E5%92%8C%E6%80%9D%E8%80%83-e5c07287d28d">Passkeys 及基于非对称加密的生物特征验证方案介绍和思考</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3120536ea8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passkeys 及基于非对称加密的生物特征验证方案介绍和思考]]></title>
            <link>https://medium.com/@wanxiao1994/passkeys-%E5%8F%8A%E5%9F%BA%E4%BA%8E%E9%9D%9E%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86%E7%9A%84%E7%94%9F%E7%89%A9%E7%89%B9%E5%BE%81%E9%AA%8C%E8%AF%81%E6%96%B9%E6%A1%88%E4%BB%8B%E7%BB%8D%E5%92%8C%E6%80%9D%E8%80%83-e5c07287d28d?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c07287d28d</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[biometrics]]></category>
            <category><![CDATA[keystore]]></category>
            <category><![CDATA[webauthn]]></category>
            <category><![CDATA[passkey]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 03:24:31 GMT</pubDate>
            <atom:updated>2024-10-18T02:56:22.902Z</atom:updated>
            <content:encoded><![CDATA[<p>首先要说明的是，我还没有深入了解过 Passkeys ，此外因为 Passkeys 的实现基本是不公开源码的，我也只能从各种标准文件和介绍里推测出结论。</p><h3>Passkeys 是什么</h3><p>Passkeys 是基于非对称加密的一种可以实现无密码登陆的方案。</p><p>传统上，用户的身份验证，往往依赖用户记住自己的密码，而且经常是要求用户记住一个强密码。用户当然记不住许多强密码，于是会出现重复使用密码的情况，或者其密码有明显的规律。最终因为某些网站被拖库，或者用户自己被网络钓鱼，导致密码泄漏，被黑客冒充完成用户验证。</p><p>后来出现 Autofill 框架，以及密码管理工具，用来自动帮助用户记住密码和同步密码，在某种程度上提高了安全性。但只要还使用密码认证，就难以抵御网络钓鱼，以及不可避免的需要在网络上传输密码或密码的某种变体。</p><h3>简化后的大概流程</h3><p>Passkeys 借助非对称加密，可以做到无密码登录。这里仅介绍一下简化的大概流程。</p><h4>注册</h4><p>用户首先需要进行注册。</p><p>注册时，服务器会给出一个随机的 challenge，即将注册的用户 ID 等信息。</p><p>客户端拿到服务器数据后，将独立生成一对密钥，其中私钥安全保存，并用私钥对 challenge 的摘要进行签名，将签名的摘要，密钥对中的公钥传回服务器。</p><p>服务器用收到的公钥验证签名，可以确认客户端确实持有这个公钥对应的私钥。</p><p>服务器将公钥保存，关联到用户 ID 上，注册流程结束。</p><h4>验证</h4><p>用户后续验证时，客户端会向服务器发起验证，给出用户 ID 信息。</p><p>服务器会给出一个随机的 challenge。</p><p>客户端的 authenticator 会将调用方的 origin，服务器的 challenge 等信息组合在一起，生成 clientDataJSON，该用户的私钥对 clientDataJson 的摘要进行签名，将签名传给服务器。</p><p>服务器用该用户 ID 对应的公钥进行验证，验证通过，则验证成功。</p><p>以上流程中，自始至终，用户的私钥都没有在网络上传输过。传输的信息中，公钥本来就可以公开，摘要的签名无法反推私钥，即便有攻击者且听到了通信，也无法得知私钥。通信过程本身也要受 TLS 等协议的保护。而服务器上也并不存储用户的私钥信息，即便服务器被攻破，攻击者也不知道用户的私钥是什么。</p><p>只要用户的手机能安全的保存这个私钥，攻击者就难以冒充用户进行验证。</p><h3>Passkeys 的标准文件</h3><p>Passkeys 是 FIDO2 标准的一个具体实现，FIDO2 标准包含三个部分。</p><ol><li>W3C WebAuthn：W3C 和 FIDO 发起并制定的一套标准，旨在为 Web 环境中的身份验证提供一种更加安全和无密码的验证方式。支持这个标准的浏览器，即具有支持 Passkeys 的能力。由于这个标准定义的内容对 app 也适用，当系统提供类似的 API 时，app 也能支持 Passkeys。需要注意的是，无论是运行在浏览器中的web还是直接运行在操作系统里的app，都需要操作系统和硬件提供支持。</li><li>CTAP2：CTAP 全称 Client-to-Authenticator Protocol （客户端到验证器协议）。CTAP2 允许使用外部身份验证器（FIDO 安全密钥、移动设备）通过USB、NFC 或 BLE（Bluetooth Low Energy，低功耗蓝牙）在支持 FIDO2 的浏览器和操作系统上进行身份验证，实现无密码、双因素或多因素身份验证体验。这个外部身份验证器被称为 roaming authenticator。有了这个标准，可以实现两种 Passkeys 能力：<br>a. 当你在iPhone上想要登陆，你发现 Passkeys 在 Android 手机上，你可以通过 Android 手机扫 iPhone 上展示的二维码，让 Android 手机替iPhone 做一次验证。<br>b. 可以有一个外部的实体 key，类似银行的 U盾，在需要验证时，将其插在手机/电脑上，完成验证。典型产品如 Yubikey。</li><li>CTAP1：FIDO U2F（Universal 2nd Factor）的新名字，FIDO U2F 设备和基于 CTAP2 的设备目的不同，安全性低很多，仅能提供多因素验证（MFA）中的第二因素验证，即用户输入密码之后，额外插入U盾这类东西，进行第二因素验证。他不能取代第一因素，不能独立验证，只能作为第一因素之后的一个补充第二因素增强安全性。将CTAP1纳入FIDO2，主要是为了兼容现有U2F设备，以及过渡，因为U2F目前提供足够的安全性。如果专注实现passkey，没有存量U2F设备，可以考虑忽略这个标准文件。</li></ol><h3>Passkeys 方案中有多少角色</h3><p>目前正式推荐的标准：<a href="https://www.w3.org/TR/2021/REC-webauthn-2-20210408/">https://www.w3.org/TR/2021/REC-webauthn-2-20210408/</a></p><p>根据标准中一致性（Conformance）一节，可以得知 Passkeys 方案中存在三个角色。</p><ul><li>User Agents（用户代理）：一般指浏览器或客户端是否正确实现了 WebAuthn 的 API，并与服务器和验证器进行有效的通信。</li><li>Authenticator（验证器）：WebAuthn API 最终都需要通过验证器来实现，包括密钥对的生成和使用等。验证器可以在用户代理底层的操作系统中实现，也可以在外部硬件中实现，或者两者结合实现。</li><li>Relying Party（依赖方）：也就是网站或者客户端背后的服务器，需要能够正确处理和验证来自客户端和身份验证器的数据。</li></ul><p>开发者一般需要做的是，在前端调用 User Agents 的 WebAuthn API，并将相关信息安全的传给开发者的服务器。</p><p>以及开发者服务器作为 Relying Party，验证收到的信息。</p><p>WebAuthn API 通常由浏览器或者操作系统提供。Authenticator 一般直接集成在操作系统中，此时它被称为 platform authenticator（平台验证器），或者集成在某些外部硬件如一个 USB security token 中，此时它被称为 roaming authenticator（漫游验证器）。</p><p>Authenticator 需要保管用户的私钥，以及使用私钥进行签名，纯软件实现的 Authenticator 往往安全性不足，目前 Authenticator 基本都需要依赖硬件提供安全性，例如 iOS 上的 Secure Enclave，Android 上的 TEE（Trusted Execution Environment）以及后来的硬件安全模块 StringBox Keymaster。</p><h3>Passkeys 和 WebAuthn 的关系</h3><p>Passkeys 是基于 WebAuthn 标准的实现。目前 Chrome 和 Safari 在遇到 WebAuthn API 调用时，弹窗都是写的 Passkeys ，所以实际情况下 Passkeys 和 WebAuthn 并不是那么泾渭分明。</p><p>但 Passkeys 目前一个很明显的和 WebAuthn 的区别就在于 WebAuthn 中定义了 Authenticator 两种存储私钥的模式，一种是存在设备上，一种是加密后存在 Relying Party 服务器里。把私钥存在设备中的这种模式，其私钥，或者说凭证是可发现的凭证（discoverable credential），可发现的凭证才能被称为 Passkey。</p><p>参考：<a href="https://www.w3.org/TR/2021/REC-webauthn-2-20210408/#sctn-credential-storage-modality">https://www.w3.org/TR/2021/REC-webauthn-2-20210408/#sctn-credential-storage-modality</a></p><h3>Passkeys 在 Android 上的可用性</h3><p>在没有 Google Play service 的手机上，需要 Android 14。Passkeys 需要依赖 Credential Manager 来管理 Passkey。Credential Manager 是 Android 14 新增的特性。</p><p>如果你使用 Jetpack Credential Manager，在有 Google Play service 的手机上，可以只需要 Android 9。由 Google Play service 来提供 Credential Manager 支持。</p><p>2024–05–01 的设备的分布情况如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liZyb7MWLoZYB1mN-Go8Sw.png" /></figure><p>你可能好奇为什么 Google Play service 提供到 Android 9 的兼容性。</p><p>因为Android 9.0正式引入了几个特性：</p><p>引入了统一的生物认证弹窗API（BiometricPrompt），废弃了原先的指纹API（FingerprintManager），但这个无足轻重。因为 Passkeys 可以不依赖生物验证。</p><p>Android 9 可以搭载硬件安全模块 StrongBox Keymaster。Android 6 引入的TEE（Trusted Execution Environment）虽然和Android系统隔离，但还是依赖 SoC 运行，安全性取决于芯片厂商。StrongBox Keymaster整个硬件都是隔离的，属于专门设计的安全硬件，管理密钥、执行加解密更加安全。相当于iOS的secure enclave。</p><p>且 Android 9 支持安全密钥导入。</p><p>虽然 Android 9 的硬件安全模块是可选的，但因为诸多技术在 Android 9 才标准化和成熟，所以 Passkeys 的支持从 9 开始。</p><h3>Passkeys 常见误解和问题</h3><h4>Passkey 永远不会离开用户的设备吗？</h4><p>我不止一次听到过有人说 “Passkey 永远不会离开用户的设备”。这完全就是一个误传。</p><p>FIDO 的原文在 <a href="https://fidoalliance.org/how-fido-works/">https://fidoalliance.org/how-fido-works/</a> 里：</p><blockquote>Public key is sent to the online service and associated with the user’s account. Any information about the local authentication method (such as biometric measurements or templates) never leave the local device.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGYWEZMi5B5FPiCpjgPGrA.png" /></figure><p>这里说的是有关本地身份验证方法的任何信息都不会离开本地设备。也就是说是你的 PIN、Face ID、Touch ID 这些东西都不会离开设备。这是一种业界共识，Face ID，锁屏密码这些东西在每台手机上都要重新设置。</p><p>此外 WebAuthn 标准中描述了私钥存储的两种方式，其中一种是：</p><blockquote>By encrypting (i.e., wrapping) the credential private key such that only this authenticator can decrypt (i.e., unwrap) it and letting the resulting ciphertext be the credential ID for the public key credential source. The credential ID is stored by the Relying Party and returned to the authenticator via the allowCredentials option of get(), which allows the authenticator to decrypt and use the credential private key.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8VJ9U1l1_bq8OoPp1EUWA.png" /></figure><p>标准中允许将加密后的私钥存储在 Relying Party 中，只要保证只有 Authenticator 知道如何解密即可。可见 Passkey 其实是可以离开用户设备的，只不过是加密后离开。</p><p>最后，FIDO Passkey FAQ 里有这样一个问题：密钥离开设备并同步到其他设备是否不安全？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhwWhnfmEOUu7A47Ma1vtQ.png" /></figure><p><a href="https://fidoalliance.org/faqs/#PasskeysFAQs">https://fidoalliance.org/faqs/#PasskeysFAQs</a></p><p>回答很长，我只摘抄几段：</p><blockquote>Passkey syncing is end-to-end encrypted and sync providers have strong account security protections.</blockquote><blockquote>If the cryptographic key is bound to the user’s computer or mobile device, then every time the user gets a new device, the RP would have to fall back to other methods of authentication (typically a knowledge-based credential such as a password). In practice, this often means that the first sign-in on a new device will be both inconvenient <em>and </em>phishable.</blockquote><blockquote>Passkeys solve this issue because they are available on the user’s device if and when the user needs them — starting from the very first sign-in to a website from that device.</blockquote><blockquote>Phishing-resistance is a core design goal of FIDO Authentication. This goal is achieved at sign-in whether or not the cryptographic keys are bound to hardware.</blockquote><p>FIDO 认为 Passkey 同步是一个很重要的便利提升，Passkeys 想要替代密码，就必须在速度、便利性、安全性上超越密码。密码可以在用户新设备上同步，如果 Passkey 是绑定到硬件的，则当用户在新设备上登录时，需要重新走注册流程，这一阶段非常不便且容易被钓鱼攻击，会导致 Passkeys 方案的安全性和便利性受挫。</p><p>回答中也明确指出，Passkey 的同步是端到端加密的，提供同步的服务商也需要提供强账户安全保护。</p><h4>Passkeys 只用生物验证技术来验证用户吗？</h4><p>Passkeys 中验证用户身份的工作是 Authenticator 来承担的，一般 Authenticator 都是集成在系统中，其会使用设备上支持的本地用户验证方式来验证用户，不需要一定是生物验证技术，PIN、图案也是可以的。</p><p>Relying Party 可以要求不做用户验证，但具体做不做还是依赖 Authenticator 的实现。</p><h4>Passkey 同步端到端加密是如何实现的</h4><p>有些人可能会好奇，Passkey 同步时端到端加密时如何做到的，毕竟像 iCloud 和 Google 只知道我们的账号的密码特征，如果仅用账号密码特征，那是做不到端到端加密的。</p><p>其实比较简单，回想一下之前说的，有一类信息是真的不会离开设备的，那就是本地用户验证用的信息，其中有一项是用户明确知道是什么，能准确复述的，即 PIN。某种程度上，解锁手机的图案，也是一种 PIN。</p><p>可以通过用户的 PIN 派生出一个密钥，派生过程可以使用加随机 salt，密钥延伸等技术，从一个很短的 PIN 派生出一个非常长的密钥。用这个密钥加密 Passkey。加密后的 Passkey，密钥派生过程中使用的全部随机 salt，都要上传到服务器中，这样之后在新设备上，只要输入旧设备的 PIN，就可以重建密钥，解密 Passkey。</p><p>注意这个过程中，存放我们同步数据的服务器，是存在对我们进行中间人攻击或者暴力穷举的可能性的，因为世界上并不存在一个完全在线的，不需要任何事先验证的端到端加密方案，这是不可能的，所以只能信任提供 Passkey 同步的服务商。</p><p>一般来讲，开启端到端加密之后，在新手机上需要输入旧手机的 PIN 或者某个同步密码才能使用同步下来的密码。</p><h4>为什么不直接对 challenge 签名？</h4><p>Authenticator 是对 clientDataJSON 的摘要签名，而非直接对 challenge 签名或 challenge 的摘要签名。</p><p>这主要是避免中间人攻击，因为 Passkey 验证中，clientDataJSON 中的很多信息由 Authenticator 如实报告，服务器可以验证 clientDataJSON 以确保请求来源正确。</p><p>对 clientDataJSON 摘要，是为了避免签名冗长的应用层数据，只需要保护 clientDataJSON 完整未被篡改即可。</p><p>对 challenge 或其摘要签名，只能避免避免重放，无法避免中间人攻击。</p><h4>Passkeys 属于多因素认证吗？</h4><p>Passkeys 在要求验证用户的情况下属于多因素认证。</p><p>多因素认证，一般需要验证以下三个中的两个。</p><ul><li>知识要素：例如用户知晓其用户名及密码</li><li>持有的物件：例如独立的装置、安全令牌、身份证、银行卡等等</li><li>固有要素：生物特征：例如人脸识别、指纹识别、语音识别</li></ul><p>因为 Passkey 保存在用户的设备上，对 challenge 摘要的签名能证明用户确实持有公钥对应的 Passkey。同时 Relying Party 会要求 Authenticator 对用户的身份进行验证，Authenticator 会通过本地验证手段来验证用户，这可能是验证用户所知道的 PIN，也可能是验证用户的生物特征，属于知识要素或者固有要素。所以当 Passkey 验证过程中带有用户验证时，整个验证过程可以视为验证了两个因素的多因素认证。</p><p>但这个多因素认证中，用户验证的部分，能不能构成一个可信因素，我认为有待商榷，具体原因后面会说。</p><h4>Authenticator 会伪造用户验证结果吗？</h4><p>由于用户验证这个步骤由 Authenticator 执行，且一般只报告是否执行了验证，Relying Party 并不知道其具体的验证方式和真实的用户特征。</p><p>一个不诚实或者有缺陷的 Authenticator 确实会导致 Passkeys 的安全性打折扣，所以 Passkeys 中设计了 Attestation（证明）机制，主要在注册阶段，Authenticator 也会有自己的私钥，会提供 Attestation 及证书，Relying Party 可以验证 Authenticator 的身份，证明该 Authenticator 的真实性和安全性。类似 https 证书信任链的机制。</p><h4>Passkey 同步服务商被攻击了怎么办？</h4><p>假如同步用户 Passkey 的服务商如 iCloud、Google Password Manager 被攻击，或者用户的 iCloud 账户、Gmail 邮箱的被黑客盗取了怎么办？</p><p>其实这个并不算一个问题，目前这个服务商同时还会同步用户保存在设备上的密码，如果你担心用户的平台账号被攻破导致 Passkey 泄漏，那你早就应该担心用户同步的密码是不是会泄漏了。</p><p>我们只能信任 Apple 和 Google 会尽量确保只有通过多因素验证过的用户才能登录账户，且正确实现了端到端加密来保护同步的密码和 Passkey。</p><h4>Passkeys 可以排除 PIN 这个验证方式吗？</h4><p>你可能会想要求 Passkeys 只使用用户的生物特征来验证用户，但这做不到，具体的验证方式是 Authenticator 决定的。</p><p>而且有些人想排除 PIN 的动机是因为认为生物特征验证更安全，这其实是错误的，从证明用户身份准确性上来讲，一定是知识因素是最准确可靠的。典型的，双胞胎可以通过 Face ID 的验证，造成非授权的访问。</p><h3>Passkeys 的适用范围</h3><p>一般来讲，Passkeys 最适用的地方是登录和注册。如果原先你的登录页面就允许 Autofill 框架帮用户填充/记住密码，那么切换到 Passkeys 会更加安全。</p><p>在其他场景如支付密码等也可以考虑用，但考虑到目前 Passkeys 的很多 UI 提示都显示的是“登录”字样，用户理解起来会有些许成本。此外 Passkeys 和支付密码并不是完全等价的，在替换之前要考虑清楚。</p><h3>Passkeys 能取代支付密码吗？</h3><p>如果你的密码是一个类似支付密码的概念，即支付 PIN，这种 PIN 一般不会被保存到 iCloud 或者 Google Password Manager 里。</p><p>当你希望用 Passkey 取代支付 PIN，那你可能需要明确一些概念，因为我认为 Passkeys 并不能取代支付 PIN。</p><h4>Passkeys 在验证什么</h4><p>因为 Passkeys 会被 iCloud、Gmail 这类平台账号同步，所以 Passkeys 本质上是属于平台账号拥有者的。</p><p>在实际使用 Passkeys 时，你会发现，其实 Authenticator 只会验证机主身份。看起来似乎有点矛盾，Passkey 明明是平台账号所有人的资产，为什么验证的是机主身份。</p><p>其实这并不矛盾，当平台账号的拥有者在这台手机上登录了平台账号，并开启同步时，可以认为是平台账号拥有者信任了设备，允许设备使用自己平台账号中的密码和 Passkey。而设备中的 Authenticator 则只信任设备的拥有者。</p><p>所以之后每次 Authenticator 需要使用 Passkey 时，只需验证机主身份。验证机主身份比验证平台账号所有人的身份要简单的多。</p><p>如果之后机主的生物特征发生了变化，比如录入了新指纹，Authenticator 也还是允许机主继续使用 Passkey，因为只有机主才能改变设备中的录入的生物特征。</p><p>所以 Passkeys 的信任链是：</p><p>平台账号拥有者 ==信任==&gt; 设备 ==信任==&gt; 设备拥有者。</p><p>虽然 Passkeys 验证的是机主，但其中是有信任链存在的，所以才只需要验证机主。但风险就在于，如果机主将设备转移给了另一个人，又没有登出平台账号，另一个人将可以使用这台设备上的 Passkey。</p><p>之前我说 Passkeys 构成双因素认证，但它的用户验证这部分，验证的是机主，而很多时候，我们希望验证的是原先获得 Passkey 的那个机主，信任链的存在，导致这两个机主在 Passkeys 方案中并不一定等价。</p><p>总而言之，验证 Passkey，验证的是拥有 Passkey 的人，即某个平台账号的拥有者，但这个平台账号拥有者由可以通过在设备上登录账号，来对某个设备的机主做授权，允许机主使用他的 Passkey。</p><h4>支付 PIN 在验证什么</h4><p>支付 PIN 验证的是知道这个 PIN 的人。谁能说出正确的 PIN，谁就是我认可的人。显然只有设置 PIN 的人才知道 PIN 是什么。在支付环节，支付系统其实只信任拥有账号，且知道支付 PIN 的人。</p><p>所以支付 PIN 的安全级别是比 Passkey 高的。因为 Passkey 相当于你将支付 PIN 放在一个房间里，谁拥有房间的钥匙，谁就能发起支付。而支付 PIN 是将 PIN 放在你脑子里，除了你没人能发起支付。</p><p>目前很多银行 App 都支持生物特征验证登录，你会发现它们都有一个很明显的特征，一旦你的生物特征变化，比如换新手机、录入了新指纹，银行 App 都会立即停用你的生物特征验证登录功能，需要你重新启用。这和 Passkeys 的信任链是有显著区别的。</p><p>因为银行和用户的信任是一对一的直接信任关系，银行需要确保信任的是一个非常具体的人，即在当时通过了身份验证，且拥有那一瞬间生物特征的机主，一旦其生物特征发生变化，就有可能换机主了，银行就不能再信任这个机主了。</p><p>如果用 Passkey 来取代支付 PIN，则会在支付环节引入 Passkeys 的信任链，显然当金融机构信任用户 A 时，是不能允许对 A 的信任链的延伸的。即银行通过验证 Passkey，无法确保当前是 A 机主在操作，而不是保存 Passkey 设备的新机主。</p><p>目前世界上有很多银行在探索 Passkeys 的使用，但在支付密码验证这一部分，我认为在当下，Passkeys 还不太适合使用。</p><h3>银行 App 的生物特征验证登录/支付的原理</h3><p>虽然我认为 Passkeys 不太适合在银行 App 中使用，但基于 Passkeys 原理的生物特征验证方案，安全性是比较高的。这个正是当前银行 App 中普遍使用的方案。</p><p>我把它称之为基于非对称加密的生物验证方案。</p><p>其原理与 Passkeys 方案是类似的，都是客户端生成密钥对，私钥保密，公钥传递给服务器用于验证。区别在于 App 会直接通过 KeyStore 这类 API 来生成密钥对，指定用户必须验证后才能使用私钥，并且指定当生物特征变化时，将密钥对失效。在 Android 上对应的 API 是 setInvalidatedByBiometricEnrollment。</p><p>因为使用了 KeyStore 这类 API，密钥的生成和使用都是 KeyStore 中进行的，可能是在安全硬件模块里，App 从开始到结束都无法接触到私钥，只能获取到公钥。App 无法导出这个私钥，所以不存在密钥同步的问题，想同步也同步不了。</p><p>相比 Passkeys ，这个方案的安全性显然更高，因为它只信任生成密钥对那瞬间录入了生物特征的机主。</p><p>此外，签名过程，也是 KeyStore 来做，App 只能把要签名的数据交给 KeyStore，KeyStore 用私钥签名后还给 App，且 KeyStore 还会按照生成密钥对时的参数，在验证用户之后才能进行签名，确保非机主无法代替机主完成数字签名流程。</p><h3>基于非对称加密的生物特征验证在 Android 上的可用性</h3><p>出于和 Passkeys 同样的考虑，也建议只在 Android 9 及以上的设备中实施这个方案，以减少兼容性问题。</p><p>但还需要额外考虑一点，Android CDD（Compatibility Definition Document，兼容性定义文档）中为生物特征验证器定义了不同的生物识别强度，目前有最强为 BIOMETRIC_STRONG (Class 3)，只有 BIOMETRIC_STRONG 强度的验证器才能与 KeyStore 一起使用。</p><p>也就是说即便这台设备上有生物特征验证器，也需要检验强度后才能启用。</p><p>在 Android 的<a href="https://security.googleblog.com/2020/09/lockscreen-and-authentication.html">分层验证模型</a>中，主要验证方式依旧是基于知识的验证，即 PIN 、图案或密码。生物识别技术属于第二层，是更方便但更不安全的验证方式。第三层是用户所拥有的，基于环境的因素。验证用户所拥有的东西，最大的问题就在于，它无法很好的代表用户的身份。</p><p>所以在 Android 系统看来，使用锁屏密码验证用户身份，是比生物特征验证更安全的，这也是为什么 BiometricPrompt 中会集成锁屏密码验证。</p><p>iOS 其实也是类似的分层设计，认为密码才是最安全的，生物识别则提供更多便利性，在关键步骤依旧要验证密码。只不过从生物验证器的安全性上，iOS 的安全性比几乎所有 Android 设备都要高。</p><p>使用生物特征，其实本身已经在安全性上做了妥协，增强了便利性。所以才需要限制密钥在生物特征变化后立即失效，尽量在增加便利的同时，增加证明用户身份的准确性。</p><p>参考链接<br><a href="https://developers.google.com/identity/passkeys">https://developers.google.com/identity/passkeys</a><br><a href="https://developer.android.com/identity/sign-in/credential-manager">https://developer.android.com/identity/sign-in/credential-manager</a><br><a href="https://www.w3.org/TR/2021/REC-webauthn-2-20210408/">https://www.w3.org/TR/2021/REC-webauthn-2-20210408/</a><br><a href="https://fidoalliance.org/faqs/#PasskeysFAQs">https://fidoalliance.org/faqs/#PasskeysFAQs</a><br><a href="https://source.android.com/docs/security/features/biometric">https://source.android.com/docs/security/features/biometric</a><br><a href="https://security.googleblog.com/2020/09/lockscreen-and-authentication.html">https://security.googleblog.com/2020/09/lockscreen-and-authentication.html</a></p><p>English version:</p><p><a href="https://medium.com/@wanxiao1994/introduction-and-reflections-on-passkeys-and-public-key-based-biometric-authentication-solutions-b3120536ea8c">Introduction and Reflections on Passkeys and Public Key-Based Biometric Authentication Solutions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c07287d28d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experience in Adapting iOS Password AutoFill]]></title>
            <link>https://medium.com/@wanxiao1994/experience-in-adapting-ios-password-autofill-8ba8f5c544de?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba8f5c544de</guid>
            <category><![CDATA[uitextfield]]></category>
            <category><![CDATA[autofill]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[password-management]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 09:52:48 GMT</pubDate>
            <atom:updated>2025-01-14T02:26:15.369Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, my work shifted from Android development to iOS development. The first task was to adapt our app for Password AutoFill, allowing users to store their account passwords in iOS, and thus avoid constantly forgetting them.</p><p>To my surprise, using Password AutoFill comes with many limitations and bugs, and requires handling some unexpected scenarios. If not correctly adapted, there’s a high chance that the user’s account password will not be saved, or an incorrect account password will be saved.</p><p>Note that the term “username” used in this article refers to the username used for logging in, not the user’s nickname or real name. This will not be reiterated in the following text.</p><h3>Enabling Password AutoFill in iOS</h3><p>Taking iOS 17 as an example, to enable Password AutoFill, one needs to go to Settings — Passwords — Password Options and turn on AutoFill Passwords and Passkeys.</p><p>At the same time, iOS also features a function to automatically generate and fill in strong passwords. This requires going to Settings — top iCloud Account — iCloud, and ensuring that Passwords and Keychain are turned on.</p><p>With these settings, iOS gains the ability to automatically generate strong passwords and autofill account passwords.</p><h3>Adapting Password AutoFill in the App</h3><p>Apps must have an associated domain, which can be referenced in Apple’s documentation <a href="https://developer.apple.com/documentation/xcode/supporting-associated-domains?language=objc">Supporting associated domains</a>.</p><p>According to Apple’s documentation <a href="https://developer.apple.com/documentation/security/password_autofill/enabling_password_autofill_on_a_text_input_view?language=objc">Enabling Password AutoFill on a text input view</a>, it’s sufficient to set the correct UITextContentType for the corresponding UITextField to make Password AutoFill work correctly. Possible UITextContentType values include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*E8e2uc0wyzAVOCo-tr4Cqw.png" /><figcaption>UITextContentType value</figcaption></figure><p>When UITextContentType == UITextContentTypeNewPassword, iOS will automatically generate a suggested strong password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*ywc70Mclf4pVxAnxJotMZw.png" /><figcaption>Strong password</figcaption></figure><p>If you want iOS to generate a password that meets the requirements of your app, you can use passwordRules to inform iOS of the rules for generating the password. For example, the following rule requires a minimum of 10 characters and a maximum of 14 characters for the password, and mandates the inclusion of lowercase, uppercase, and numerical characters:</p><pre>minlength: 10; maxlength: 14; required: lower; required: upper; required: digit;</pre><p>Rules can be generated or verified through Apple’s website: <a href="https://developer.apple.com/password-rules/">https://developer.apple.com/password-rules/</a></p><p>Note that iOS only suggests a strong password when the isSecureTextEntry property of the text field is set to YES.</p><p>The information introduced above is either from official iOS sources or can be found on the internet. However, in reality, during the adaptation process, combined with business code, there are various issues that need to be addressed.</p><h3>General Working Mechanism of Password AutoFill</h3><p>Based on Apple’s documentation and my own testing results, iOS Password AutoFill uses a heuristic method to determine when a user is logging in, creating a password, which text field is for the username, which is for the password, and which is for the new password. Password AutoFill will perform relevant operations, including saving/updating passwords, when a UIViewController with the pertinent text fields closes. In some cases, it may also prompt a UIActionSheet to ask the user whether they want to save/update the password.</p><p>Passwords saved by Password AutoFill in native iOS apps generally contain three fields: Username, Password, and Associated Domains. These can be viewed in Settings — Passwords.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*JHh5cPuUJAi3XPVSs-ui3w.png" /></figure><p>Associated domains can be referenced in Apple’s documentation <a href="https://developer.apple.com/documentation/xcode/supporting-associated-domains?language=objc">Supporting associated domains</a>. This element is automatically determined by the system based on the app’s associated domain, and this domain must pass verification; otherwise, Password AutoFill will not function. Developers cannot directly specify this through the API, nor can they misuse the associated domains of other apps. When a user browses a page under this domain or subdomain in Safari and needs to enter a password, Safari will automatically prompt to fill in the password saved from the app.</p><p>Since it operates on a heuristic basis, there are inevitably occasions of incorrect judgments. Therefore, iOS also allows developers to set the UITextContentType property of UITextField to explicitly specify the specific role of the text field.</p><p>Unfortunately, based on my testing, even up to iOS 17, Password AutoFill merely considers the UITextContentType set by the developer and mostly still prioritizes heuristic methods. This leads to situations where setting the UITextContentType might be ineffective, and sometimes it’s even necessary to set an incorrect UITextContentType to make Password AutoFill function correctly.</p><h3>Scenarios Where Users Need to Save/Update Passwords</h3><p>Users typically need to save/update passwords in the following scenarios:</p><ul><li>Setting a password for the first time after registering an account</li><li>Logging in on a new device for the first time</li><li>Changing the password</li><li>Changing the login account</li></ul><p>Since Password AutoFill only saves the username and password from an app and does not have a concept like userId, when a user changes their login account and logs in again, Password AutoFill will treat it as a different account and remember the password accordingly.</p><h3>Password AutoFill Does Not Know When User Login/Registration Succeeds</h3><p>Unlike Google’s <a href="https://developers.google.com/identity/one-tap/android/save-passwords">One Tap for Android</a>, the app does not need to directly inform iOS of the username and password. Password AutoFill merely operates in a heuristic way; it does not know whether the user’s login/registration has been successful or not. This information is only known to the app, and Apple has not provided any interface for apps to inform the system about it.</p><p>Password AutoFill only prompts the user to save/update passwords when a UIViewController with username and password input fields is closed. For instance, if a user enters a username and password on the login page but exits without logging in, the system will still prompt to save the password. If the user entered an incorrect password, it could be saved mistakenly.</p><p>Therefore, an important aspect of adapting Password AutoFill is to ensure that when a user exits the username and password interface without going through the actual password verification process, the contents of the UITextField should be cleared to prevent Password AutoFill from prompting the user to save.</p><h3>Invisible Username UITextField</h3><p>Many modern apps’ login processes often start by having the user input a username, after which, if the backend identifies the user as existing, a page with only a password input field is opened.</p><p>As previously mentioned, Password AutoFill operates heuristically. However, even in iOS 17, it only functions correctly when both a username input field and a password input field are present in the UIViewController. If your page only has a password input field, Password AutoFill won’t work properly.</p><p>The solution is to add a non-interactive UITextField (userInteractionEnabled = NO) right above the password input field, and fill it with the user’s username, like the one entered by the user on the previous page. Adding an input field to display the username on a page originally lacking one would change the page design. To avoid altering the design, this non-interactive UITextField can be made invisible. Note that you should not use the hidden property to hide the UITextField, as Password AutoFill does not recognize hidden UITextFields.</p><pre>UITextField *tf = UITextField.new;<br>tf.text = {username for login};<br>tf.textContentType = UITextContentTypeUsername;<br>tf.textColor = {same color as your background};<br>tf.userInteractionEnabled = NO;</pre><p>However, we can make the UITextField invisible to the user but visible to the system. The implementation is quite straightforward: set the UITextField’s text color to match the background color.</p><p>In terms of UI layout, the UITextField holding the username should be placed directly above the password UITextField. If it’s a password change page, it should be right above the field for the new password.</p><h3>Avoiding User Nicknames Being Saved as Usernames</h3><p>In some apps’ registration processes, the flow might start with OTP verification of the phone number, followed by allowing the user to set a nickname and password. The UI layout might look like this:</p><p>User Nickname Input Field<br>User Password Input Field</p><p>In this scenario, Password AutoFill will mistakenly save the nickname field above the password field as the username.</p><p>Therefore, you need to place an invisible username UITextField above the password field and fill it with the user’s actual username to ensure Password AutoFill saves the correct username.</p><p>This means your UI layout should ultimately be arranged like this:</p><p>User Nickname Input Field<br>Username Input Field (invisible and non-editable)<br>User Password Input Field</p><p>Note that the first UITextField above the password input field must be your username input field. There should be no other UITextFields between them, as Password AutoFill always considers the first input field above the password field as the username input field, even if you have not specified a UITextContentType.</p><h3>Preventing Modifications to the Invisible Username UITextField</h3><p>The invisible username UITextField needs to be filled with the correct username to function properly. You also need to ensure that the UITextField where you store the username is not modified.</p><p>Although users can’t modify it, the system keyboard can. iOS’s keyboard sometimes prompts users to autofill usernames. If a user selects the system-provided option, the system will directly modify the username UITextField, leading to an incorrect username being saved. We need to revert it back to the original. The simplest way is to listen for text change events and revert the text back to the desired username if it doesn’t match what we expect:</p><pre>// UITextField *tf = UITextField.new;<br>// self.usernameForAutoFill = {username for login}<br>[tf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];<br><br>- (void)textFieldDidChange:(UITextField *)textField {<br>    if (textField == self.usernameTFForAutoFill) {<br>        if (![textField.text isEqualToString:self.usernameForAutoFill]) {<br>            textField.text = self.usernameForAutoFill;<br>        }<br>    }<br>}</pre><h3>Potential Issues When isSecureTextEntry is Set to NO</h3><p>Many modern apps now have a ‘show password’ button in the password input field. When clicked, the password is displayed in plaintext:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*HT7xwE2aucc7pXSQ94PlDg.png" /><figcaption>Password Input Field with a Show Password Button</figcaption></figure><p>This is often achieved by modifying the isSecureTextEntry property of a UITextField.</p><pre>- (void)onTap:(UIButton *)sender {<br>    self.passwordTextField.secureTextEntry = !self.passwordTextField.isSecureTextEntry;<br>}</pre><p>However, this feature may lead to unexpected behavior with iOS Password AutoFill. If you observe closely, you’ll notice that many password input fields within the iOS system do not support plaintext password display. iOS Password AutoFill determines whether a UITextField is a password field not only based on UITextContentType but also by checking the secureTextEntry property. It&#39;s only when Password AutoFill recognizes your password text field as an approved password field that it functions correctly.</p><p>Since I have only tested Password AutoFill on iOS 16 and iOS 17, I can provide specific behavior observed on these versions as follows:</p><p><strong>iOS 16<br></strong>If the secureEntryText property of a UITextField is set to NO when the UIViewController is closed, then Password AutoFill does not consider it as a password field.</p><p><strong>iOS 17<br></strong>If a UITextField has secureEntryText set to YES when the user interacts with it, Password AutoFill will recognize it as a password field. Even if its secureEntryText is later set to NO, Password AutoFill will still remember it as a password field.</p><p>However, in the case of creating a new password with UITextContentTypeNewPassword, at least one of the new password text fields should have secureEntryText set to YES when the UIViewController is closed for Password AutoFill to prompt saving the password.</p><p>Therefore, it’s advisable to change the “show password” button behavior to temporarily display plaintext while it’s pressed and revert to displaying ciphertext when released. This approach reduces the likelihood of issues.</p><p>It’s also a good practice to proactively set secureTextEntry to YES for all password fields before making a request to the server.</p><h3>Issue of Repeated Strong Password Suggestions in iOS 16</h3><p>UITextContentTypeNewPassword is used for UITextField related to new passwords. In this scenario, iOS generates suggested strong passwords when conditions are met, but users can also choose to set their own passwords by clicking ‘Choose My Own Password.’</p><p>On pages where users typically set passwords, they are often required to enter the new password twice. However, there is a strange bug in iOS 16. When a user clicks the first new password input field, selects ‘Choose My Own Password,’ enters a password, and then clicks the second new password input field, iOS 16 suggests a strong password again, resulting in a poor user experience.</p><p>There is a workaround to bypass this bug, which is to set the UITextContentType of the second new password input field to UITextContentTypePassword.</p><p>In iOS 17, your text fields should be configured like this:</p><p>UITextField (UITextContentTypeUsername)<br>UITextField (UITextContentTypeNewPassword)<br>UITextField (UITextContentTypeNewPassword)</p><p>And on iOS 16, it needs to be changed to:</p><p>UITextField (UITextContentTypeUsername)<br>UITextField (UITextContentTypeNewPassword)<br>UITextField (UITextContentTypePassword)</p><p>The heuristic working method of Password AutoFill correctly recognizes the second UITextField as a new password input field as well.</p><h3>Issue with Password AutoFill Not Saving New Passwords</h3><p>iOS Password AutoFill has another frustrating issue. If the last UITextField edited by the user is not the one associated with UITextContentTypeNewPassword, Password AutoFill will not save the new password.</p><p>Therefore, on pages such as registration, password modification, or password reset, just before sending a request to the server, you need to check if the last UITextField edited by the user is not associated with UITextContentTypeNewPassword. If it’s not, you should proactively make it becomeFirstResponder, let the user to click the button again to trigger the request.</p><p>You can achieve this by using the textFieldDidBeginEditing method of UITextFieldDelegate to keep track of the last UITextField edited. If it’s not associated with UITextContentTypeNewPassword, make it becomeFirstResponder.</p><pre>[newPasswordTextField becomeFirstResponder];</pre><p>Please be cautious not to immediately call resignFirstResponder at this point in an attempt to dismiss the raised keyboard. Otherwise, iOS will generate a new strong password.</p><h3>My Perspective on iOS Password AutoFill</h3><p>Initially, I hoped that users could conveniently remember their passwords through Password AutoFill. However, during the actual development process and the series of issues I encountered, I found Password AutoFill to be very unreliable, and in severe cases, it could lead to problems. Therefore, after completing support for Password AutoFill, I shifted my goal to remembering users’ passwords within the app, storing passwords in the user’s Keychain for a better user experience. This approach also ensures the security of password storage, with iOS providing protection.</p><p>中文版：</p><p><a href="https://medium.com/@wanxiao1994/ios-password-autofill%E9%80%82%E9%85%8D%E7%BB%8F%E9%AA%8C-889f3bd178d5">iOS Password AutoFill适配经验</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba8f5c544de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Password AutoFill适配经验]]></title>
            <link>https://medium.com/@wanxiao1994/ios-password-autofill%E9%80%82%E9%85%8D%E7%BB%8F%E9%AA%8C-889f3bd178d5?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/889f3bd178d5</guid>
            <category><![CDATA[autofill]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[password-management]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[uitextfield]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 09:03:26 GMT</pubDate>
            <atom:updated>2024-01-30T09:53:25.055Z</atom:updated>
            <content:encoded><![CDATA[<p>最近我的工作从 Android 开发转为 iOS 开发。第一个需求就是为我们的 app 适配 Password AutoFill，让用户可以将账号密码记在 iOS 里，避免总是忘记密码。</p><p>出乎我意料的是，Password AutoFill 的使用有非常多的限制和 bug，且需要处理一些意想不到的情况。如果没有正确适配，极有可能导致用户的账号密码不被保存或者保存一个错误的账号密码。</p><p>注意本文中的“用户名”，指的是用户登录用的用户名，而非用户昵称或真实名字，下文不再说明。</p><h3>在 iOS 中启用 Password AutoFill</h3><p>以 iOS 17 为例，Password AutoFill 需要在 Settings — Passwords — Password Options 中，打开 AutoFill Passwords and Passkeys。</p><p>与此同时，iOS 中还有一个自动生成并填充强密码的功能，需要在 Settings — 顶部 iCloud Account — iCloud中，确保 Passwords and Keychain 处于打开的状态。</p><p>这样 iOS 就有了自动生成强密码和自动填充账户密码的能力。</p><h3>App 中适配 Password AutoFill</h3><p>App 必须有关联域名，可以参考 Apple 的文档 <a href="https://developer.apple.com/documentation/xcode/supporting-associated-domains?language=objc">Supporting associated domains</a>。</p><p>按照 Apple 的文档 <a href="https://developer.apple.com/documentation/security/password_autofill/enabling_password_autofill_on_a_text_input_view?language=objc">Enabling Password AutoFill on a text input view</a> 中所描述的，只需要给对应的 UITextField 设置好正确的 UITextContentType 即可让 Password AutoFill 正确工作。可能的 UITextContentType 如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*E8e2uc0wyzAVOCo-tr4Cqw.png" /><figcaption>UITextContentType value</figcaption></figure><p>当 UITextContentType == UITextContentTypeNewPassword 时，iOS 会自动生成建议的强密码：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*ywc70Mclf4pVxAnxJotMZw.png" /><figcaption>Strong password</figcaption></figure><p>如果你希望 iOS 可以生成满足你的 App 要求的密码，可以使用 passwordRules 来告知 iOS 生成密码的规则。例如下面的规则，是要求密码最小10个字符，最大14个字符，要求必须有小写、大写及数字：</p><pre>minlength: 10; maxlength: 14; required: lower; required: upper; required: digit;</pre><p>规则可以通过 Apple 的网站生成或验证：<a href="https://developer.apple.com/password-rules/">https://developer.apple.com/password-rules/</a></p><p>注意 iOS 只有在文本框的 isSecureTextEntry 属性为 YES 时，才会建议强密码。</p><p>上面介绍的都是 iOS 官方或者目前网络上可以查到的信息，但实际上是配过程中，结合业务代码，还有各种问题需要处理。</p><h3>Password AutoFill 大概的工作方式</h3><p>根据 Apple 的文档，以及我实际测试的结果，iOS Password AutoFill 采用启发式的方法判断什么时候用户是在登录，什么时候用户是在创建密码，哪个文本框是用户名，哪个文本框是密码，哪个文本框是新密码。Password AutoFill 将会在具有相关文本框的 UIViewController 关闭时，执行相应的操作，包括保存/更新密码，某些情况下还会弹出 UIActionSheet 询问用户是否需要保存/更新密码。</p><p>Password AutoFill 在 iOS 原生 App 运行的时候保存的密码，一般具有三个字段：用户名（Username），密码（Password），关联域名（Associated domains）。可以在 Settings — Passwords 中查看。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*JHh5cPuUJAi3XPVSs-ui3w.png" /></figure><p>关联域名（Associated domains）可以参考 Apple 的文档 <a href="https://developer.apple.com/documentation/xcode/supporting-associated-domains?language=objc">Supporting associated domains</a>。这一项是系统自动根据 App 的关联域名确定的，且关联域名必须能通过校验，否则 Password AutoFill 不会工作。开发者无法指定，更无法冒用其他 App 的关联域名。当用户在 Safari 中浏览这个域名或子域名的页面，需要输入密码时，Safari 会自动提示填充从 App 中保存的密码。</p><p>由于是启发式的工作方式，难免有判断错误的时候，因此 iOS 还允许开发者设置 UITextField 的 UITextContentType 属性，显式指定文本框的具体作用。</p><p>但遗憾的是，根据我的测试，即便是到了 iOS 17，Password AutoFill 也仅仅是参考开发者设置的 UITextContentType，大部分情况下还是优先使用启发式的方法工作，这就导致某些情况下，即便你设置了 UITextContentType 也没用，甚至有时还需要设置错误的 UITextContentType 来让 Password AutoFill 正常工作。</p><h3>用户需要保存/更新密码的场景</h3><p>用户一般在如下场景需要保存/更新密码。</p><ul><li>注册账号后首次设置密码</li><li>在新设备上首次登录</li><li>更改密码</li><li>更改登录账号</li></ul><p>由于 Password AutoFill 仅从一个 App 中保存用户名和密码，并没有 userId 这样的概念，所以当用户更改登录账号后重新登录时，Password AutoFill 会将其视为另一个账号密码记住。</p><h3>Password AutoFill 不知道用户登录/注册成功了</h3><p>与 Google 的 <a href="https://developers.google.com/identity/one-tap/android/save-passwords">One Tap for Android</a> 不同，App 并不需要将用户名和密码直接告知 iOS。Password AutoFill 只是在以启发式的方式工作，它并不知道用户登录/注册是否成功了，这个信息只有 App 才知道，而且 Apple 也并没有提供任何接口给 App 来告知系统。</p><p>Password AutoFill 仅在显示有用户名密码的输入框的 UIViewController 关闭时，提示用户保存/更新密码。假如用户在登录页面输入了用户名和密码，但又没有登录，直接退出登录页面，此时系统也会提醒保存密码，如果用户输入了错误的密码，就可能会被保存下来。</p><p>因此在适配 Password AutoFill 时，很重要的一点就是当用户没有真正的执行密码验证流程，直接退出用户名及密码界面时，需要清空 UITextField 里的内容，避免 Password AutoFill 提示用户保存。</p><h3>隐形的用户名 UITextField</h3><p>很多现代 App 的登录流程，往往都是先输入用户名，后台判断为已存在用户后再打开一个仅有密码输入框的页面。</p><p>刚才提到 Password AutoFill 是以启发式的方式工作，但在 iOS 17 上，它仍旧只有在 UIViewController 中同时存在用户名输入框和密码输入框时，才能正常工作，如果你的页面上仅有一个密码输入框，Password AutoFill 并不能正常工作。</p><p>解决方案是在密码输入框的正上方，添加一个用户不可交互（userInteractionEnabled = NO）的 UITextField，并在其中填充用户的用户名，比如前一个页面用户输入的用户名。在一个原本没有用户名输入框的页面，添加一个输入框展示用户名，会改变页面的设计，为了避免改变页面的设计，我们可以将这个不可交互的 UITextField 隐藏起来，注意这里不能用 hidden 属性来隐藏 UITextField，Password AutoFill 并不识别被隐藏的 UITextField。</p><pre>UITextField *tf = UITextField.new;<br>tf.text = {username for login};<br>tf.textContentType = UITextContentTypeUsername;<br>tf.textColor = {same color as your background};<br>tf.userInteractionEnabled = NO;</pre><p>但我们可以让 UITextField 对用户是隐藏的，但对系统是可见的，实现也很简单，那就是将 UITextField 的文本颜色设置为和背景一致。</p><p>注意 UI 布局上，将存放用户名的 UITextField 放在密码 UITextField 的正上方，如果是更改密码页面，则应该是新密码的正上方。</p><h3>避免用户昵称被保存为用户名</h3><p>某些 App 的注册流程，可能是先 OTP 验证手机号，再让用户设置昵称和密码，UI 界面可能是这样排版的：</p><p>用户昵称输入框<br>用户密码输入框</p><p>此时 Password AutoFill 会将密码框上方的昵称文本框视为用户名保存，这会导致错误。</p><p>因此你需要在密码框上方放一个隐形的用户名 UITextField，并填充用户的用户名，这样 Password AutoFill 才能保存正确的用户名。</p><p>也就是说，最终你的 UI 界面应该是这样排版的：</p><p>用户昵称输入框<br>用户名输入框（隐形且不可编辑）<br>用户密码输入框</p><p>注意密码输入框上方的第一个 UITextField 必须是你的用户名输入框，他们中间不能有任何其他 UITextField，因为 Password AutoFill 总是将密码框上方出现的第一个输入框作为用户名输入框，就算你没有指定 UITextContentType 也一样。</p><h3>避免用户名 UITextField 被修改</h3><p>隐形的用户名 UITextField 中需要填充正确的用户名，才能正常工作。你还需要避免你存放用户名的 UITextField 被修改。</p><p>虽然用户无法修改，但系统输入法却有能力修改，iOS 的输入法有时会提示用户自动填充用户名，如果用户点击了系统提供的选项，则系统会直接修改用户名 UITextField，导致我们保存一个错误的用户名，我们需要将它改回来，最简单的就是监听文本改变的事件，一旦发现和我们想要的不符，就改回来：</p><pre>// UITextField *tf = UITextField.new;<br>// self.usernameForAutoFill = {username for login}<br>[tf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];<br><br>- (void)textFieldDidChange:(UITextField *)textField {<br>    if (textField == self.usernameTFForAutoFill) {<br>        if (![textField.text isEqualToString:self.usernameForAutoFill]) {<br>            textField.text = self.usernameForAutoFill;<br>        }<br>    }<br>}</pre><h3>isSecureTextEntry 为 NO 时可能导致的问题</h3><p>当今许多 App 的密码输入框都有明文展示密码的按钮，在点击之后密码会以明文展示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*HT7xwE2aucc7pXSQ94PlDg.png" /><figcaption>带有展示密码按钮的密码输入框</figcaption></figure><p>这往往是通过改变 UITextField 的 isSecureTextEntry 属性实现的：</p><pre>- (void)onTap:(UIButton *)sender {<br>    self.passwordTextField.secureTextEntry = !self.passwordTextField.isSecureTextEntry;<br>}</pre><p>但这个功能可能会导致 iOS Password AutoFill 不按你预期的方式工作。如果你仔细观察的话，你会发现 iOS 系统内很多密码输入框，是不支持明文展示密码的。iOS Password AutoFill 会通过 secureTextEntry 来判断一个 UITextField 是否是密码框，而不仅仅是 UITextContentType。只有当 Password AutoFill 认为你的密码文本框是它所认可的密码框时，才能正常工作。</p><p>由于我只在 iOS 16 和 iOS 17 上测试过 Password AutoFill，我只知道 iOS 16 和 iOS 17 上的表现，具体如下：</p><p><strong>iOS 16<br></strong>如果 UITextField 在 UIViewController 关闭时，secureEntryText为 NO，则 Password AutoFill 不认为它是密码框。</p><p><strong>iOS 17<br></strong>如果 UITextField 在用户点击它时 secureEntryText 为 YES，Password AutoFill 就会认为它是密码框，就算后续它的 secureEntryText 不为 YES，Password AutoFill 也会记得它。</p><p>但如果是 UITextContentTypeNewPassword 创建新密码的情况，则至少要有一个新密码文本框在 UIViewController 关闭时 secureEntryText 为 YES，Password AutoFill 才会提示保存密码。</p><p>所以我建议最好将展示密码按钮改为按住时展示明文，松手时恢复展示密文的形式，这样不太容易出问题。</p><p>最好在向服务器发起请求前，将密码框的 secureTextEntry 全部主动改为 YES。</p><h3>iOS 16 重复建议强密码问题</h3><p>UITextContentTypeNewPassword 用于新密码的 UITextField，此时 iOS 在满足条件时会自动生成建议的强密码，但用户也可以通过点击“Choose My Own Password”来自己设置密码。</p><p>一般设置密码的页面，都会要求用户重复输入一次新密码。在 iOS 16 上，有奇怪的 bug，当用户点击第一个新密码输入框，选择“Choose My Own Password”，输入了密码之后，点击第二个新密码输入框时，iOS 16 会再次建议强密码，用户体验非常差。</p><p>有一种办法可以绕过这个 bug，那就是将第二个新密码输入框的 UITextContentType 设置为 UITextContentTypePassword。</p><p>也就是说，在 iOS 17 上，你的文本框是这样的：</p><p>UITextField (UITextContentTypeUsername)<br>UITextField (UITextContentTypeNewPassword)<br>UITextField (UITextContentTypeNewPassword)</p><p>而在 iOS 16 上，需要改成：</p><p>UITextField (UITextContentTypeUsername)<br>UITextField (UITextContentTypeNewPassword)<br>UITextField (UITextContentTypePassword)</p><p>Password AutoFill 的启发式工作方式，会正确的将第二个 UITextField 也识别为新密码输入框。</p><h3>Password AutoFill 不保存新密码问题</h3><p>iOS Password AutoFill 还有一个非常恶心的问题，如果用户最后一个编辑的不是 UITextContentTypeNewPassword 对应的 UITextField，则 Password AutoFill 不会保存新密码。</p><p>因此你需要在注册、修改密码、重置密码这些页面上，在即将向服务器发起请求时，检查用户最后一次编辑的是不是 UITextContentTyp 为 eUITextContentTypeNewPassword 的 UITextField，如果不是，则需要主动将其 becomeFirstResponder，让用户再点击一次按钮触发请求。</p><p>可以通过 UITextFieldDelegate 中的 textFieldDidBeginEditing 来记录最后一次被编辑的 UITextField，如果不是 UITextContentTypeNewPassword 对应的 UITextField，则让 becomeFirstResponder。</p><pre>[newPasswordTextField becomeFirstResponder];</pre><p>注意此时千万不要立即调用 resignFirstResponder，来尝试将弹起的软键盘收回，否则 iOS 会生成一个新的强密码。</p><h3>我对于 iOS Password AutoFill 的看法</h3><p>原本我希望用户可以通过 Password AutoFill 方便的记住密码，但实际开发过程中遇到的一系列问题，让我觉得 Password AutoFill 非常不可靠，而且严重时还会导致问题。因此在完成对 Password AutoFill 的支持后，我将目标改为在 App 内记住用户的密码，将密码保存到用户的 Keychain 中，以带来更好的用户体验，同时在密码存储安全性上也能得到 iOS 的保护。</p><p>English version:</p><p><a href="https://medium.com/@wanxiao1994/experience-in-adapting-ios-password-autofill-8ba8f5c544de">Experience in Adapting iOS Password AutoFill</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=889f3bd178d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement a carousel style notification]]></title>
            <link>https://medium.com/@wanxiao1994/how-to-implement-a-carousel-style-notification-b95fb817d2ba?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b95fb817d2ba</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[fileprovider]]></category>
            <category><![CDATA[carousel]]></category>
            <category><![CDATA[custom-notification]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 07:30:57 GMT</pubDate>
            <atom:updated>2023-08-27T07:30:57.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*HQy0z51hLAGS8eMkOyLbhg.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-InROlayGjg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-InROlayGjg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-InROlayGjg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/667bd974cf1116e8a84032772a257b67/href">https://medium.com/media/667bd974cf1116e8a84032772a257b67/href</a></iframe><p>The video demonstration above showcases the carousel-style notification that I created. Its essence lies in being a custom notification, but to achieve this effect, a slight modification to the FileProvider is also necessary. Next, I will explain how to implement this functionality.</p><h3>How to Download Images</h3><p>I recommend using coroutines for concurrent image downloading, where individual image downloads can be handled using Picasso.</p><pre>val bitmap = Picasso.get().load(url).get()</pre><h3>Custom Notification</h3><p>Since Android does not provide this style of notification natively, we need to use custom notification to achieve it. Therefore, our code for sending the notification is as follows:</p><pre>// Later, I will explain how remoteViews are created.<br>val notification = NotificationCompat.Builder(requireContext(), CHANNEL_ID)<br>    .setSmallIcon(R.drawable.baseline_photo_library_24)<br>    .setContentTitle(&quot;ContentTitle&quot;)<br>    .setContentText(&quot;Expand to view carousel notification&quot;)<br>    .setCustomBigContentView(remoteViews)<br>    .build()<br>NotificationManagerCompat.from(requireContext()).apply {<br>    notify(generateId(), notification)<br>}</pre><h3>RemoteViews XML Layout</h3><p>Custom notification requires the use of RemoteViews. Although RemoteViews is also declared using XML, the layout is ultimately loaded by the system. As a result, the range of widgets that can be used within it is limited. For specific supported widgets, you can refer to the documentation below:</p><p><a href="https://developer.android.com/reference/android/widget/RemoteViews">RemoteViews | API reference | Android Developers</a></p><p>The ViewFlipper provided by Android allows us to achieve the carousel effect.</p><p>Next, let’s implement our RemoteViews XML layout, layout_remote_custom_carousel.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        style=&quot;@style/TextAppearance.Compat.Notification.Title&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        tools:text=&quot;Custom Title&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/desc&quot;<br>        style=&quot;@style/TextAppearance.Compat.Notification.Line2&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        tools:text=&quot;Custom Desc Custom Desc Custom Desc Custom Desc&quot; /&gt;<br><br>    &lt;ViewFlipper<br>        android:id=&quot;@+id/view_flipper&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center_vertical&quot;<br>        android:autoStart=&quot;true&quot;<br>        android:flipInterval=&quot;3000&quot;<br>        android:inAnimation=&quot;@anim/slide_in_right&quot;<br>        android:outAnimation=&quot;@anim/slide_out_left&quot; /&gt;<br>&lt;/LinearLayout&gt;</pre><p>slide_in_right and slide_out_left are the animations used when switching views in the ViewFlipper. Here, we will implement a simple translate animation:</p><p>slide_in_right.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;set xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;translate android:fromXDelta=&quot;100%p&quot; android:toXDelta=&quot;0&quot;<br>        android:duration=&quot;@android:integer/config_mediumAnimTime&quot;/&gt;<br>&lt;/set&gt;</pre><p>slide_out_left.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;set xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;translate android:fromXDelta=&quot;0&quot; android:toXDelta=&quot;-100%p&quot;<br>        android:duration=&quot;@android:integer/config_mediumAnimTime&quot;/&gt;<br>&lt;/set&gt;</pre><h3>Creating RemoteViews</h3><p>In the code provided earlier, there was no declaration of remoteViews. Here, we will create the remoteViews:</p><pre>val remoteViews = RemoteViews(<br>    requireContext().packageName,<br>    R.layout.layout_remote_custom_carousel<br>)<br><br>remoteViews.setTextViewText(R.id.title, &quot;Travel to Republic of Singapore&quot;)<br>remoteViews.setTextViewText(<br>    R.id.desc,<br>    &quot;Singapore is open to all travellers without quarantine or testing requirements&quot;<br>)</pre><p>Currently, we have only inflated the layout_remote_custom_carousel.xml and set text to the TextView within it. However, the ViewFlipper inside it doesn&#39;t have any content yet. Next, we will populate the ViewFlipper with content.</p><h3>Layout for Individual Element in ViewFlipper</h3><p>To add elements to the ViewFlipper, you can use the remoteViews.addView(R.id.view_flipper, childView) interface, where childView is also a RemoteViews.</p><p>Next, define the layout for an individual element, layout_remote_custom_carousel_item.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/root&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        style=&quot;@style/TextAppearance.Compat.Notification.Info&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:ellipsize=&quot;end&quot;<br>        android:maxLines=&quot;1&quot; /&gt;<br><br>    &lt;FrameLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;&gt;<br><br>        &lt;ImageView<br>            android:id=&quot;@+id/image_view&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:adjustViewBounds=&quot;true&quot;<br>            android:scaleType=&quot;centerCrop&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/desc&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_gravity=&quot;bottom&quot;<br>            android:background=&quot;@drawable/shadow_bottom_up&quot;<br>            android:padding=&quot;6dp&quot;<br>            android:paddingTop=&quot;10dp&quot;<br>            android:textColor=&quot;#ffffff&quot;<br>            android:textSize=&quot;12dp&quot; /&gt;<br>    &lt;/FrameLayout&gt;<br>&lt;/LinearLayout&gt;</pre><h3>Adding Carousel Elements to ViewFlipper</h3><p>Assuming I have a val bitmaps: List&lt;Bitmap&gt;? where the stored bitmaps are images for the carousel, and dataTriples is an array of Triples where each Triple.second stores the title of an individual carousel element, and Triple.third stores the description on the image of an individual carousel element. You can iterate through the bitmaps, construct RemoteViews, and then use remoteViews.addView to add them.</p><pre>val childViews = Array(bitmaps.size) {<br>    val remoteView = RemoteViews(<br>        requireContext().packageName,<br>        R.layout.layout_remote_custom_carousel_item<br>    )<br><br>    remoteView.setImageViewBitmap(R.id.image_view, bitmapUris[it])<br><br>    remoteView.setTextViewText(R.id.title, dataTriples[it].second)<br>    remoteView.setTextViewText(R.id.desc, dataTriples[it].third)<br><br>    val pendingIntent = ...<br><br>    remoteView.setOnClickPendingIntent(R.id.root, pendingIntent)<br><br>    remoteView<br>}<br><br>for (each in childViews) {<br>    remoteViews.addView(R.id.view_flipper, each)<br>}</pre><h3>Attempting to Run: Not Working</h3><p>If you followed the approach I mentioned above, depending on your system version, you might notice that the ViewFlipper in the notification doesn’t show any content. This is because, in order to display the carousel images, we passed multiple bitmaps to the system. Since a single bitmap consumes a large amount of memory, when passing multiple bitmaps, the system may easily perceive it as excessive data being passed. By observing the logcat, you may notice log messages similar to the following:</p><blockquote>NotificationService system_server W Removed too large RemoteViews (10093824 bytes) on pkg: com.example.shawtest tag: null id: 2</blockquote><p>Therefore, we cannot use RemoteViews.setImageViewBitmap, and instead, we should use RemoteViews.setImageViewUri to avoid directly passing bitmaps to the system.</p><h3>Save File and Pass Uri</h3><p>Because passing a file path directly can result in a FileUriExposedException from the system, after saving the bitmap to a file, we also need to convert the file into a Uri.</p><h4>The standard FileProvider might not work</h4><p>For example, after saving the bitmap to a file using the code below, attempting to retrieve the Uri using the standard FileProvider might not work:</p><pre>val bitmap = Picasso.get().load(url).get()<br>val file = File(dir, UUID.randomUUID().toString())<br>file.outputStream().use {<br>    bitmap.compress(Bitmap.CompressFormat.WEBP, 90, it)<br>}<br>bitmap.recycle()<br>FileProvider.getUriForFile(requireContext(), authority, file)</pre><p>Then set the path using the following code:</p><pre>remoteView.setImageViewUri(R.id.image_view, bitmapUris[it])</pre><p>You might encounter situations where, prior to Android 12 and on some Android 13 systems, the system lacks permission to access the Uri we’ve set:</p><blockquote>android.widget.RemoteViews$ActionException: java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri content://com.example.shawtest.fileprovider/internal_cache/d2c5d24e-f9c1–48c4–9d5d-56f55f3efe42 from pid=2558, uid=1000 requires the provider be exported, or grantUriPermission()</blockquote><p>If you attempt to set the ‘exported’ attribute of FileProvider to true, the app will crash as soon as it starts because FileProvider will check at runtime whether ‘exported’ is set to false. If it’s not set to false, an exception will be thrown:</p><pre>@Override<br>public void attachInfo(@NonNull Context context, @NonNull ProviderInfo info) {<br>    super.attachInfo(context, info);<br><br>    // Check our security attributes<br>    if (info.exported) {<br>        throw new SecurityException(&quot;Provider must not be exported&quot;);<br>    }<br>    ...<br>}</pre><h4>Modifying FileProvider to Allow exported to be true</h4><p>In this case, we can create a copy of FileProvider, remove the relevant validation code, and allow it to set exported to true. Let’s name this customized version ExportedFileProvider:</p><pre>@Override<br>public void attachInfo(@NonNull Context context, @NonNull ProviderInfo info) {<br>    super.attachInfo(context, info);<br><br>    // Check our security attributes<br>//        if (info.exported) {<br>//            throw new SecurityException(&quot;Provider must not be exported&quot;);<br>//        }<br>    ...<br>}</pre><p>Declare in Manifest, and note that I’m using a specific authorities:</p><pre>        &lt;provider<br>            android:name=&quot;.fileprovider.ExportedFileProvider&quot;<br>            android:authorities=&quot;${applicationId}.fileprovider.exported&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;meta-data<br>                android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot;<br>                android:resource=&quot;@xml/exported_filepaths&quot; /&gt;<br>        &lt;/provider&gt;<br><br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>Here, I’m choosing to store the files in the internal cache directory.</p><p>Due to the FileProvider with exported set to true, allowing third-party apps to access any exposed path, we can add a subdirectory named exported/ to avoid exposing the entire cache directory to other apps.</p><p>exported_filepaths.xml：</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;paths xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;cache-path name=&quot;internal_cache&quot; path=&quot;exported/&quot; /&gt;<br>&lt;/paths&gt;</pre><p>Modify the code for saving files, keeping in mind that we want to save them under a path that can be exposed by the ExportedFileProvider:</p><pre>val dir = File(requireContext().cacheDir, &quot;exported&quot;)<br>// Please ensure that the directory path &#39;dir&#39; exists.<br><br>val bitmap = Picasso.get().load(url).get()<br>val file = File(dir, UUID.randomUUID().toString())<br>file.outputStream().use {<br>    bitmap.compress(Bitmap.CompressFormat.WEBP, 90, it)<br>}<br>bitmap.recycle()<br>ExportedFileProvider.getUriForFile(requireContext(), authority, file)</pre><p>This way, any process, including system processes, can directly access the Uri we’ve passed.</p><p>Please note that no other files should be saved to this directory, as it can be accessed by any third-party app.</p><h3>Further Security Modifications for ExportedFileProvider</h3><p>FileProvider is designed with exported set to false, so much of its code assumes that third-party apps won’t directly access it. Since ExportedFileProvider has exported set to true, any app can access it, which means we need to make additional modifications in ExportedFileProvider to prevent malicious app exploitation.</p><p>Prohibit Deletion. Prevent other apps from attempting to delete files in the exposed directory:</p><pre>@Override<br>    public int delete(@NonNull Uri uri, @Nullable String selection,<br>                      @Nullable String[] selectionArgs) {<br>        // ContentProvider has already checked granted permissions<br>//        final File file = mStrategy.getFileForUri(uri);<br>//        return file.delete() ? 1 : 0;<br>        throw new UnsupportedOperationException(&quot;No external delete&quot;);<br>    }</pre><p>Prohibit opening files with modes other than read-only. Preventing other apps from attempting to modify or write files to the exposed directory:</p><pre>/**<br>     * Copied from ContentResolver.java<br>     */<br>    private static int modeToMode(String mode) {<br>        int modeBits;<br>        if (&quot;r&quot;.equals(mode)) {<br>            modeBits = ParcelFileDescriptor.MODE_READ_ONLY;<br>//        } else if (&quot;w&quot;.equals(mode) || &quot;wt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>//        } else if (&quot;wa&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_APPEND;<br>//        } else if (&quot;rw&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE;<br>//        } else if (&quot;rwt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid mode: &quot; + mode);<br>        }<br>        return modeBits;<br>    }</pre><h4>Is ExportedFileProvider Vulnerable to Arbitrary Path Traversal?</h4><p>Because FileProvider itself has path validation in its code, specifically in SimplePathStrategy#getFileForUri, and we restrict the ExportedFileProvider to only expose files within the ‘exported’ directory under the internal cache directory through exported_filepaths.xml, ExportedFileProvider should not have arbitrary path traversal vulnerabilities. However, please note that the ‘exported’ directory under the internal cache directory is completely exposed to third-party apps and should only be used for this specific type of file storage.</p><h3>Appendix: Complete ExportedFileProvider Code</h3><pre>public class ExportedFileProvider extends ContentProvider {<br>    private static final String[] COLUMNS = {<br>            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE };<br><br>    private static final String<br>            META_DATA_FILE_PROVIDER_PATHS = &quot;android.support.FILE_PROVIDER_PATHS&quot;;<br><br>    private static final String TAG_ROOT_PATH = &quot;root-path&quot;;<br>    private static final String TAG_FILES_PATH = &quot;files-path&quot;;<br>    private static final String TAG_CACHE_PATH = &quot;cache-path&quot;;<br>    private static final String TAG_EXTERNAL = &quot;external-path&quot;;<br>    private static final String TAG_EXTERNAL_FILES = &quot;external-files-path&quot;;<br>    private static final String TAG_EXTERNAL_CACHE = &quot;external-cache-path&quot;;<br>    private static final String TAG_EXTERNAL_MEDIA = &quot;external-media-path&quot;;<br><br>    private static final String ATTR_NAME = &quot;name&quot;;<br>    private static final String ATTR_PATH = &quot;path&quot;;<br><br>    private static final String DISPLAYNAME_FIELD = &quot;displayName&quot;;<br><br>    private static final File DEVICE_ROOT = new File(&quot;/&quot;);<br><br>    @GuardedBy(&quot;sCache&quot;)<br>    private static final HashMap&lt;String, PathStrategy&gt; sCache = new HashMap&lt;&gt;();<br><br>    private PathStrategy mStrategy;<br>    private int mResourceId;<br><br>    public ExportedFileProvider() {<br>        mResourceId = ResourcesCompat.ID_NULL;<br>    }<br><br>    protected ExportedFileProvider(@XmlRes int resourceId) {<br>        mResourceId = resourceId;<br>    }<br><br>    /**<br>     * The default FileProvider implementation does not need to be initialized. If you want to<br>     * override this method, you must provide your own subclass of FileProvider.<br>     */<br>    @Override<br>    public boolean onCreate() {<br>        return true;<br>    }<br><br>    /**<br>     * After the FileProvider is instantiated, this method is called to provide the system with<br>     * information about the provider.<br>     *<br>     * @param context A {@link Context} for the current component.<br>     * @param info A {@link ProviderInfo} for the new provider.<br>     */<br>    @SuppressWarnings(&quot;StringSplitter&quot;)<br>    @Override<br>    public void attachInfo(@NonNull Context context, @NonNull ProviderInfo info) {<br>        super.attachInfo(context, info);<br><br>        // Check our security attributes<br>//        if (info.exported) {<br>//            throw new SecurityException(&quot;Provider must not be exported&quot;);<br>//        }<br>        if (!info.grantUriPermissions) {<br>            throw new SecurityException(&quot;Provider must grant uri permissions&quot;);<br>        }<br><br>        String authority = info.authority.split(&quot;;&quot;)[0];<br>        synchronized (sCache) {<br>            sCache.remove(authority);<br>        }<br><br>        mStrategy = getPathStrategy(context, authority, mResourceId);<br>    }<br><br>    /**<br>     * Return a content URI for a given {@link File}. Specific temporary<br>     * permissions for the content URI can be set with<br>     * {@link Context#grantUriPermission(String, Uri, int)}, or added<br>     * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then<br>     * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are<br>     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and<br>     * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri} for file paths defined in their &lt;code&gt;&amp;lt;paths&amp;gt;&lt;/code&gt;<br>     * meta-data element. See the Class Overview for more information.<br>     *<br>     * @param context A {@link Context} for the current component.<br>     * @param authority The authority of a {@link FileProvider} defined in a<br>     *            {@code &lt;provider&gt;} element in your app&#39;s manifest.<br>     * @param file A {@link File} pointing to the filename for which you want a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri}.<br>     * @return A content URI for the file.<br>     * @throws IllegalArgumentException When the given {@link File} is outside<br>     * the paths supported by the provider.<br>     */<br>    public static Uri getUriForFile(@NonNull Context context, @NonNull String authority,<br>                                    @NonNull File file) {<br>        final PathStrategy strategy = getPathStrategy(context, authority, ResourcesCompat.ID_NULL);<br>        return strategy.getUriForFile(file);<br>    }<br><br>    /**<br>     * Return a content URI for a given {@link File}. Specific temporary<br>     * permissions for the content URI can be set with<br>     * {@link Context#grantUriPermission(String, Uri, int)}, or added<br>     * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then<br>     * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are<br>     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and<br>     * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri} for file paths defined in their &lt;code&gt;&amp;lt;paths&amp;gt;&lt;/code&gt;<br>     * meta-data element. See the Class Overview for more information.<br>     *<br>     * @param context A {@link Context} for the current component.<br>     * @param authority The authority of a {@link FileProvider} defined in a<br>     *            {@code &lt;provider&gt;} element in your app&#39;s manifest.<br>     * @param file A {@link File} pointing to the filename for which you want a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri}.<br>     * @param displayName The filename to be displayed. This can be used if the original filename<br>     * is undesirable.<br>     * @return A content URI for the file.<br>     * @throws IllegalArgumentException When the given {@link File} is outside<br>     * the paths supported by the provider.<br>     */<br>    @SuppressLint(&quot;StreamFiles&quot;)<br>    @NonNull<br>    public static Uri getUriForFile(@NonNull Context context, @NonNull String authority,<br>                                    @NonNull File file, @NonNull String displayName) {<br>        Uri uri = getUriForFile(context, authority, file);<br>        return uri.buildUpon().appendQueryParameter(DISPLAYNAME_FIELD, displayName).build();<br>    }<br><br>    /**<br>     * Use a content URI returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file<br>     * managed by the FileProvider.<br>     * FileProvider reports the column names defined in {@link OpenableColumns}:<br>     * &lt;ul&gt;<br>     * &lt;li&gt;{@link OpenableColumns#DISPLAY_NAME}&lt;/li&gt;<br>     * &lt;li&gt;{@link OpenableColumns#SIZE}&lt;/li&gt;<br>     * &lt;/ul&gt;<br>     * For more information, see<br>     * {@link ContentProvider#query(Uri, String[], String, String[], String)<br>     * ContentProvider.query()}.<br>     *<br>     * @param uri A content URI returned by {@link #getUriForFile}.<br>     * @param projection The list of columns to put into the {@link Cursor}. If null all columns are<br>     * included.<br>     * @param selection Selection criteria to apply. If null then all data that matches the content<br>     * URI is returned.<br>     * @param selectionArgs An array of {@link String}, containing arguments to bind to<br>     * the &lt;i&gt;selection&lt;/i&gt; parameter. The &lt;i&gt;query&lt;/i&gt; method scans &lt;i&gt;selection&lt;/i&gt; from left to<br>     * right and iterates through &lt;i&gt;selectionArgs&lt;/i&gt;, replacing the current &quot;?&quot; character in<br>     * &lt;i&gt;selection&lt;/i&gt; with the value at the current position in &lt;i&gt;selectionArgs&lt;/i&gt;. The<br>     * values are bound to &lt;i&gt;selection&lt;/i&gt; as {@link String} values.<br>     * @param sortOrder A {@link String} containing the column name(s) on which to sort<br>     * the resulting {@link Cursor}.<br>     * @return A {@link Cursor} containing the results of the query.<br>     *<br>     */<br>    @NonNull<br>    @Override<br>    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,<br>                        @Nullable String[] selectionArgs,<br>                        @Nullable String sortOrder) {<br>        // ContentProvider has already checked granted permissions<br>        final File file = mStrategy.getFileForUri(uri);<br>        String displayName = uri.getQueryParameter(DISPLAYNAME_FIELD);<br><br>        if (projection == null) {<br>            projection = COLUMNS;<br>        }<br><br>        String[] cols = new String[projection.length];<br>        Object[] values = new Object[projection.length];<br>        int i = 0;<br>        for (String col : projection) {<br>            if (OpenableColumns.DISPLAY_NAME.equals(col)) {<br>                cols[i] = OpenableColumns.DISPLAY_NAME;<br>                values[i++] = (displayName == null) ? file.getName() : displayName;<br>            } else if (OpenableColumns.SIZE.equals(col)) {<br>                cols[i] = OpenableColumns.SIZE;<br>                values[i++] = file.length();<br>            }<br>        }<br><br>        cols = copyOf(cols, i);<br>        values = copyOf(values, i);<br><br>        final MatrixCursor cursor = new MatrixCursor(cols, 1);<br>        cursor.addRow(values);<br>        return cursor;<br>    }<br><br>    /**<br>     * Returns the MIME type of a content URI returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     *<br>     * @param uri A content URI returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     * @return If the associated file has an extension, the MIME type associated with that<br>     * extension; otherwise &lt;code&gt;application/octet-stream&lt;/code&gt;.<br>     */<br>    @Nullable<br>    @Override<br>    public String getType(@NonNull Uri uri) {<br>        // ContentProvider has already checked granted permissions<br>        final File file = mStrategy.getFileForUri(uri);<br><br>        final int lastDot = file.getName().lastIndexOf(&#39;.&#39;);<br>        if (lastDot &gt;= 0) {<br>            final String extension = file.getName().substring(lastDot + 1);<br>            final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);<br>            if (mime != null) {<br>                return mime;<br>            }<br>        }<br><br>        return &quot;application/octet-stream&quot;;<br>    }<br><br>    /**<br>     * By default, this method throws an {@link UnsupportedOperationException}. You must<br>     * subclass FileProvider if you want to provide different functionality.<br>     */<br>    @Override<br>    public Uri insert(@NonNull Uri uri, @NonNull ContentValues values) {<br>        throw new UnsupportedOperationException(&quot;No external inserts&quot;);<br>    }<br><br>    /**<br>     * By default, this method throws an {@link UnsupportedOperationException}. You must<br>     * subclass FileProvider if you want to provide different functionality.<br>     */<br>    @Override<br>    public int update(@NonNull Uri uri, @NonNull ContentValues values, @Nullable String selection,<br>                      @Nullable String[] selectionArgs) {<br>        throw new UnsupportedOperationException(&quot;No external updates&quot;);<br>    }<br><br>    /**<br>     * Deletes the file associated with the specified content URI, as<br>     * returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this<br>     * method does &lt;b&gt;not&lt;/b&gt; throw an {@link IOException}; you must check its return value.<br>     *<br>     * @param uri A content URI for a file, as returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     * @param selection Ignored. Set to {@code null}.<br>     * @param selectionArgs Ignored. Set to {@code null}.<br>     * @return 1 if the delete succeeds; otherwise, 0.<br>     */<br>    @Override<br>    public int delete(@NonNull Uri uri, @Nullable String selection,<br>                      @Nullable String[] selectionArgs) {<br>        // ContentProvider has already checked granted permissions<br>//        final File file = mStrategy.getFileForUri(uri);<br>//        return file.delete() ? 1 : 0;<br>        throw new UnsupportedOperationException(&quot;No external delete&quot;);<br>    }<br><br>    /**<br>     * By default, FileProvider automatically returns the<br>     * {@link ParcelFileDescriptor} for a file associated with a &lt;code&gt;content://&lt;/code&gt;<br>     * {@link Uri}. To get the {@link ParcelFileDescriptor}, call<br>     * {@link ContentResolver#openFileDescriptor(Uri, String)<br>     * ContentResolver.openFileDescriptor}.<br>     *<br>     * To override this method, you must provide your own subclass of FileProvider.<br>     *<br>     * @param uri A content URI associated with a file, as returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     * @param mode Access mode for the file. May be &quot;r&quot; for read-only access, &quot;rw&quot; for read and<br>     * write access, or &quot;rwt&quot; for read and write access that truncates any existing file.<br>     * @return A new {@link ParcelFileDescriptor} with which you can access the file.<br>     */<br>    @SuppressLint(&quot;UnknownNullness&quot;) // b/171012356<br>    @Override<br>    public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)<br>            throws FileNotFoundException {<br>        // ContentProvider has already checked granted permissions<br>        final File file = mStrategy.getFileForUri(uri);<br>        final int fileMode = modeToMode(mode);<br>        return ParcelFileDescriptor.open(file, fileMode);<br>    }<br><br>    /**<br>     * Return {@link PathStrategy} for given authority, either by parsing or<br>     * returning from cache.<br>     */<br>    private static PathStrategy getPathStrategy(Context context, String authority, int resourceId) {<br>        PathStrategy strat;<br>        synchronized (sCache) {<br>            strat = sCache.get(authority);<br>            if (strat == null) {<br>                try {<br>                    strat = parsePathStrategy(context, authority, resourceId);<br>                } catch (IOException e) {<br>                    throw new IllegalArgumentException(<br>                            &quot;Failed to parse &quot; + META_DATA_FILE_PROVIDER_PATHS + &quot; meta-data&quot;, e);<br>                } catch (XmlPullParserException e) {<br>                    throw new IllegalArgumentException(<br>                            &quot;Failed to parse &quot; + META_DATA_FILE_PROVIDER_PATHS + &quot; meta-data&quot;, e);<br>                }<br>                sCache.put(authority, strat);<br>            }<br>        }<br>        return strat;<br>    }<br><br>    @VisibleForTesting<br>    static XmlResourceParser getFileProviderPathsMetaData(Context context, String authority,<br>                                                          @Nullable ProviderInfo info,<br>                                                          int resourceId) {<br>        if (info == null) {<br>            throw new IllegalArgumentException(<br>                    &quot;Couldn&#39;t find meta-data for provider with authority &quot; + authority);<br>        }<br><br>        if (info.metaData == null &amp;&amp; resourceId != ResourcesCompat.ID_NULL) {<br>            info.metaData = new Bundle(1);<br>            info.metaData.putInt(META_DATA_FILE_PROVIDER_PATHS, resourceId);<br>        }<br><br>        final XmlResourceParser in = info.loadXmlMetaData(<br>                context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);<br>        if (in == null) {<br>            throw new IllegalArgumentException(<br>                    &quot;Missing &quot; + META_DATA_FILE_PROVIDER_PATHS + &quot; meta-data&quot;);<br>        }<br><br>        return in;<br>    }<br><br>    /**<br>     * Parse and return {@link PathStrategy} for given authority as defined in<br>     * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data&gt;}.<br>     *<br>     * @see #getPathStrategy(Context, String, int)<br>     */<br>    private static PathStrategy parsePathStrategy(Context context, String authority, int resourceId)<br>            throws IOException, XmlPullParserException {<br>        final SimplePathStrategy strat = new SimplePathStrategy(authority);<br><br>        final ProviderInfo info = context.getPackageManager()<br>                .resolveContentProvider(authority, PackageManager.GET_META_DATA);<br>        final XmlResourceParser in = getFileProviderPathsMetaData(context, authority, info,<br>                resourceId);<br><br>        int type;<br>        while ((type = in.next()) != END_DOCUMENT) {<br>            if (type == START_TAG) {<br>                final String tag = in.getName();<br><br>                final String name = in.getAttributeValue(null, ATTR_NAME);<br>                String path = in.getAttributeValue(null, ATTR_PATH);<br><br>                File target = null;<br>                if (TAG_ROOT_PATH.equals(tag)) {<br>                    target = DEVICE_ROOT;<br>                } else if (TAG_FILES_PATH.equals(tag)) {<br>                    target = context.getFilesDir();<br>                } else if (TAG_CACHE_PATH.equals(tag)) {<br>                    target = context.getCacheDir();<br>                } else if (TAG_EXTERNAL.equals(tag)) {<br>                    target = Environment.getExternalStorageDirectory();<br>                } else if (TAG_EXTERNAL_FILES.equals(tag)) {<br>                    File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);<br>                    if (externalFilesDirs.length &gt; 0) {<br>                        target = externalFilesDirs[0];<br>                    }<br>                } else if (TAG_EXTERNAL_CACHE.equals(tag)) {<br>                    File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);<br>                    if (externalCacheDirs.length &gt; 0) {<br>                        target = externalCacheDirs[0];<br>                    }<br>                } else if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP<br>                        &amp;&amp; TAG_EXTERNAL_MEDIA.equals(tag)) {<br>                    File[] externalMediaDirs = Api21Impl.getExternalMediaDirs(context);<br>                    if (externalMediaDirs.length &gt; 0) {<br>                        target = externalMediaDirs[0];<br>                    }<br>                }<br><br>                if (target != null) {<br>                    strat.addRoot(name, buildPath(target, path));<br>                }<br>            }<br>        }<br><br>        return strat;<br>    }<br><br>    /**<br>     * Strategy for mapping between {@link File} and {@link Uri}.<br>     * &lt;p&gt;<br>     * Strategies must be symmetric so that mapping a {@link File} to a<br>     * {@link Uri} and then back to a {@link File} points at the original<br>     * target.<br>     * &lt;p&gt;<br>     * Strategies must remain consistent across app launches, and not rely on<br>     * dynamic state. This ensures that any generated {@link Uri} can still be<br>     * resolved if your process is killed and later restarted.<br>     *<br>     * @see SimplePathStrategy<br>     */<br>    interface PathStrategy {<br>        /**<br>         * Return a {@link Uri} that represents the given {@link File}.<br>         */<br>        Uri getUriForFile(File file);<br><br>        /**<br>         * Return a {@link File} that represents the given {@link Uri}.<br>         */<br>        File getFileForUri(Uri uri);<br>    }<br><br>    /**<br>     * Strategy that provides access to files living under a narrow allowed list<br>     * of filesystem roots. It will throw {@link SecurityException} if callers try<br>     * accessing files outside the configured roots.<br>     * &lt;p&gt;<br>     * For example, if configured with<br>     * {@code addRoot(&quot;myfiles&quot;, context.getFilesDir())}, then<br>     * {@code context.getFileStreamPath(&quot;foo.txt&quot;)} would map to<br>     * {@code content://myauthority/myfiles/foo.txt}.<br>     */<br>    static class SimplePathStrategy implements PathStrategy {<br>        private final String mAuthority;<br>        private final HashMap&lt;String, File&gt; mRoots = new HashMap&lt;&gt;();<br><br>        SimplePathStrategy(String authority) {<br>            mAuthority = authority;<br>        }<br><br>        /**<br>         * Add a mapping from a name to a filesystem root. The provider only offers<br>         * access to files that live under configured roots.<br>         */<br>        void addRoot(String name, File root) {<br>            if (TextUtils.isEmpty(name)) {<br>                throw new IllegalArgumentException(&quot;Name must not be empty&quot;);<br>            }<br><br>            try {<br>                // Resolve to canonical path to keep path checking fast<br>                root = root.getCanonicalFile();<br>            } catch (IOException e) {<br>                throw new IllegalArgumentException(<br>                        &quot;Failed to resolve canonical path for &quot; + root, e);<br>            }<br><br>            mRoots.put(name, root);<br>        }<br><br>        @Override<br>        public Uri getUriForFile(File file) {<br>            String path;<br>            try {<br>                path = file.getCanonicalPath();<br>            } catch (IOException e) {<br>                throw new IllegalArgumentException(&quot;Failed to resolve canonical path for &quot; + file);<br>            }<br><br>            // Find the most-specific root path<br>            Map.Entry&lt;String, File&gt; mostSpecific = null;<br>            for (Map.Entry&lt;String, File&gt; root : mRoots.entrySet()) {<br>                final String rootPath = root.getValue().getPath();<br>                if (path.startsWith(rootPath) &amp;&amp; (mostSpecific == null<br>                        || rootPath.length() &gt; mostSpecific.getValue().getPath().length())) {<br>                    mostSpecific = root;<br>                }<br>            }<br><br>            if (mostSpecific == null) {<br>                throw new IllegalArgumentException(<br>                        &quot;Failed to find configured root that contains &quot; + path);<br>            }<br><br>            // Start at first char of path under root<br>            final String rootPath = mostSpecific.getValue().getPath();<br>            if (rootPath.endsWith(&quot;/&quot;)) {<br>                path = path.substring(rootPath.length());<br>            } else {<br>                path = path.substring(rootPath.length() + 1);<br>            }<br><br>            // Encode the tag and path separately<br>            path = Uri.encode(mostSpecific.getKey()) + &#39;/&#39; + Uri.encode(path, &quot;/&quot;);<br>            return new Uri.Builder().scheme(&quot;content&quot;)<br>                    .authority(mAuthority).encodedPath(path).build();<br>        }<br><br>        @Override<br>        public File getFileForUri(Uri uri) {<br>            String path = uri.getEncodedPath();<br><br>            final int splitIndex = path.indexOf(&#39;/&#39;, 1);<br>            final String tag = Uri.decode(path.substring(1, splitIndex));<br>            path = Uri.decode(path.substring(splitIndex + 1));<br><br>            final File root = mRoots.get(tag);<br>            if (root == null) {<br>                throw new IllegalArgumentException(&quot;Unable to find configured root for &quot; + uri);<br>            }<br><br>            File file = new File(root, path);<br>            try {<br>                file = file.getCanonicalFile();<br>            } catch (IOException e) {<br>                throw new IllegalArgumentException(&quot;Failed to resolve canonical path for &quot; + file);<br>            }<br><br>            if (!file.getPath().startsWith(root.getPath())) {<br>                throw new SecurityException(&quot;Resolved path jumped beyond configured root&quot;);<br>            }<br><br>            return file;<br>        }<br>    }<br><br>    /**<br>     * Copied from ContentResolver.java<br>     */<br>    private static int modeToMode(String mode) {<br>        int modeBits;<br>        if (&quot;r&quot;.equals(mode)) {<br>            modeBits = ParcelFileDescriptor.MODE_READ_ONLY;<br>//        } else if (&quot;w&quot;.equals(mode) || &quot;wt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>//        } else if (&quot;wa&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_APPEND;<br>//        } else if (&quot;rw&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE;<br>//        } else if (&quot;rwt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid mode: &quot; + mode);<br>        }<br>        return modeBits;<br>    }<br><br>    private static File buildPath(File base, String... segments) {<br>        File cur = base;<br>        for (String segment : segments) {<br>            if (segment != null) {<br>                cur = new File(cur, segment);<br>            }<br>        }<br>        return cur;<br>    }<br><br>    private static String[] copyOf(String[] original, int newLength) {<br>        final String[] result = new String[newLength];<br>        System.arraycopy(original, 0, result, 0, newLength);<br>        return result;<br>    }<br><br>    private static Object[] copyOf(Object[] original, int newLength) {<br>        final Object[] result = new Object[newLength];<br>        System.arraycopy(original, 0, result, 0, newLength);<br>        return result;<br>    }<br><br>    @RequiresApi(21)<br>    static class Api21Impl {<br>        private Api21Impl() {<br>            // This class is not instantiable.<br>        }<br><br>        static File[] getExternalMediaDirs(Context context) {<br>            // Deprecated, otherwise this would belong on ContextCompat as a public method.<br>            return context.getExternalMediaDirs();<br>        }<br>    }<br>}</pre><p>中文版：</p><p><a href="https://medium.com/@wanxiao1994/%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%B8%A6%E6%9C%89%E8%BD%AE%E6%92%AD%E5%9B%BE%E7%9A%84notification-1f8e4cefabb5">如何实现带有轮播图的notification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b95fb817d2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何实现带有轮播图的notification]]></title>
            <link>https://medium.com/@wanxiao1994/%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%B8%A6%E6%9C%89%E8%BD%AE%E6%92%AD%E5%9B%BE%E7%9A%84notification-1f8e4cefabb5?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f8e4cefabb5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[fileprovider]]></category>
            <category><![CDATA[carousel]]></category>
            <category><![CDATA[custom-notification]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 07:05:48 GMT</pubDate>
            <atom:updated>2023-08-27T07:31:53.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*HQy0z51hLAGS8eMkOyLbhg.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-InROlayGjg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-InROlayGjg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-InROlayGjg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/667bd974cf1116e8a84032772a257b67/href">https://medium.com/media/667bd974cf1116e8a84032772a257b67/href</a></iframe><p>上面是我做的一个轮播图notification的录屏演示。它的本质就是一个自定义通知，但为了实现这个效果，还需要对FileProvider进行一点改造。接下来我就来讲解如何实现这个功能。</p><h3>如何下载图片</h3><p>我建议使用协程进行并发的图片下载，其中单个图片的下载可以使用 Picasso 来完成。</p><pre>val bitmap = Picasso.get().load(url).get()</pre><h3>自定义notification</h3><p>由于 Android 原生没有提供这种样式的 notification，我们需要使用自定义 notification 来实现，所以我们发送通知的代码如下：</p><pre>// 稍后会讲解 remoteViews 是如何创建的<br>val notification = NotificationCompat.Builder(requireContext(), CHANNEL_ID)<br>    .setSmallIcon(R.drawable.baseline_photo_library_24)<br>    .setContentTitle(&quot;ContentTitle&quot;)<br>    .setContentText(&quot;Expand to view carousel notification&quot;)<br>    .setCustomBigContentView(remoteViews)<br>    .build()<br>NotificationManagerCompat.from(requireContext()).apply {<br>    notify(generateId(), notification)<br>}</pre><h3>RemoteViews XML 布局</h3><p>自定义 notification 需要用到 RemoteViews。尽管 RemoteViews 也是使用 xml 来进行声明，但因为这个布局最终要被系统所加载，所以它内部所能使用的控件都是受限的，具体支持的控件可以参考下面的文档：</p><p><a href="https://developer.android.com/reference/android/widget/RemoteViews">RemoteViews | API reference | Android Developers</a></p><p>Android 提供的 ViewFlipper 可以让我们实现轮播效果。</p><p>接下来实现我们的 RemoteViews 的 xml 布局 layout_remote_custom_carousel.xml：</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        style=&quot;@style/TextAppearance.Compat.Notification.Title&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        tools:text=&quot;Custom Title&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/desc&quot;<br>        style=&quot;@style/TextAppearance.Compat.Notification.Line2&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        tools:text=&quot;Custom Desc Custom Desc Custom Desc Custom Desc&quot; /&gt;<br><br>    &lt;ViewFlipper<br>        android:id=&quot;@+id/view_flipper&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center_vertical&quot;<br>        android:autoStart=&quot;true&quot;<br>        android:flipInterval=&quot;3000&quot;<br>        android:inAnimation=&quot;@anim/slide_in_right&quot;<br>        android:outAnimation=&quot;@anim/slide_out_left&quot; /&gt;<br>&lt;/LinearLayout&gt;</pre><p>其中 slide_in_right 和 slide_out_left 是 ViewFlipper 切换视图时所使用的动画，这里我们做简单的 translate 动画即可：</p><p>slide_in_right.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;set xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;translate android:fromXDelta=&quot;100%p&quot; android:toXDelta=&quot;0&quot;<br>        android:duration=&quot;@android:integer/config_mediumAnimTime&quot;/&gt;<br>&lt;/set&gt;</pre><p>slide_out_left.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;set xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;translate android:fromXDelta=&quot;0&quot; android:toXDelta=&quot;-100%p&quot;<br>        android:duration=&quot;@android:integer/config_mediumAnimTime&quot;/&gt;<br>&lt;/set&gt;</pre><h3>填充 RemoteViews</h3><p>在刚才的代码里，并没有 remoteViews 的声明，这里我们来创建 remoteViews：</p><pre>val remoteViews = RemoteViews(<br>    requireContext().packageName,<br>    R.layout.layout_remote_custom_carousel<br>)<br><br>remoteViews.setTextViewText(R.id.title, &quot;Travel to Republic of Singapore&quot;)<br>remoteViews.setTextViewText(<br>    R.id.desc,<br>    &quot;Singapore is open to all travellers without quarantine or testing requirements&quot;<br>)</pre><p>现在我们只是将 layout_remote_custom_carousel.xml 加载并给其中的 TextView 设置了文案，但里面的 ViewFlipper 其实并没有内容，接下来我们要给 ViewFlipper 填充内容。</p><h3>ViewFlipper 中的单个元素布局</h3><p>我们要给 ViewFlipper 添加元素，可以通过这个接口 remoteViews.addView(R.id.view_flipper, childView) 来添加，其中 childView 也是一个 RemoteViews。</p><p>接下来定义单个元素的布局 layout_remote_custom_carousel_item.xml：</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/root&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        style=&quot;@style/TextAppearance.Compat.Notification.Info&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:ellipsize=&quot;end&quot;<br>        android:maxLines=&quot;1&quot; /&gt;<br><br>    &lt;FrameLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;&gt;<br><br>        &lt;ImageView<br>            android:id=&quot;@+id/image_view&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:adjustViewBounds=&quot;true&quot;<br>            android:scaleType=&quot;centerCrop&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/desc&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_gravity=&quot;bottom&quot;<br>            android:background=&quot;@drawable/shadow_bottom_up&quot;<br>            android:padding=&quot;6dp&quot;<br>            android:paddingTop=&quot;10dp&quot;<br>            android:textColor=&quot;#ffffff&quot;<br>            android:textSize=&quot;12dp&quot; /&gt;<br>    &lt;/FrameLayout&gt;<br>&lt;/LinearLayout&gt;</pre><h3>给 ViewFlipper 增加轮播元素</h3><p>假设我这里有一个 val bitmaps: List&lt;Bitmap&gt;? 其中存储的是轮播图片的 bitmap，dataTriples 为 Triple 数组，其中每个 Triple.second 存储的是单个轮播元素的的标题，Triple.third 存储的是单个轮播元素图片上的描述。依次遍历 bitmaps并构造 RemoteViews 然后执行 remoteViews.addView 即可。</p><pre>val childViews = Array(bitmaps.size) {<br>    val remoteView = RemoteViews(<br>        requireContext().packageName,<br>        R.layout.layout_remote_custom_carousel_item<br>    )<br><br>    remoteView.setImageViewBitmap(R.id.image_view, bitmapUris[it])<br><br>    remoteView.setTextViewText(R.id.title, dataTriples[it].second)<br>    remoteView.setTextViewText(R.id.desc, dataTriples[it].third)<br><br>    val pendingIntent = ...<br><br>    remoteView.setOnClickPendingIntent(R.id.root, pendingIntent)<br><br>    remoteView<br>}<br><br>for (each in childViews) {<br>    remoteViews.addView(R.id.view_flipper, each)<br>}</pre><h3>尝试运行：无效</h3><p>如果你真的按照我上面写的方式运行，取决于你的系统版本，你可能会发现 notification 的 ViewFlipper 中并没有内容，这是因为我们为了显示轮播图，传了多个 bitmap 给系统，且因为单个 bitmap 本身占用内存很大，当传递了多个 bitmap 时很容易被系统判定为传递数据过大，观察 logcat 可以看到类似下面的日志：</p><blockquote>NotificationService system_server W Removed too large RemoteViews (10093824 bytes) on pkg: com.example.shawtest tag: null id: 2</blockquote><p>因此我们不能使用 RemoteViews.setImageViewBitmap ，而应该用 RemoteViews.setImageViewUri，避免向系统直接传递 bitmap。</p><h3>保存文件并传递 Uri</h3><p>由于直接传递文件路径会被系统抛出 FileUriExposedException，因此我们在保存 bitmap 到文件后，还需要将文件转换为 Uri。</p><h4>标准 FileProvider 可能无法工作</h4><p>例如下面的代码保存 bitmap 到文件后，再通过标准 FileProvider 获取 Uri：</p><pre>val bitmap = Picasso.get().load(url).get()<br>val file = File(dir, UUID.randomUUID().toString())<br>file.outputStream().use {<br>    bitmap.compress(Bitmap.CompressFormat.WEBP, 90, it)<br>}<br>bitmap.recycle()<br>FileProvider.getUriForFile(requireContext(), authority, file)</pre><p>然后通过下面的代码设置路径</p><pre>remoteView.setImageViewUri(R.id.image_view, bitmapUris[it])</pre><p>你可能会在 Android 12 以前以及部分 Android 13 系统上发现系统没有权限访问我们设置的 Uri：</p><blockquote>android.widget.RemoteViews$ActionException: java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri content://com.example.shawtest.fileprovider/internal_cache/d2c5d24e-f9c1–48c4–9d5d-56f55f3efe42 from pid=2558, uid=1000 requires the provider be exported, or grantUriPermission()</blockquote><p>如果你尝试将 FileProvider 的 exported 属性设为 true，则 app 一启动就会崩溃，因为 FileProvider 会在运行时检查 exported 是否设置为 false，如果不为 false，则直接抛异常：</p><pre>@Override<br>public void attachInfo(@NonNull Context context, @NonNull ProviderInfo info) {<br>    super.attachInfo(context, info);<br><br>    // Check our security attributes<br>    if (info.exported) {<br>        throw new SecurityException(&quot;Provider must not be exported&quot;);<br>    }<br>    ...<br>}</pre><h4>修改 FileProvider 使其 exported 可以为 true</h4><p>既然如此，我们可以复制一份 FileProvider，删除相关的检查代码，使其可以设置 exported 为 true，不妨叫它 ExportedFileProvider：</p><pre>@Override<br>public void attachInfo(@NonNull Context context, @NonNull ProviderInfo info) {<br>    super.attachInfo(context, info);<br><br>    // Check our security attributes<br>//        if (info.exported) {<br>//            throw new SecurityException(&quot;Provider must not be exported&quot;);<br>//        }<br>    ...<br>}</pre><p>在 Manifest 中声明，注意我使用了一个特别的 authorities：</p><pre>        &lt;provider<br>            android:name=&quot;.fileprovider.ExportedFileProvider&quot;<br>            android:authorities=&quot;${applicationId}.fileprovider.exported&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;meta-data<br>                android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot;<br>                android:resource=&quot;@xml/exported_filepaths&quot; /&gt;<br>        &lt;/provider&gt;<br><br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>这里我选择将文件存储到内部的缓存目录。</p><p>由于 exported 为 true 的 FileProvider，允许第三方 app 访问任何暴露的路径，因此我们可以添加一个子目录 exported/ 避免将整个缓存目录暴露给其他 app。</p><p>exported_filepaths.xml：</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;paths xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;cache-path name=&quot;internal_cache&quot; path=&quot;exported/&quot; /&gt;<br>&lt;/paths&gt;</pre><p>修改保存文件的代码，注意我们要保存到 ExportedFileProvider 可以暴露的路径下：</p><pre>val dir = File(requireContext().cacheDir, &quot;exported&quot;)<br>// 请确保路径 dir 存在<br><br>val bitmap = Picasso.get().load(url).get()<br>val file = File(dir, UUID.randomUUID().toString())<br>file.outputStream().use {<br>    bitmap.compress(Bitmap.CompressFormat.WEBP, 90, it)<br>}<br>bitmap.recycle()<br>ExportedFileProvider.getUriForFile(requireContext(), authority, file)</pre><p>这样任意进程，包括系统进程就可以直接访问我们传递过去的 Uri 了。</p><p>注意其他任何文件都不应该保存到这个目录下，因为这个目录可以被任意第三方 app 访问</p><h3>关于 ExportedFileProvider 的更多安全性修改</h3><p>FileProvider 是禁止 exported 为 true 的，所以它有很多代码都是假设不会有第三方 app 直接访问它。由于 ExportedFileProvider exported 为 true，任何 app 都可以访问它，所以我们还需要在 ExportedFileProvider 中做一些修改，才能避免它被恶意 app 利用。</p><p>禁止删除，避免其他 app 试图删除我们暴露的目录下的文件：</p><pre>    @Override<br>    public int delete(@NonNull Uri uri, @Nullable String selection,<br>                      @Nullable String[] selectionArgs) {<br>        // ContentProvider has already checked granted permissions<br>//        final File file = mStrategy.getFileForUri(uri);<br>//        return file.delete() ? 1 : 0;<br>        throw new UnsupportedOperationException(&quot;No external delete&quot;);<br>    }</pre><p>禁止使用只读以外的模式打开文件，避免其他 app 试图修改或者写入文件到我们暴露的目录下：</p><pre>    /**<br>     * Copied from ContentResolver.java<br>     */<br>    private static int modeToMode(String mode) {<br>        int modeBits;<br>        if (&quot;r&quot;.equals(mode)) {<br>            modeBits = ParcelFileDescriptor.MODE_READ_ONLY;<br>//        } else if (&quot;w&quot;.equals(mode) || &quot;wt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>//        } else if (&quot;wa&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_APPEND;<br>//        } else if (&quot;rw&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE;<br>//        } else if (&quot;rwt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid mode: &quot; + mode);<br>        }<br>        return modeBits;<br>    }</pre><h4>ExportedFileProvider 是否有任意路径遍历漏洞</h4><p>由于 FileProvider 本身代码中 SimplePathStrategy#getFileForUri 有做路径校验，我们在 exported_filepaths.xml 中限制了这个 ExportedFileProvider 只能暴露内部缓存目录下的 exported 目录中的文件。因此 ExportedFileProvider 并不会有任意路径遍历漏洞。只是需要注意，内部缓存目录下的 exported 目录是完全暴露给第三方 app 的，只能用于这类特殊的文件存储。</p><h3>附录：完整ExportedFileProvider代码</h3><pre>public class ExportedFileProvider extends ContentProvider {<br>    private static final String[] COLUMNS = {<br>            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE };<br><br>    private static final String<br>            META_DATA_FILE_PROVIDER_PATHS = &quot;android.support.FILE_PROVIDER_PATHS&quot;;<br><br>    private static final String TAG_ROOT_PATH = &quot;root-path&quot;;<br>    private static final String TAG_FILES_PATH = &quot;files-path&quot;;<br>    private static final String TAG_CACHE_PATH = &quot;cache-path&quot;;<br>    private static final String TAG_EXTERNAL = &quot;external-path&quot;;<br>    private static final String TAG_EXTERNAL_FILES = &quot;external-files-path&quot;;<br>    private static final String TAG_EXTERNAL_CACHE = &quot;external-cache-path&quot;;<br>    private static final String TAG_EXTERNAL_MEDIA = &quot;external-media-path&quot;;<br><br>    private static final String ATTR_NAME = &quot;name&quot;;<br>    private static final String ATTR_PATH = &quot;path&quot;;<br><br>    private static final String DISPLAYNAME_FIELD = &quot;displayName&quot;;<br><br>    private static final File DEVICE_ROOT = new File(&quot;/&quot;);<br><br>    @GuardedBy(&quot;sCache&quot;)<br>    private static final HashMap&lt;String, PathStrategy&gt; sCache = new HashMap&lt;&gt;();<br><br>    private PathStrategy mStrategy;<br>    private int mResourceId;<br><br>    public ExportedFileProvider() {<br>        mResourceId = ResourcesCompat.ID_NULL;<br>    }<br><br>    protected ExportedFileProvider(@XmlRes int resourceId) {<br>        mResourceId = resourceId;<br>    }<br><br>    /**<br>     * The default FileProvider implementation does not need to be initialized. If you want to<br>     * override this method, you must provide your own subclass of FileProvider.<br>     */<br>    @Override<br>    public boolean onCreate() {<br>        return true;<br>    }<br><br>    /**<br>     * After the FileProvider is instantiated, this method is called to provide the system with<br>     * information about the provider.<br>     *<br>     * @param context A {@link Context} for the current component.<br>     * @param info A {@link ProviderInfo} for the new provider.<br>     */<br>    @SuppressWarnings(&quot;StringSplitter&quot;)<br>    @Override<br>    public void attachInfo(@NonNull Context context, @NonNull ProviderInfo info) {<br>        super.attachInfo(context, info);<br><br>        // Check our security attributes<br>//        if (info.exported) {<br>//            throw new SecurityException(&quot;Provider must not be exported&quot;);<br>//        }<br>        if (!info.grantUriPermissions) {<br>            throw new SecurityException(&quot;Provider must grant uri permissions&quot;);<br>        }<br><br>        String authority = info.authority.split(&quot;;&quot;)[0];<br>        synchronized (sCache) {<br>            sCache.remove(authority);<br>        }<br><br>        mStrategy = getPathStrategy(context, authority, mResourceId);<br>    }<br><br>    /**<br>     * Return a content URI for a given {@link File}. Specific temporary<br>     * permissions for the content URI can be set with<br>     * {@link Context#grantUriPermission(String, Uri, int)}, or added<br>     * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then<br>     * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are<br>     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and<br>     * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri} for file paths defined in their &lt;code&gt;&amp;lt;paths&amp;gt;&lt;/code&gt;<br>     * meta-data element. See the Class Overview for more information.<br>     *<br>     * @param context A {@link Context} for the current component.<br>     * @param authority The authority of a {@link FileProvider} defined in a<br>     *            {@code &lt;provider&gt;} element in your app&#39;s manifest.<br>     * @param file A {@link File} pointing to the filename for which you want a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri}.<br>     * @return A content URI for the file.<br>     * @throws IllegalArgumentException When the given {@link File} is outside<br>     * the paths supported by the provider.<br>     */<br>    public static Uri getUriForFile(@NonNull Context context, @NonNull String authority,<br>                                    @NonNull File file) {<br>        final PathStrategy strategy = getPathStrategy(context, authority, ResourcesCompat.ID_NULL);<br>        return strategy.getUriForFile(file);<br>    }<br><br>    /**<br>     * Return a content URI for a given {@link File}. Specific temporary<br>     * permissions for the content URI can be set with<br>     * {@link Context#grantUriPermission(String, Uri, int)}, or added<br>     * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then<br>     * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are<br>     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and<br>     * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri} for file paths defined in their &lt;code&gt;&amp;lt;paths&amp;gt;&lt;/code&gt;<br>     * meta-data element. See the Class Overview for more information.<br>     *<br>     * @param context A {@link Context} for the current component.<br>     * @param authority The authority of a {@link FileProvider} defined in a<br>     *            {@code &lt;provider&gt;} element in your app&#39;s manifest.<br>     * @param file A {@link File} pointing to the filename for which you want a<br>     * &lt;code&gt;content&lt;/code&gt; {@link Uri}.<br>     * @param displayName The filename to be displayed. This can be used if the original filename<br>     * is undesirable.<br>     * @return A content URI for the file.<br>     * @throws IllegalArgumentException When the given {@link File} is outside<br>     * the paths supported by the provider.<br>     */<br>    @SuppressLint(&quot;StreamFiles&quot;)<br>    @NonNull<br>    public static Uri getUriForFile(@NonNull Context context, @NonNull String authority,<br>                                    @NonNull File file, @NonNull String displayName) {<br>        Uri uri = getUriForFile(context, authority, file);<br>        return uri.buildUpon().appendQueryParameter(DISPLAYNAME_FIELD, displayName).build();<br>    }<br><br>    /**<br>     * Use a content URI returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file<br>     * managed by the FileProvider.<br>     * FileProvider reports the column names defined in {@link OpenableColumns}:<br>     * &lt;ul&gt;<br>     * &lt;li&gt;{@link OpenableColumns#DISPLAY_NAME}&lt;/li&gt;<br>     * &lt;li&gt;{@link OpenableColumns#SIZE}&lt;/li&gt;<br>     * &lt;/ul&gt;<br>     * For more information, see<br>     * {@link ContentProvider#query(Uri, String[], String, String[], String)<br>     * ContentProvider.query()}.<br>     *<br>     * @param uri A content URI returned by {@link #getUriForFile}.<br>     * @param projection The list of columns to put into the {@link Cursor}. If null all columns are<br>     * included.<br>     * @param selection Selection criteria to apply. If null then all data that matches the content<br>     * URI is returned.<br>     * @param selectionArgs An array of {@link String}, containing arguments to bind to<br>     * the &lt;i&gt;selection&lt;/i&gt; parameter. The &lt;i&gt;query&lt;/i&gt; method scans &lt;i&gt;selection&lt;/i&gt; from left to<br>     * right and iterates through &lt;i&gt;selectionArgs&lt;/i&gt;, replacing the current &quot;?&quot; character in<br>     * &lt;i&gt;selection&lt;/i&gt; with the value at the current position in &lt;i&gt;selectionArgs&lt;/i&gt;. The<br>     * values are bound to &lt;i&gt;selection&lt;/i&gt; as {@link String} values.<br>     * @param sortOrder A {@link String} containing the column name(s) on which to sort<br>     * the resulting {@link Cursor}.<br>     * @return A {@link Cursor} containing the results of the query.<br>     *<br>     */<br>    @NonNull<br>    @Override<br>    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,<br>                        @Nullable String[] selectionArgs,<br>                        @Nullable String sortOrder) {<br>        // ContentProvider has already checked granted permissions<br>        final File file = mStrategy.getFileForUri(uri);<br>        String displayName = uri.getQueryParameter(DISPLAYNAME_FIELD);<br><br>        if (projection == null) {<br>            projection = COLUMNS;<br>        }<br><br>        String[] cols = new String[projection.length];<br>        Object[] values = new Object[projection.length];<br>        int i = 0;<br>        for (String col : projection) {<br>            if (OpenableColumns.DISPLAY_NAME.equals(col)) {<br>                cols[i] = OpenableColumns.DISPLAY_NAME;<br>                values[i++] = (displayName == null) ? file.getName() : displayName;<br>            } else if (OpenableColumns.SIZE.equals(col)) {<br>                cols[i] = OpenableColumns.SIZE;<br>                values[i++] = file.length();<br>            }<br>        }<br><br>        cols = copyOf(cols, i);<br>        values = copyOf(values, i);<br><br>        final MatrixCursor cursor = new MatrixCursor(cols, 1);<br>        cursor.addRow(values);<br>        return cursor;<br>    }<br><br>    /**<br>     * Returns the MIME type of a content URI returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     *<br>     * @param uri A content URI returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     * @return If the associated file has an extension, the MIME type associated with that<br>     * extension; otherwise &lt;code&gt;application/octet-stream&lt;/code&gt;.<br>     */<br>    @Nullable<br>    @Override<br>    public String getType(@NonNull Uri uri) {<br>        // ContentProvider has already checked granted permissions<br>        final File file = mStrategy.getFileForUri(uri);<br><br>        final int lastDot = file.getName().lastIndexOf(&#39;.&#39;);<br>        if (lastDot &gt;= 0) {<br>            final String extension = file.getName().substring(lastDot + 1);<br>            final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);<br>            if (mime != null) {<br>                return mime;<br>            }<br>        }<br><br>        return &quot;application/octet-stream&quot;;<br>    }<br><br>    /**<br>     * By default, this method throws an {@link UnsupportedOperationException}. You must<br>     * subclass FileProvider if you want to provide different functionality.<br>     */<br>    @Override<br>    public Uri insert(@NonNull Uri uri, @NonNull ContentValues values) {<br>        throw new UnsupportedOperationException(&quot;No external inserts&quot;);<br>    }<br><br>    /**<br>     * By default, this method throws an {@link UnsupportedOperationException}. You must<br>     * subclass FileProvider if you want to provide different functionality.<br>     */<br>    @Override<br>    public int update(@NonNull Uri uri, @NonNull ContentValues values, @Nullable String selection,<br>                      @Nullable String[] selectionArgs) {<br>        throw new UnsupportedOperationException(&quot;No external updates&quot;);<br>    }<br><br>    /**<br>     * Deletes the file associated with the specified content URI, as<br>     * returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this<br>     * method does &lt;b&gt;not&lt;/b&gt; throw an {@link IOException}; you must check its return value.<br>     *<br>     * @param uri A content URI for a file, as returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     * @param selection Ignored. Set to {@code null}.<br>     * @param selectionArgs Ignored. Set to {@code null}.<br>     * @return 1 if the delete succeeds; otherwise, 0.<br>     */<br>    @Override<br>    public int delete(@NonNull Uri uri, @Nullable String selection,<br>                      @Nullable String[] selectionArgs) {<br>        // ContentProvider has already checked granted permissions<br>//        final File file = mStrategy.getFileForUri(uri);<br>//        return file.delete() ? 1 : 0;<br>        throw new UnsupportedOperationException(&quot;No external delete&quot;);<br>    }<br><br>    /**<br>     * By default, FileProvider automatically returns the<br>     * {@link ParcelFileDescriptor} for a file associated with a &lt;code&gt;content://&lt;/code&gt;<br>     * {@link Uri}. To get the {@link ParcelFileDescriptor}, call<br>     * {@link ContentResolver#openFileDescriptor(Uri, String)<br>     * ContentResolver.openFileDescriptor}.<br>     *<br>     * To override this method, you must provide your own subclass of FileProvider.<br>     *<br>     * @param uri A content URI associated with a file, as returned by<br>     * {@link #getUriForFile(Context, String, File) getUriForFile()}.<br>     * @param mode Access mode for the file. May be &quot;r&quot; for read-only access, &quot;rw&quot; for read and<br>     * write access, or &quot;rwt&quot; for read and write access that truncates any existing file.<br>     * @return A new {@link ParcelFileDescriptor} with which you can access the file.<br>     */<br>    @SuppressLint(&quot;UnknownNullness&quot;) // b/171012356<br>    @Override<br>    public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)<br>            throws FileNotFoundException {<br>        // ContentProvider has already checked granted permissions<br>        final File file = mStrategy.getFileForUri(uri);<br>        final int fileMode = modeToMode(mode);<br>        return ParcelFileDescriptor.open(file, fileMode);<br>    }<br><br>    /**<br>     * Return {@link PathStrategy} for given authority, either by parsing or<br>     * returning from cache.<br>     */<br>    private static PathStrategy getPathStrategy(Context context, String authority, int resourceId) {<br>        PathStrategy strat;<br>        synchronized (sCache) {<br>            strat = sCache.get(authority);<br>            if (strat == null) {<br>                try {<br>                    strat = parsePathStrategy(context, authority, resourceId);<br>                } catch (IOException e) {<br>                    throw new IllegalArgumentException(<br>                            &quot;Failed to parse &quot; + META_DATA_FILE_PROVIDER_PATHS + &quot; meta-data&quot;, e);<br>                } catch (XmlPullParserException e) {<br>                    throw new IllegalArgumentException(<br>                            &quot;Failed to parse &quot; + META_DATA_FILE_PROVIDER_PATHS + &quot; meta-data&quot;, e);<br>                }<br>                sCache.put(authority, strat);<br>            }<br>        }<br>        return strat;<br>    }<br><br>    @VisibleForTesting<br>    static XmlResourceParser getFileProviderPathsMetaData(Context context, String authority,<br>                                                          @Nullable ProviderInfo info,<br>                                                          int resourceId) {<br>        if (info == null) {<br>            throw new IllegalArgumentException(<br>                    &quot;Couldn&#39;t find meta-data for provider with authority &quot; + authority);<br>        }<br><br>        if (info.metaData == null &amp;&amp; resourceId != ResourcesCompat.ID_NULL) {<br>            info.metaData = new Bundle(1);<br>            info.metaData.putInt(META_DATA_FILE_PROVIDER_PATHS, resourceId);<br>        }<br><br>        final XmlResourceParser in = info.loadXmlMetaData(<br>                context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);<br>        if (in == null) {<br>            throw new IllegalArgumentException(<br>                    &quot;Missing &quot; + META_DATA_FILE_PROVIDER_PATHS + &quot; meta-data&quot;);<br>        }<br><br>        return in;<br>    }<br><br>    /**<br>     * Parse and return {@link PathStrategy} for given authority as defined in<br>     * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data&gt;}.<br>     *<br>     * @see #getPathStrategy(Context, String, int)<br>     */<br>    private static PathStrategy parsePathStrategy(Context context, String authority, int resourceId)<br>            throws IOException, XmlPullParserException {<br>        final SimplePathStrategy strat = new SimplePathStrategy(authority);<br><br>        final ProviderInfo info = context.getPackageManager()<br>                .resolveContentProvider(authority, PackageManager.GET_META_DATA);<br>        final XmlResourceParser in = getFileProviderPathsMetaData(context, authority, info,<br>                resourceId);<br><br>        int type;<br>        while ((type = in.next()) != END_DOCUMENT) {<br>            if (type == START_TAG) {<br>                final String tag = in.getName();<br><br>                final String name = in.getAttributeValue(null, ATTR_NAME);<br>                String path = in.getAttributeValue(null, ATTR_PATH);<br><br>                File target = null;<br>                if (TAG_ROOT_PATH.equals(tag)) {<br>                    target = DEVICE_ROOT;<br>                } else if (TAG_FILES_PATH.equals(tag)) {<br>                    target = context.getFilesDir();<br>                } else if (TAG_CACHE_PATH.equals(tag)) {<br>                    target = context.getCacheDir();<br>                } else if (TAG_EXTERNAL.equals(tag)) {<br>                    target = Environment.getExternalStorageDirectory();<br>                } else if (TAG_EXTERNAL_FILES.equals(tag)) {<br>                    File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);<br>                    if (externalFilesDirs.length &gt; 0) {<br>                        target = externalFilesDirs[0];<br>                    }<br>                } else if (TAG_EXTERNAL_CACHE.equals(tag)) {<br>                    File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);<br>                    if (externalCacheDirs.length &gt; 0) {<br>                        target = externalCacheDirs[0];<br>                    }<br>                } else if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP<br>                        &amp;&amp; TAG_EXTERNAL_MEDIA.equals(tag)) {<br>                    File[] externalMediaDirs = Api21Impl.getExternalMediaDirs(context);<br>                    if (externalMediaDirs.length &gt; 0) {<br>                        target = externalMediaDirs[0];<br>                    }<br>                }<br><br>                if (target != null) {<br>                    strat.addRoot(name, buildPath(target, path));<br>                }<br>            }<br>        }<br><br>        return strat;<br>    }<br><br>    /**<br>     * Strategy for mapping between {@link File} and {@link Uri}.<br>     * &lt;p&gt;<br>     * Strategies must be symmetric so that mapping a {@link File} to a<br>     * {@link Uri} and then back to a {@link File} points at the original<br>     * target.<br>     * &lt;p&gt;<br>     * Strategies must remain consistent across app launches, and not rely on<br>     * dynamic state. This ensures that any generated {@link Uri} can still be<br>     * resolved if your process is killed and later restarted.<br>     *<br>     * @see SimplePathStrategy<br>     */<br>    interface PathStrategy {<br>        /**<br>         * Return a {@link Uri} that represents the given {@link File}.<br>         */<br>        Uri getUriForFile(File file);<br><br>        /**<br>         * Return a {@link File} that represents the given {@link Uri}.<br>         */<br>        File getFileForUri(Uri uri);<br>    }<br><br>    /**<br>     * Strategy that provides access to files living under a narrow allowed list<br>     * of filesystem roots. It will throw {@link SecurityException} if callers try<br>     * accessing files outside the configured roots.<br>     * &lt;p&gt;<br>     * For example, if configured with<br>     * {@code addRoot(&quot;myfiles&quot;, context.getFilesDir())}, then<br>     * {@code context.getFileStreamPath(&quot;foo.txt&quot;)} would map to<br>     * {@code content://myauthority/myfiles/foo.txt}.<br>     */<br>    static class SimplePathStrategy implements PathStrategy {<br>        private final String mAuthority;<br>        private final HashMap&lt;String, File&gt; mRoots = new HashMap&lt;&gt;();<br><br>        SimplePathStrategy(String authority) {<br>            mAuthority = authority;<br>        }<br><br>        /**<br>         * Add a mapping from a name to a filesystem root. The provider only offers<br>         * access to files that live under configured roots.<br>         */<br>        void addRoot(String name, File root) {<br>            if (TextUtils.isEmpty(name)) {<br>                throw new IllegalArgumentException(&quot;Name must not be empty&quot;);<br>            }<br><br>            try {<br>                // Resolve to canonical path to keep path checking fast<br>                root = root.getCanonicalFile();<br>            } catch (IOException e) {<br>                throw new IllegalArgumentException(<br>                        &quot;Failed to resolve canonical path for &quot; + root, e);<br>            }<br><br>            mRoots.put(name, root);<br>        }<br><br>        @Override<br>        public Uri getUriForFile(File file) {<br>            String path;<br>            try {<br>                path = file.getCanonicalPath();<br>            } catch (IOException e) {<br>                throw new IllegalArgumentException(&quot;Failed to resolve canonical path for &quot; + file);<br>            }<br><br>            // Find the most-specific root path<br>            Map.Entry&lt;String, File&gt; mostSpecific = null;<br>            for (Map.Entry&lt;String, File&gt; root : mRoots.entrySet()) {<br>                final String rootPath = root.getValue().getPath();<br>                if (path.startsWith(rootPath) &amp;&amp; (mostSpecific == null<br>                        || rootPath.length() &gt; mostSpecific.getValue().getPath().length())) {<br>                    mostSpecific = root;<br>                }<br>            }<br><br>            if (mostSpecific == null) {<br>                throw new IllegalArgumentException(<br>                        &quot;Failed to find configured root that contains &quot; + path);<br>            }<br><br>            // Start at first char of path under root<br>            final String rootPath = mostSpecific.getValue().getPath();<br>            if (rootPath.endsWith(&quot;/&quot;)) {<br>                path = path.substring(rootPath.length());<br>            } else {<br>                path = path.substring(rootPath.length() + 1);<br>            }<br><br>            // Encode the tag and path separately<br>            path = Uri.encode(mostSpecific.getKey()) + &#39;/&#39; + Uri.encode(path, &quot;/&quot;);<br>            return new Uri.Builder().scheme(&quot;content&quot;)<br>                    .authority(mAuthority).encodedPath(path).build();<br>        }<br><br>        @Override<br>        public File getFileForUri(Uri uri) {<br>            String path = uri.getEncodedPath();<br><br>            final int splitIndex = path.indexOf(&#39;/&#39;, 1);<br>            final String tag = Uri.decode(path.substring(1, splitIndex));<br>            path = Uri.decode(path.substring(splitIndex + 1));<br><br>            final File root = mRoots.get(tag);<br>            if (root == null) {<br>                throw new IllegalArgumentException(&quot;Unable to find configured root for &quot; + uri);<br>            }<br><br>            File file = new File(root, path);<br>            try {<br>                file = file.getCanonicalFile();<br>            } catch (IOException e) {<br>                throw new IllegalArgumentException(&quot;Failed to resolve canonical path for &quot; + file);<br>            }<br><br>            if (!file.getPath().startsWith(root.getPath())) {<br>                throw new SecurityException(&quot;Resolved path jumped beyond configured root&quot;);<br>            }<br><br>            return file;<br>        }<br>    }<br><br>    /**<br>     * Copied from ContentResolver.java<br>     */<br>    private static int modeToMode(String mode) {<br>        int modeBits;<br>        if (&quot;r&quot;.equals(mode)) {<br>            modeBits = ParcelFileDescriptor.MODE_READ_ONLY;<br>//        } else if (&quot;w&quot;.equals(mode) || &quot;wt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>//        } else if (&quot;wa&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_APPEND;<br>//        } else if (&quot;rw&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE;<br>//        } else if (&quot;rwt&quot;.equals(mode)) {<br>//            modeBits = ParcelFileDescriptor.MODE_READ_WRITE<br>//                    | ParcelFileDescriptor.MODE_CREATE<br>//                    | ParcelFileDescriptor.MODE_TRUNCATE;<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid mode: &quot; + mode);<br>        }<br>        return modeBits;<br>    }<br><br>    private static File buildPath(File base, String... segments) {<br>        File cur = base;<br>        for (String segment : segments) {<br>            if (segment != null) {<br>                cur = new File(cur, segment);<br>            }<br>        }<br>        return cur;<br>    }<br><br>    private static String[] copyOf(String[] original, int newLength) {<br>        final String[] result = new String[newLength];<br>        System.arraycopy(original, 0, result, 0, newLength);<br>        return result;<br>    }<br><br>    private static Object[] copyOf(Object[] original, int newLength) {<br>        final Object[] result = new Object[newLength];<br>        System.arraycopy(original, 0, result, 0, newLength);<br>        return result;<br>    }<br><br>    @RequiresApi(21)<br>    static class Api21Impl {<br>        private Api21Impl() {<br>            // This class is not instantiable.<br>        }<br><br>        static File[] getExternalMediaDirs(Context context) {<br>            // Deprecated, otherwise this would belong on ContextCompat as a public method.<br>            return context.getExternalMediaDirs();<br>        }<br>    }<br>}</pre><p>English version:</p><p><a href="https://medium.com/@wanxiao1994/how-to-implement-a-carousel-style-notification-b95fb817d2ba">How to implement a carousel style notification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f8e4cefabb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android storage permission adaptation and reading/writing media files]]></title>
            <link>https://medium.com/@wanxiao1994/android-storage-permission-adaptation-and-reading-writing-media-files-6b85121c9461?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b85121c9461</guid>
            <category><![CDATA[android-storage]]></category>
            <category><![CDATA[permission]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mediastore]]></category>
            <category><![CDATA[scoped-storage]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 03:38:08 GMT</pubDate>
            <atom:updated>2023-04-09T04:15:48.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the years of my work, I have come across many storage-related codes, such as reading and writing media files. Most of them are wrong, such as applying for permissions when not necessary, reading files by querying file paths and then read. These codes can only work by chance. Even the code samples provided by the official documentation may not work sometimes. In addition, Android has been making modifications to the storage permission in its recent versions and has only recently provided official guidelines. This means that to write correct code, one still needs to pay attention to certain things.</p><h3>Access app-specific private internal storage</h3><p>Related APIs: Context.getFilesDir, Context.getCacheDir.</p><p>Reading and writing to the app’s private storage does not require any permission. You can use the File API directly.</p><p>The path returned by getFilesDir on Android 13 is /data/user/0/{packageName}/files.</p><h3>Access app-specific external storage</h3><p>Related APIs: Context.getExternalFilesDir, Context.getExternalCacheDir.</p><p>You can directly use the File API to access the app-specific external storage.</p><p>On Android 13, getExternalFilesDir returns the path /storage/emulated/0/Android/data/{packageName}/files.</p><p><strong>Permission requirement</strong></p><p>API level &lt; 19 (Android 4.4): WRITE_EXTERNAL_STORAGE or READ_EXTERNAL_STORAGE required.</p><p>API level ≥ 19 (Android 4.4): No permission required.</p><h3>Access external shared storage</h3><p>Related APIs: Environment.getExternalStorageDirectory, Environment.getExternalStoragePublicDirectory.</p><p>Just use the File API directly.</p><p>Note that starting from Android 11 (API level 30), due to the enforced scoped storage, these APIs can no longer be used, and I strongly recommend avoiding using these APIs. We will discuss this in detail later.</p><p><strong>Permission requirement</strong></p><p>WRITE_EXTERNAL_STORAGE or READ_EXTERNAL_STORAGE required.</p><p>To use these APIs on Android 10 (API level 29), you need to set requestLegacyExternalStorage to true to opt-out of scoped storage.</p><p>getExternalStorageDirectory returns /storage/emulated/0 on Android 9.</p><p>Next, let’s talk about reading and writing media files, which refer to files such as images, audio, and video.</p><h3>Reading media files</h3><h4>Using Intents</h4><p>Use Intent.ACTION_GET_CONTENT or Intent.ACTION_PICK action to call the system or third-party app to obtain a user-selected media file path.</p><p><strong>Permission requirement</strong></p><p>API level &lt; 29 (Android 10): READ_EXTERNAL_STORAGE required.</p><p>This is because accessing early versions of MediaStore Uri requires the app to have permission to read external storage. Since we don’t know where the Uri we obtained came from, we need to request permission to read external storage.</p><p>API level ≥ 29 (Android 10): No permission required</p><p>This is because modern apps grant read permission to the returned Uri, so we don’t need to request permission.</p><p><strong>The correct way to read files</strong></p><p>It should be noted that for Uris obtained through this method, the correct way to read the file is to use methods like ContentResolver.openInputStream to read the file, rather than querying the file path through ContentResolver and then accessing it with File API.</p><p>If you insist on querying the file path and accessing it with File API, you must set requestLegacyExternalStorage to true on Android 10 to opt-out of scoped storage, and do not assume that you will always get the file path, as the latest version of FileProvider no longer discloses the file path to queriers.</p><h4>Traversing external shared storage file paths manually</h4><blockquote>Note that this method cannot be used at all on Android 11 and above. I also strongly against using this method.</blockquote><p>Your app may not want to use a third-party media file picker and decides to create its own picker. You can directly traverse the user’s files through Environment.getExternalStoragePublicDirectory.</p><p><strong>Permission requirement</strong></p><p>API level &lt; 29 (Android 10): READ_EXTERNAL_STORAGE required</p><p>API level = 29 (Android 10): READ_EXTERNAL_STORAGE required and declare android:requestLegacyExternalStorage=&quot;true&quot; in the Manifest.</p><p>API level &gt; 29 (Android 10): this method is completely unusable.</p><h4>Using MediaStore API</h4><p>Use MediaStore API to read files. For usage, please refer to the official documentation.</p><p><a href="https://developer.android.com/training/data-storage/shared/media#query-collection">Access media files from shared storage | Android Developers</a></p><p><strong>Permission requirement</strong></p><p>API level &lt; 29 (Android 10): READ_EXTERNAL_STORAGE required.</p><p>MediaStore requires READ_EXTERNAL_STORAGE permission to read files before Android 10.</p><p>29 &lt;= API level &lt; 33 (Android 13):</p><p>If you only need to read and write files saved by your app in the media store, no permission required.</p><p>If you want to read other apps’ files in the media store, you need to request READ_EXTERNAL_STORAGE permission.</p><p>API level ≥ 33 (Android 13):</p><p>If you only need to read and write files saved by your app in the media store, no permission required.</p><p>If you want to read other apps’ files in the media store, you need to request the corresponding permission based on the file type:</p><ul><li>READ_MEDIA_IMAGES: Access other apps’ images .</li><li>READ_MEDIA_VIDEO: Access other apps’ video.</li><li>READ_MEDIA_AUDIO: Access other apps’ audio.</li></ul><blockquote>Do not try to check or request READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions on Android 13 or later. The system will reject the request directly.</blockquote><h3>Writing media files</h3><p>Please note that in most cases, we only need to save our own media files to the media store and do not need to edit or delete files belonging to other apps.</p><h4>Writing external shared storage through File API</h4><p>Traverse the user’s files directly through Environment.getExternalStoragePublicDirectory and perform write operations on them.</p><p>Here’s an example of saving a Bitmap as a PNG image to the user’s device using the File API:</p><pre>fun saveImageToFile(displayName: String, bitmap: Bitmap): Uri? {<br>    val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)<br>    val imageFile = File(directory, &quot;$displayName.png&quot;)<br>    if (!directory.isDirectory) {<br>        directory.mkdir()<br>    }<br>    return if (directory.isDirectory) {<br>        try {<br>            imageFile.outputStream().use {<br>                bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)<br>            }<br>            imageFile.toUri()<br>        } catch (e: IOException) {<br>            null<br>        }<br>    } else {<br>        null<br>    }<br>}</pre><p>Note that this method is completely unusable on Android 11 and above. However, I recommend you using this method to save media files on systems below Android 10 because the MediaStore API may not automatically create folders on systems below Android 10, leading to failed file saving.</p><p><strong>Permission requirement</strong></p><p>API level &lt; 29（Android 10）: WRITE_EXTERNAL_STORAGE required. Only recommended for saving media files to users’ device in this case.</p><p>API level = 29（Android 10）: WRITE_EXTERNAL_STORAGE required and declare android:requestLegacyExternalStorage=&quot;true&quot; in the Manifest.</p><p>API level &gt; 29（Android 10）: This method is completely unusable.</p><p><strong>Trigger media scan manually</strong></p><p>The above code only saves the file, but it does not trigger the media scan. Since this photo is not recorded in the media store, users cannot see the file in the album app, which displays data from the MediaStore. They can only see them in the file manager.</p><p>You can use the following code to trigger the media scanner to scan the file to add it to MediaStore:</p><pre>context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))</pre><h4>Using MediaStore API</h4><p>Here’s an example of how to save a Bitmap as a PNG image to the user’s media store using the MediaStore API:</p><pre>fun saveImageToMediaStore(context: Context, displayName: String, bitmap: Bitmap): Uri? {<br>    val imageCollections = if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) {<br>        MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)<br>    } else {<br>        MediaStore.Images.Media.EXTERNAL_CONTENT_URI<br>    }<br><br>    val imageDetails = ContentValues().apply {<br>        put(MediaStore.Images.Media.DISPLAY_NAME, displayName)<br>        put(MediaStore.Images.Media.MIME_TYPE, &quot;image/png&quot;)<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) {<br>            put(MediaStore.Images.Media.IS_PENDING, 1)<br>        }<br>    }<br><br>    val resolver = context.applicationContext.contentResolver<br>    val imageContentUri = resolver.insert(imageCollections, imageDetails) ?: return null<br><br>    return try {<br>        resolver.openOutputStream(imageContentUri, &quot;w&quot;).use { os -&gt;<br>            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os)<br>        }<br><br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) {<br>            imageDetails.clear()<br>            imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0)<br>            resolver.update(imageContentUri, imageDetails, null, null)<br>        }<br><br>        imageContentUri<br>    } catch (e: FileNotFoundException) {<br>        // Some legacy devices won&#39;t create directory for the Uri if dir not exist, resulting in<br>        // a FileNotFoundException. To resolve this issue, we should use the File API to save the<br>        // image, which allows us to create the directory ourselves.<br>        null<br>    }<br>}</pre><p>Please refer to the official documentation for usage instructions.</p><p><a href="https://developer.android.com/training/data-storage/shared/media#add-item">Access media files from shared storage | Android Developers</a></p><p><strong>Permission requirement</strong></p><p>API level &lt; 29 (Android 10): WRITE_EXTERNAL_STORAGE required.</p><p>API level = 29 (Android 10):</p><p>If you only need to save media files to the media store, no permission required.</p><p>If you need to write other apps’ files, it is recommended that you use one of the following methods:</p><ul><li><strong>Recommend</strong> using requestLegacyExternalStorage to opt-out of scoped storage, and then use the same code as in API level &lt; 29.</li><li>Catch and handle RecoverableSecurityException, refer to:</li></ul><p><a href="https://developer.android.com/training/data-storage/shared/media#update-other-apps-files">Access media files from shared storage | Android Developers</a></p><p>API level &gt; 29 (Android 10):</p><p>If you only need to save media files to the media store, no permission required.</p><p>If you need to write other apps’ files, you need to use the create*Request methods from the MediaStore API, such as <a href="https://developer.android.com/reference/android/provider/MediaStore#createWriteRequest(android.content.ContentResolver,%20java.util.Collection%3Candroid.net.Uri%3E)">createWriteRequest</a>, <a href="https://developer.android.com/reference/android/provider/MediaStore#createTrashRequest(android.content.ContentResolver,%20java.util.Collection%3Candroid.net.Uri%3E,%20boolean)">createTrashRequest</a>, to write to those files. For more information, please refer to:</p><p><a href="https://developer.android.com/training/data-storage/shared/media#manage-groups-files">Access media files from shared storage | Android Developers</a></p><blockquote>Do not try to check or request READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions on Android 13 or later. The system will reject the request directly.</blockquote><p><strong>Why I recommend writing external shared storage through File API on Android versions below 10</strong></p><p>Although saving media files to the media store using the MediaStore API allows for the same core code to be used across all Android versions, You may still encounter some issues.</p><p>During my investigation, I found that on some devices running Android versions prior to Android 10, saving media files using the MediaStore API does not trigger a media scan. In such cases, you need to obtain the file path and trigger a scan for that file, as shown in the code below:</p><pre>val filePath = getFilePathOfUri(context, imageUri)<br>if (filePath != null &amp;&amp; Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.Q) {<br>    context.sendBroadcast(<br>        Intent(<br>            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(<br>                File(filePath)<br>            )<br>        )<br>    )<br>}<br><br><br>fun getFilePathOfUri(context: Context, uri: Uri): String? {<br>    var result: String? = null;<br>    context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null)?.use { cursor -&gt;<br>        if (cursor.moveToFirst()) {<br>            val dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA)<br>            if (dataColumnIndex &gt;= 0) {<br>                result = cursor.getString(dataColumnIndex)<br>            }<br>        }<br>    }<br>    return result<br>}</pre><p>I have also found that on some devices running Android versions before 10, if the folder for saving the media file in the media store does not exist when saving through the MediaStore API, it will not be created automatically, leading to a failed file write. As the MediaStore API does not have a method to create a directory, this problem cannot be solved solely by using the MediaStore API.</p><p>Therefore, I recommend using the File API directly to write to external shared storage for API levels &lt; 29 (Android 10) and manually triggering a media scan after the file is written. For API level ≥ 29 (Android 10), using the MediaStore API as it doesn’t require requesting permissions or triggering media scan.</p><p>中文版：</p><p><a href="https://medium.com/@wanxiao1994/android%E5%AD%98%E5%82%A8%E6%9D%83%E9%99%90%E9%80%82%E9%85%8D%E4%B8%8E%E8%AF%BB%E5%86%99%E5%AA%92%E4%BD%93%E6%96%87%E4%BB%B6-5c2004a62dfa">Android存储权限适配与读写媒体文件</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b85121c9461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android存储权限适配与读写媒体文件]]></title>
            <link>https://medium.com/@wanxiao1994/android%E5%AD%98%E5%82%A8%E6%9D%83%E9%99%90%E9%80%82%E9%85%8D%E4%B8%8E%E8%AF%BB%E5%86%99%E5%AA%92%E4%BD%93%E6%96%87%E4%BB%B6-5c2004a62dfa?source=rss-2069902eeca1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c2004a62dfa</guid>
            <category><![CDATA[scoped-storage]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mediastore]]></category>
            <category><![CDATA[permission]]></category>
            <category><![CDATA[android-storage]]></category>
            <dc:creator><![CDATA[Wan Xiao]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 11:45:18 GMT</pubDate>
            <atom:updated>2023-04-09T03:47:29.464Z</atom:updated>
            <content:encoded><![CDATA[<p>我工作这些年，见过许多存储相关的代码，比如读写媒体文件。它们大部分都是错误的，比如在不需要申请权限的时候申请权限，查询文件路径再读文件，能正常工作也只是歪打正着。即便是官方推荐的正确写法，有时也无法工作。加上 Android 最近的几个版本不断的对存储权限做出修改，也是最近的版本才开始正视存储权限相关的问题，给出官方指引。这就导致，想写出正确的代码，还是需要注意一些东西的。</p><h3>读写app内部存储</h3><p>相关 API：Context.getFilesDir、Context.getCacheDir。</p><p>读写 app 私有目录并不需要权限，直接使用 File API 即可。</p><p>getFilesDir 在Android 13上，返回的路径为 /data/user/0/{packageName}/files 。</p><h3>读写app外部存储</h3><p>相关 API：Context.getExternalFilesDir、Context.getExternalCacheDir。</p><p>直接使用 File API 即可。</p><p>getExternalFilesDir在 Android 13 上，返回的路径为 /storage/emulated/0/Android/data/{packageName}/files 。</p><p><strong>权限要求</strong></p><p>API level &lt; 19（Android 4.4）：WRITE_EXTERNAL_STORAGE 或者 READ_EXTERNAL_STORAGE 权限。</p><p>API level ≥ 19（Android 4.4）：无需权限。</p><h3>读写外部共享存储</h3><p>相关API：Environment.getExternalStorageDirectory、Environment.getExternalStoragePublicDirectory。</p><p>直接使用 File API 即可。</p><p>注意 Android 11（API level 30）开始，由于强制分区存储，因此这些 API 再也无法使用，我也非常不推荐各位用这种 API 。具体后面会讲。</p><p>需要 WRITE_EXTERNAL_STORAGE 或者 READ_EXTERNAL_STORAGE 权限。如需在 Android 10（API level 29）上使用，需要将 requestLegacyExternalStorage 设置为 true，以避免被分区存储限制。</p><p>getExternalStorageDirectory 在 Android 9 上，返回的路径为 /storage/emulated/0 。</p><p>接下来介绍媒体文件的读写，这里媒体文件指的是图片、音频、视频这一类文件。</p><h3>读媒体文件</h3><h4>使用Intent</h4><p>使用 Intent.ACTION_GET_CONTENT 或者 Intent.ACTION_PICK 这类 action 来调用系统或者第三方app，获得一个用户选择的媒体文件路径。</p><p><strong>权限要求</strong></p><p>API level &lt; 29（Android 10）：申请 READ_EXTERNAL_STORAGE</p><p>这是因为访问早期的媒体库 Uri，要求 app 必须有读外部存储的权限，由于我们不知道我们获得的 Uri 是从何而来，因此需要申请读外部存储权限。</p><p>API level ≥ 29（Android 10）：无需申请权限</p><p>这是因为现在的 app，会对返回的 Uri 授予读权限，因此我们不需要申请权限。</p><p><strong>正确读取文件</strong></p><p>需要注意的是，对于这种方式获取到的 Uri 路径，正确的读取方式是使用 ContentResolver.openInputStream 这类方法来读取文件，而不是通过 ContentResolver 查询文件的路径，然后再用 File API 访问。</p><p>如果你一定要查询文件路径，然后使用 File API 访问，必须在 Android 10 上将 requestLegacyExternalStorage 置 true 以禁用分区存储，且不要假设你一定能拿到文件路径，因为最新版本的 FileProvider 已经不会响应文件路径的查询。</p><h4>自行遍历外部存储的文件路径</h4><p>注意这个方法在 Android 11 及以上完全无法使用。我也非常不推荐使用这个方法。</p><p>你的 app 可能不想用第三方的媒体文件选择器，决定自己做一个选择器。你可以直接通过Environment.getExternalStoragePublicDirectory 来遍历用户的文件。</p><p><strong>权限要求</strong></p><p>API level &lt; 29（Android 10）：申请 READ_EXTERNAL_STORAGE</p><p>API level = 29（Android 10）：申请 READ_EXTERNAL_STORAGE，且在 Manifest 中声明 android:requestLegacyExternalStorage=&quot;true&quot; 。</p><p>API level &gt; 29（Android 10）：这个方法完全不可用。</p><h4>使用MediaStore API</h4><p>使用 MediaStore API 来读取文件，使用方法可以参考官方文档：</p><p><a href="https://developer.android.com/training/data-storage/shared/media#query-collection">Access media files from shared storage | Android Developers</a></p><p><strong>权限要求</strong></p><p>API level &lt; 29（Android 10）：申请 READ_EXTERNAL_STORAGE，MediaStore 在 Android 10 之前要求 app 必须有 READ_EXTERNAL_STORAGE 权限才能读取其中的文件。</p><p>29 &lt;= API level &lt; 33（Android 13）：</p><p>如果你只需要读写 app 自身保存到媒体库的文件，不需要申请权限。</p><p>如果你想读取其他 app 写入到媒体库的文件，需要申请 READ_EXTERNAL_STORAGE。</p><p>API level ≥ 33（Android 13）：</p><p>如果你只需要读写 app 自身保存到媒体库的文件，不需要申请权限。</p><p>如果你想读取其他 app 写入到媒体库的文件，根据文件类型，你需要申请对应的权限：</p><ul><li>READ_MEDIA_IMAGES：访问其他 app 写入的图片。</li><li>READ_MEDIA_VIDEO：访问其他 app 写入的视频。</li><li>READ_MEDIA_AUDIO：访问其他 app 写入的音频。</li></ul><p>注意，在 Android 13 上不要再尝试检查或者动态申请 READ_EXTERNAL_STORAGE 或者 WRITE_EXTERNAL_STORAGE 权限，系统会直接拒绝。</p><h3>写媒体文件</h3><p>请注意，在绝大部分情况下，我们只是保存自己的媒体文件到媒体库，并不需要替换或者删除属于其他 app 的文件。</p><h4>通过外部存储的文件路径直接写入</h4><p>直接通过Environment.getExternalStoragePublicDirectory 来遍历用户的文件，并对用户的文件进行一些替换，或者删除。</p><p>这里是一个例子，将一个 Bitmap，以 png 图片的形式保存到用户的设备上，直接使用 File API：</p><pre>fun saveImageToFile(displayName: String, bitmap: Bitmap): Uri? {<br>    val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)<br>    val imageFile = File(directory, &quot;$displayName.png&quot;)<br>    if (!directory.isDirectory) {<br>        directory.mkdir()<br>    }<br>    return if (directory.isDirectory) {<br>        try {<br>            imageFile.outputStream().use {<br>                bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)<br>            }<br>            imageFile.toUri()<br>        } catch (e: IOException) {<br>            null<br>        }<br>    } else {<br>        null<br>    }<br>}</pre><p>注意这个方法在 Android 11 及以上完全无法使用。但我推荐你在 Android 10 以下的系统上使用这个方法来保存媒体文件，这是因为MediaStore API在 Android 10 以下的系统上可能不会自动创建文件夹，导致保存文件失败。</p><p><strong>权限要求</strong></p><p>API level &lt; 29（Android 10）：申请 WRITE_EXTERNAL_STORAGE。仅在这种情况下推荐用于保存媒体文件到用户的设备上。</p><p>API level = 29（Android 10）：申请 WRITE_EXTERNAL_STORAGE，且在 Manifest 中声明 android:requestLegacyExternalStorage=&quot;true&quot; 。</p><p>API level &gt; 29（Android 10）：这个方法完全不可用。</p><p><strong>注意事项</strong></p><p>上面只是做到了保存文件，但实际上并不会触发媒体库扫描器，所以此时用户在相册中并不能看到这张片，只能在文件管理中看到。</p><p>可以通过如下代码触发对该文件的扫描：</p><pre>context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))</pre><h4>使用MediaStore API</h4><p>这里是一个例子，将一个 Bitmap，以 png 图片的形式保存到用户媒体库中。</p><pre>fun saveImageToMediaStore(context: Context, displayName: String, bitmap: Bitmap): Uri? {<br>    val imageCollections = if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) {<br>        MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)<br>    } else {<br>        MediaStore.Images.Media.EXTERNAL_CONTENT_URI<br>    }<br><br>    val imageDetails = ContentValues().apply {<br>        put(MediaStore.Images.Media.DISPLAY_NAME, displayName)<br>        put(MediaStore.Images.Media.MIME_TYPE, &quot;image/png&quot;)<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) {<br>            put(MediaStore.Images.Media.IS_PENDING, 1)<br>        }<br>    }<br><br>    val resolver = context.applicationContext.contentResolver<br>    val imageContentUri = resolver.insert(imageCollections, imageDetails) ?: return null<br><br>    return try {<br>        resolver.openOutputStream(imageContentUri, &quot;w&quot;).use { os -&gt;<br>            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os)<br>        }<br><br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) {<br>            imageDetails.clear()<br>            imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0)<br>            resolver.update(imageContentUri, imageDetails, null, null)<br>        }<br><br>        imageContentUri<br>    } catch (e: FileNotFoundException) {<br>        // Some legacy devices won&#39;t create directory for the Uri if dir not exist, resulting in<br>        // a FileNotFoundException. To resolve this issue, we should use the File API to save the<br>        // image, which allows us to create the directory ourselves.<br>        null<br>    }<br>}</pre><p>具体的使用方法请参考官方文档：</p><p><a href="https://developer.android.com/training/data-storage/shared/media#add-item">Access media files from shared storage | Android Developers</a></p><p><strong>权限要求</strong></p><p>API level &lt; 29（Android 10）：申请 WRITE_EXTERNAL_STORAGE。</p><p>API level = 29（Android 10）：</p><p>如果你只需要保存媒体文件到媒体库，不需要申请权限。</p><p>如果你需要写其他 app 拥有的文件，推荐你使用如下两种方法之一。</p><ol><li>推荐使用 requestLegacyExternalStorage 禁用分区存储，然后使用和 API level &lt; 29 中一样的代码进行操作。</li><li>捕获 RecoverableSecurityException 并进行处理，参考：</li></ol><p><a href="https://developer.android.com/training/data-storage/shared/media#update-other-apps-files">Access media files from shared storage | Android Developers</a></p><p>API level &gt; 29（Android 10）：</p><p>如果你只需要保存媒体文件到媒体库，不需要申请权限。</p><p>如果你需要写其他 app 拥有的文件，则需要使用 MediaStore API 中的 create*Request 系列方法，例如 <a href="https://developer.android.com/reference/android/provider/MediaStore#createWriteRequest(android.content.ContentResolver,%20java.util.Collection%3Candroid.net.Uri%3E)">createWriteRequest</a>, <a href="https://developer.android.com/reference/android/provider/MediaStore#createTrashRequest(android.content.ContentResolver,%20java.util.Collection%3Candroid.net.Uri%3E,%20boolean)">createTrashRequest</a> 来写属于其他 app 的媒体文件，参考：</p><p><a href="https://developer.android.com/training/data-storage/shared/media#manage-groups-files">Access media files from shared storage | Android Developers</a></p><p>注意，在 Android 13 上不要再尝试检查或者动态申请 READ_EXTERNAL_STORAGE 或者 WRITE_EXTERNAL_STORAGE 权限，系统会直接拒绝。</p><p><strong>注意事项</strong></p><p>尽管将媒体文件保存到媒体库，使用 MediaStore API，核心逻辑可以一套代码在全部平台上运行，但仍然有需要注意的地方。</p><p>我在实际调查中发现，Android 10 以前的设备中，有一部分设备，在通过 MediaStore API 保存媒体文件到媒体库时，不会触发媒体库扫描，此时需要主动获取文件路径，并触发一次扫描：</p><pre>val filePath = getFilePathOfUri(context, imageUri)<br>if (filePath != null &amp;&amp; Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.Q) {<br>    context.sendBroadcast(<br>        Intent(<br>            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(<br>                File(filePath)<br>            )<br>        )<br>    )<br>}<br><br><br>fun getFilePathOfUri(context: Context, uri: Uri): String? {<br>    var result: String? = null;<br>    context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null)?.use { cursor -&gt;<br>        if (cursor.moveToFirst()) {<br>            val dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA)<br>            if (dataColumnIndex &gt;= 0) {<br>                result = cursor.getString(dataColumnIndex)<br>            }<br>        }<br>    }<br>    return result<br>}</pre><p>我还在实际调查中发现，Android 10以前的设备中，有一部分设备，在通过 MediaStore API 保存媒体文件到媒体库时，如果媒体库保存文件路径上的文件夹不存在，并不会自动创建，最终导致写文件失败。由于 MediaStore API 并没有创建路径的能力，只能写入文件，这个问题仅凭 MediaStore API 无法解决。</p><p>因此我建议对 API level &lt; 29（Android 10）直接使用 File API 来写入外部存储，并主动触发一次媒体库扫描文件，在 API level ≥ 29（Android 10）时，使用 MediaStore API，且无需申请权限。</p><p>English version:</p><p><a href="https://medium.com/@wanxiao1994/android-storage-permission-adaptation-and-reading-writing-media-files-6b85121c9461">Android storage permission adaptation and reading/writing media files</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c2004a62dfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>