<?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 Mina Hanna on Medium]]></title>
        <description><![CDATA[Stories by Mina Hanna on Medium]]></description>
        <link>https://medium.com/@minafawzi?source=rss-62bde90d91e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NozeVqEUcJAkJb9b</url>
            <title>Stories by Mina Hanna on Medium</title>
            <link>https://medium.com/@minafawzi?source=rss-62bde90d91e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:22:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@minafawzi/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[The Quantum Wave: Impacts on Cards and Wallets]]></title>
            <link>https://medium.com/@minafawzi/the-quantum-wave-impacts-on-cards-and-wallets-c8f09493af92?source=rss-62bde90d91e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8f09493af92</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[emv]]></category>
            <category><![CDATA[credit-cards]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Mina Hanna]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 04:47:44 GMT</pubDate>
            <atom:updated>2025-09-16T04:47:44.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51x24Yf1p-sTDoOHBYMHUg.png" /><figcaption>Thanks Gemini for the creativity !!</figcaption></figure><p>Chip cards and payment wallets were introduced with a key promise: security. As they handle consumer money and sensitive payment data, the highest level of security is required to protect against fraud attacks, both known and anticipated. To fulfill this promise, various cryptographic algorithms, protocols, policies, and specifications manage every aspect of the payment device and payment transaction lifecycle.</p><p>To name a few, <a href="https://www.emvco.com/specifications/">EMV Co website, </a><a href="https://www.pcisecuritystandards.org/document_library/">PCI Security Standards</a>, <a href="https://globalplatform.org/specs-library/?">Global Platform Specifications</a> and payment brand specific implementations for payments are some examples of specifications and protocols that governs the payment device and its security. However, it’s worth mentioning that some documentation is available only to members and not publicly accessible. In this article, almost all the details are based on the EMV book 2 — Security and Key Management — specification, which can be downloaded from the <a href="https://www.emvco.com/specifications/book-2-security-and-key-management-2/">EMV website</a>.</p><p>Quantum computing’s ability to break cryptographic algorithms poses a serious risk to the security of existing payment systems, especially with the latest news popping around the time of this article from <a href="https://news.microsoft.com/source/features/innovation/microsofts-majorana-1-chip-carves-new-path-for-quantum-computing/">Microsoft</a>, <a href="https://www.aboutamazon.com/news/aws/quantum-computing-aws-ocelot-chip">Amazon</a>, <a href="https://blog.google/technology/research/google-willow-quantum-chip/">Google </a>and <a href="https://www.livescience.com/technology/computing/china-achieves-quantum-supremacy-claim-with-new-chip-1-quadrillion-times-faster-than-the-most-powerful-supercomputers">China</a>. In this article I will try to dig a bit deep to summarize the impact and how the industry is moving forward accordingly.</p><p>Before we get started, this article assumes basic cryptography knowledge (i.e. you know PKI, symmetric vs asymmetric encryption) and basic payment domain expertise. If you need a crash course on both, please lookup YouTube or go through the <a href="https://www.thegeekstuff.com/2012/07/cryptography-basics/">Cryptography Basics</a> and <a href="https://www.knowyourpayments.com/transaction-basics/">Transactions Basics</a> articles.</p><p>Lets get started, the following will be the flow that I believe will connect the full story together. I will first start with an intro and a background to highlight the roles of different players in the process and then will go through the three main phases where keys are processed, stored or utilized. If you are only interested in the quantum piece, go to section #3 directly.</p><p>1- High level transaction flow</p><p>2- Cryptography in the payment transaction</p><p>3- What is the deal with quantum computing</p><p>4- How Quantum computing will impact payment</p><p>5- How the industry is moving forward</p><h3>1- High level transaction flow</h3><p>A payment transaction involves the transfer of data between various entities utilizing the well-established <a href="https://en.wikipedia.org/wiki/ISO_8583">ISO 8583</a> protocol, which has been in use for decades for transmitting magnetic stripe transactions prior to the emergence of EMV chip cards and mobile wallets. This protocol ensures that messages flow seamlessly from the merchant’s point of sale to the bank through a processing network managed by payment processing aggregators and payment brands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wA9JutUTwXuFSs-WLCXog.png" /></figure><p>The ISO message used in payment transactions comprises numerous fields that define the originator, merchant ID, and transaction details such as amount and date, among others. Additionally, the message includes card data that provides information about the issuing bank. This information is used by the payment network to route the transaction to the bank which then validate that the user has sufficient funds/credit to cover the transaction before the response flows back to the merchant point of sale.</p><p>The flow of the transaction is the same for both magnetic stripe (swipe) and EMV/chip-based transactions (insert or tap). However, the latter includes extra data fields to enhance security. The data field in the ISO message that contains all the chip data is referred to as Field 55, for record-keeping purposes.</p><p><strong>By delving deeper into the data stored within the chip/xPay wallet, we can categorize it into four key areas:</strong></p><ol><li><strong>Card Capabilities Data</strong>: This data communicates the card’s specific functionalities (e.g., application version) to the terminal device. This information allows the terminal to transmit appropriate and relevant commands for the transaction.</li><li><strong>Issuer Bank Settings (Card Profile)</strong>: These settings define the card’s behavior during transactions, including PIN attempt limits and cardholder verification methods (PIN versus signature).</li><li><strong>Cryptographic Data</strong>: This category encompasses both confidential keys (never retrieved from the card) used for generating transaction cryptograms and public key infrastructure (PKI) certificates. The certificates can be retrieved to verify the card’s authenticity.</li></ol><p>While there’s much more to explore regarding EMV data, this article focuses on the key points. For those interested in a deeper dive, numerous online resources are available, including this<a href="https://www.youtube.com/watch?v=Zv1DjtBwADg"> informative introductory video.</a></p><h3>2- Cryptography in the payment transaction</h3><p>To assess the potential impact of quantum computing on payment card transactions, we must first gain a basic understanding of how these transactions utilize various cryptographic algorithms.</p><p><strong>Pre-Transaction Security: The Power of Symmetric Keys</strong></p><p>Symmetric key cryptography plays a crucial role in securing data <strong>before</strong> the actual card transaction. This method safeguards data at rest and in transit. The data travels between platforms, capturing cardholder details, generating the 16-digit card number, and ultimately reaching a card personalization bureau or an Over The Air provisioning server (i.e. mobile wallet provisioning ). Here, the data is formatted and enriched before being loaded onto the chip (or other form of secure HW/SW component). To ensure secure transmission and prevent unauthorized device access, a <a href="https://eprint.iacr.org/2017/032.pdf">secure channel</a> exists between the provisioning device and the chip. Only authenticated devices can send provisioning commands to the chip.</p><p>The whole process of securing data in transit and while being loaded into the chip is also governed by <a href="https://www.emvco.com/specifications/emv-card-personalisation-specification/">EMVCo Card Personalization Specs</a> and the <a href="https://globalplatform.org/specs-library/">Global Platform secure channel protocols</a> and of course all PCI related policies.</p><p><strong>Transaction-time Security: Offline Authentication</strong></p><p>The EMV specification was developed mid-1990s and connectivity back then was not as it is nowadays so the specification ensured to add offline authentication capabilities. Offline Data Authentication (ODA) now help with the following:</p><ul><li>Based on the configuration, a transaction might be approved offline (in case of connectivity challenges) and settled at a later stage</li><li>Prevents replay attacks and chip card counterfeiting​</li><li>Offline authentication between the card and the terminal before proceeding with going online which validate the authenticity of the card</li><li>This is used heavily when using EMV payment cards and wallets in <a href="https://thepaypers.com/thought-leader-insights/closed-loop-versus-open-loop-payments-in-mass-transit--1262473">open loop transit</a> (allow passengers to pay for transit using a contactless card, mobile wallet). Transit gates and lines cannot wait for few seconds to validate that the card has enough credit so it relies on ODA to open the gates and keep the flow and proceed with the payment transaction flow later</li><li>Offline Encrypted Pin validation, where the terminal will capture the PIN, encrypt it using a key securely exchanged with the card and send it to the card for verification</li></ul><p>Offline authentication relies on PKI (Public Key Infrastructure) to create a certificate hierarchy maintaining the security and the authenticity of each issued card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CZNLzS4DZsA_h1jDwtOmg.png" /></figure><p>Here is what is done:</p><ul><li>Each payment brand will act as a Certificate Authority that maintains its own public/private key pair where the pubic keys will be distributed and loaded in all certified Point of Sale devices (here is a <a href="https://www.eftlab.com/knowledge-base/list-of-ca-public-keys">list </a>of major public keys).</li><li>For each card program, the issuing bank (directly or indirectly) will generate a key pair and have the public key signed by the Certificate Authority key</li><li>Each secure element/chip will have its own generated key pair where the public key will be signed by the issuing bank key</li><li>Issuer Public Key Certificate, Card public key Certificate, Signed data and its clear version will all be loaded into the card</li><li>During the transaction, the key loaded in the POS will be retrieve the issuer public key and then used retrieve the card own public key to validate the signed data and this will conclude the offline authentication which validates that the card was issued genuinely by an issuer who followed all key processes with the corresponding payment brand. <em>This is pretty similar to HTTPS flows if you are familiar with web security.</em></li></ul><p><strong>Transaction-Time Security: Unique Keys and Dynamic Cryptograms</strong></p><p>During the transaction itself, each provisioned payment application on the chip possesses a unique derived key. This key is generated by using the unique card number to derive a specific card key from a master key managed by the issuing bank. This unique card key then generates an Application Cryptogram (AC) using dynamic transaction data like the transaction amount and date. This dynamic nature ensures the uniqueness of each application cryptogram, further enhancing security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igU4iYAWGHvY5eEayw6WRg.png" /><figcaption>Symmetric Key Usage</figcaption></figure><p>If you reached here and still not 100% clear on the cryptography in an EMV payment transaction, I highly recommend watching <a href="https://youtu.be/HHfyrTn64UM">this video</a>.</p><p><strong>Key knowledge takeaway on security of cryptographic algorithms:</strong></p><p>Now that we have a good understanding of the cryptographic activities involved in the payment flows, we need to highlight a couple of takeaway items.</p><p>Cryptographic algorithms are mainly designed to secure information in one of the following verticals:</p><ul><li><strong>Confidentiality</strong>: Ensuring that only authorized parties can read the message. This is achieved through encryption.</li><li><strong>Integrity</strong>: Guaranteeing that a message hasn’t been altered. This is handled by digital signatures and hash functions.</li><li><strong>Authentication</strong>: Verifying the identity of the sender and the origin of the data.</li><li><strong>Non-repudiation</strong>️: Preventing a sender from denying they sent a message</li></ul><p>PKI mainly relies on mathematically linked keys: a <strong>public key</strong> (shared with anyone) for encryption and a <strong>private key</strong> (kept secret by the owner) for decryption. The whole thing is based on two very large, secret prime numbers. Let’s call them “Prime 1” and “Prime 2.”, the <strong>public key</strong> is the results of the multiplication of these two numbers and the original numbers are used to create the <strong>private key.</strong></p><p>The security comes from the difficulty of prime factorization. If someone intercepts your public key, they have the big number. But to find your private key (and decrypt your messages), they would have to “factor” that enormous number back into its two original prime numbers. Since that’s so incredibly hard and time-consuming, your private key (and your communications) remain secure.</p><p>The sophisticated problem in the current PKI domain is the factorization of prime numbers as highlighted above. Another example is lattice based cryptography which is based a high dimension lattice (grid) that can be represented by a simple set of vectors (good basis) and they are considered the private key and also other set of not easy vectors (bad basis) will be taken as a public key and used to encrypt the message which will be very easy to decrypt using the good basis. Short video about the concept in a 2D space is <a href="https://youtu.be/QDdOoYdb748?si=58b_m4tEcyUIdzq3">here</a>.</p><p>On the other side, Symmetric keys are essentially random strings of bits. The complexity comes from the incredibly vast number of possible key combinations, making “brute-force” (trying every possible key) attacks computationally infeasible.</p><p>Final takeaway is a quick intro for KEM (Key Encapsulation Mechanism) which blend both Asymmetric and Symmetric. It is a cryptographic process that uses asymmetric (public-key) encryption to secure and transport a randomly generated symmetric key. A Public Key Infrastructure (PKI) validates the identities of parties involved in this process, ensuring that the asymmetric keys used for the encapsulation are authentic</p><h3><strong>3- What is the deal with Quantum Computing</strong></h3><p>I will not dig into the deep quantum physics world but, <em>simply I can’t :)</em> , I will try to capture what we need to know as payment professionals.</p><p>I like to remind myself of the following Feynman <a href="https://www.feynmanlectures.caltech.edu/III_01.html">lecture </a>quote before any readings related to Quantum:</p><p>“<em>Because atomic behavior is so unlike ordinary experience, it is very difficult to get used to, and it appears peculiar and mysterious to everyone — both to the novice and to the experienced physicist.</em>”</p><p>Richard Feynman was captivated by the mind-blowing behavior of atoms, first observed in the <strong>double-slit experiment</strong>. This experiment revealed intriguing outcomes:</p><ul><li><strong>Waves (like lasers)</strong> passing through two slits create <strong>interference patterns</strong> on a backstop screen, demonstrating their wave properties as a single wave can traverse both slits simultaneously.</li><li>When <strong>large particles (like bullets)</strong> are fired, the backstop shows that each bullet passes through only one of the two slits, as expected.</li><li>However, when <strong>atomic-level particles (like electrons)</strong> are used, things become far more interesting: the electrons behave as both <strong>waves and particles</strong>, depending on how they’re measured.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*l3T_69KCdB38Syz1" /><figcaption>Source: <a href="https://quantumtech.blog/2023/07/06/the-quantum-leaps-beginner-guide-to-wave-particle-duality/">https://quantumtech.blog/2023/07/06/the-quantum-leaps-beginner-guide-to-wave-particle-duality/</a></figcaption></figure><p>Here are the core quantum mechanics takeaways from this experiment:</p><ul><li><strong>Wave-Particle Duality:</strong> Quantum entities like electrons and photons aren’t just particles or just waves; they behave like both, acting as a wave when unobserved and a particle when measured.</li><li><strong>Probability and Wave Function:</strong> The “wave” in quantum mechanics is a probability wave, meaning it describes the likelihood of finding a particle at a particular spot, with the interference pattern showing this probability distribution.</li><li><strong>The Observer Effect:</strong> The act of observing a quantum particle forces it to “choose” a definite state, collapsing its multiple possibilities into one outcome and challenging our classical idea of an objective reality.</li><li><strong>Superposition:</strong> A quantum particle can exist in multiple states simultaneously <em>before</em> it’s measured, like a coin spinning and being both heads and tails at once.</li><li><strong>Entanglement:</strong> Two or more quantum particles can become intrinsically linked, meaning the measurement of a property on one instantly reveals the corresponding property of the other, regardless of the distance between them.</li></ul><p>Just like classical computing were based on the Boolean algebra (developed by George Boole in the 19th century), the above quantum mechanics properties opened the doors for the quantum computing era. Imagine building a super-powerful computer by using the strange rules of the tiny, invisible world of atoms and particles. Here’s how it uses those rules:</p><ul><li><strong>Qubits (like special bits):</strong> Instead of regular computer bits that are either on (1) or off (0), quantum computers use “qubits.” These are like tiny, special switches that can be on, off, or <strong>both at the same time</strong>! This “both at the same time” trick is called <strong>superposition</strong>. It’s like flipping a coin and it’s both heads AND tails while it’s spinning in the air. This lets quantum computers explore many solutions at once.</li><li><strong>Entanglement (linked fates):</strong> Qubits can also be “entangled,” meaning they become deeply connected. If you change one entangled qubit, its partners instantly react, no matter how far apart they are. This linkage allows qubits to work together in powerful ways, making complex calculations possible.</li><li><strong>Probabilities (educated guesses):</strong> Unlike regular computers that give you a definite answer, quantum computers often give you a set of possibilities with different chances of being the right answer. The computer’s job is to increase the chances of the correct answer showing up, so you might run the calculation a few times to be sure.</li></ul><p><strong>Key takeaway: quantum computers get their power from these special “quantum” behaviors: being in many states at once (superposition) and having their fates linked (entanglement). Remember this is only happening on atomic level which makes quantum computers hard to build and scale.</strong></p><h3>4- How Quantum computing will impact payment</h3><p>One of the very known quantum algorithms that is challenging the PKI security (which is based on factorization) is Shor’s algorithm.</p><p>Shor’s algorithm leverages quantum mechanics to factor large numbers exponentially faster than classical computers by exploiting three key quantum properties: superposition, entanglement, and interference. Here’s how (simplified):</p><p>1. Quantum Superposition: Parallel Processing</p><p>The algorithm starts by placing qubits (quantum bits) into a superposition of all possible states simultaneously. This replaces the need to check each possibility one by one, as a classical computer would.</p><p>2. Entanglement: Linking Qubits</p><p>The algorithm entangles two quantum registers:</p><ul><li>The first register holds a superposition of exponents .</li><li>The second register stores the factorization function</li></ul><p>This entanglement ensures that measuring one register instantly determines the state of the other, creating a relationship between the input and output.</p><p>3. The algorithm used more quantum functionalities like QFT (Quantum Fourier Transform) which uses interference to amplify the correct period and cancel out incorrect guesses.</p><p>I have even a simpler explanation, lets see how we compare traditional wrench vs the universal socket wrench:</p><p>Traditionally for one nut (public key) you would try several wrenches to match:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*oBmOdak3SLTNwCcdSulSgA.png" /><figcaption>AI Generated using Flash</figcaption></figure><p>Now the quantum version “metaphorically” which fulfill several quantum properties :)</p><ul><li>Small cylinders acts as qubits (more qubits means more nuts can be matched) precisely</li><li>Input and output are instantly measured</li><li>Correct solution is amplified by adjusting the length of the cylinders to fit around the nut perfectly</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlj8WiRhKOvRJ_G782BzCg.png" /><figcaption>Combined AI generated images</figcaption></figure><p>The rising of powerful quantum computers introduces a shift in cybersecurity, particularly for the encryption methods we currently rely on <strong>Public Key Infrastructure (PKI)</strong>, which underpins secure authentication for payment cards (this is our scope here but such encryption algorithms powers all online communication and digital signatures), fundamentally depends on the immense difficulty of factoring very large numbers into their prime components. However, quantum computers, once they achieve sufficient scale and stability (i.e., enough high-quality qubits), possess algorithms like Shor’s Algorithm that can efficiently solve this factorization problem. This means that a quantum computer could, in theory, swiftly break the mathematical foundation of our most common public-key encryption schemes, rendering them vulnerable.</p><p>On the other hand, symmetric encryption algorithms, which use a single shared secret key for both encryption and decryption, operate on entirely different mathematical principles. They do not rely on prime number factorization. While quantum computers still offer some theoretical speedup for these algorithms through techniques like Grover’s Algorithm (which can accelerate brute-force searches), this speedup is not exponential like Shor’s. Consequently, symmetric encryption is considered far more resilient against quantum attacks, as quantum computers would not possess the same overwhelming leverage to compromise them, requiring only a modest increase in key length to maintain robust security.”</p><p>What does this really mean to the payment transaction ?</p><p>PKI certificates are used to have validate the following chain of trust (as discussed in the previous section):</p><ul><li><strong>Root Certification Authority (CA) Public Key:</strong> Every EMV terminal trusts a pre-loaded public key from a top-tier CA, establishing the foundation of trust.</li><li><strong>Issuer Public Key Certificate:</strong> Each card issuer’s public key is certified by the trusted Root CA and stored on the EMV card.</li><li><strong>ICC (Card) Public Key Certificate:</strong> The EMV chip card carries its own unique public key, digitally signed by its issuing bank.</li><li><strong>Dynamic Data Authentication:</strong> For each transaction, the card generates a unique signature by signing dynamic data, proving its authenticity and preventing fraud.</li></ul><p>On the top of card transaction specific usage, PKI is used in other bigger picture use case, including:</p><ul><li>Encryption of the overall transaction messages between different systems</li><li>Secure exchange of Symmetric keys between different parties</li></ul><h3>5- How the industry is moving forward</h3><p>Here are the core moving pieces:</p><ul><li>The National Institute of Standards and Technology (<strong>NIST</strong>) is publishing new <strong>post-quantum algorithms</strong> that were selected through a rigorous process involving all industry stakeholders. This is usually followed by broader standardization from the ISO (International Organization for Standardization)</li><li>After evaluating the threats and the specific impacts on the payment industry, <strong>EMVCo will then adopt the algorithms selected by NIST</strong> for their specifications</li><li>Each payment brand will define its own operating regulations and implementation timelines for <strong>issuers, acquirers, merchants, and all stakeholders.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*b_ymXKJe03DmVB79uIcwdw.png" /></figure><p>NIST, as the U.S. federal agency responsible for developing cybersecurity and cryptography standards, initiated its PQC project back in 2016 to lead the global effort to identify, evaluate, and standardize quantum-resistant algorithms. NIST approach was designed to be a public, competition-like process, with each phase open to public scrutiny.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRkLnqIOEKfHsQvoi8EGFA.png" /></figure><p>After the announcement, NIST started draft specifications for the selected algorithms to publish their FIPS (Federal Information Processing Standard) specification. FIPS is the actual implementation steps that can be used by industry for implementation and evaluation. Here is the up to date FIPS list from NIST (captured in August 2025):</p><h4><a href="https://csrc.nist.gov/pubs/fips/203/final">FIPS 203 (final):</a></h4><ul><li><strong>Algorithm:</strong> Module-Lattice-Based Key-Encapsulation Mechanism (ML-KEM), formerly known as CRYSTALS-Kyber.</li><li><strong>Cryptographic Theory:</strong> Lattice-based cryptography</li><li><strong>Used For:</strong> This standard specifies a key-encapsulation mechanism<strong> (KEM)</strong>, which is a method for two parties to establish a shared secret key over a public channel.</li></ul><h4><a href="https://csrc.nist.gov/pubs/fips/204/final">FIPS 204 (Final):</a></h4><ul><li><strong>Algorithm:</strong> Module-Lattice-Based Digital Signature Algorithm (ML-DSA), formerly known as CRYSTALS-Dilithium.</li><li><strong>Cryptographic Theory:</strong> Lattice-based cryptography</li><li><strong>Used For:</strong> This standard specifies a <strong>digital signature algorithm.</strong></li></ul><h4><a href="https://csrc.nist.gov/pubs/fips/205/final">FIPS 205 (Final):</a></h4><ul><li><strong>Algorithm:</strong> Stateless Hash-Based Digital Signature Algorithm (SLH-DSA), formerly known as SPHINCS+.</li><li><strong>Cryptographic Theory:</strong> Hash-based cryptography. Its security is based on the collision resistance of cryptographic hash functions.</li><li><strong>Used For:</strong> This standard is an alternative digital signature algorithm to FIPS 204.</li></ul><h4>FIPS 206 (Draft):</h4><ul><li><strong>Algorithm:</strong> The draft standard is based on the FALCON algorithm, but its official name under the FIPS standard will be FN-DSA.</li><li><strong>Cryptographic Theory:</strong> Lattice-based cryptography.</li><li><strong>Used For:</strong> This is another digital signature standard</li></ul><p>Based on NIST final algorithms, EMVCo will step in to define the following:</p><ul><li>What are the current and future risk for PQC and what is the impact to the payment domain ?</li><li>What are the roles and responsibilities of the different entities ?</li><li>Can this new algorithm be efficiently computed within the limited resources of a tiny chip or secure element used for payment transactions?</li><li>What is the migration roadmap, algorithm parameters (i.e. key length, prefixes.. etc.) and what actions can we take now?</li><li>Are there any lessons we can draw from past experiences?</li></ul><p>Before we analyze the EMVCo position statement, lets highlight some facts about the payment transaction and the state of the quantum computers:</p><ol><li>The “Harvest Now, Decrypt Later” (HNDL) threat is the fear that someone could steal and save encrypted data today and then use a powerful, future quantum computer to decrypt it later. While this is a serious concern for long-term, sensitive information (like government secrets), it’s not a major issue for data that loses its value quickly, such as encrypted payment transactions. By the time a quantum computer is ready to break the encryption, the payment information would be old and useless.</li><li>The current RSA Asymmetric algorithm usage in payment transaction is mainly for offline data authentication and since almost all payments today are made <strong>online</strong>, where a constant connection is available, offline use cases are becoming less relevant everyday (what’s relevant to mention here is that while EMVCo, which handles most credit and debit card payments, might not focus on offline transactions much, new digital currencies like those from central banks (CBDCs) <a href="https://www.idemia.com/press-release/idemia-secure-transactions-demonstrates-worlds-first-offline-cbdc-payment-transaction-resistant-quantum-computers-2024-06-20">will have to work offline and also be secure against future quantum computers</a>.)</li><li>While research is ongoing at a fast pace and increase interest, quantum computers today (at least what is published) is far from implementing Shor’s algorithm at a scale that will break the current RSA-2048 key length. This mainly due to the noise or what is called decoherence which impact the qubits which is, due to its atomic nature, easily impacted by temperature and magnetic fields and can lose its quantum properties.</li><li>Existing symmetric AES algorithm used in EMV transactions is a quantum safe algorithm as per NIST guidelines.</li><li>Adding more compute power to the EMV chip to enable the execution of a quantum safe algorithm, will impact the price and the supply chain of the payment cards and all hardware in mobile devices used for digital wallet provisioning.</li></ol><p>Based on the above points, <a href="https://www.emvco.com/knowledge-hub/quantum-computing-and-emv-chip-whats-the-threat/">EMVCo position paper</a> highlighted the following in brief:</p><ol><li>AES is still good as a symmetric algorithms</li><li>Online world reduce the need for offline use cases protected by RSA</li><li>Powerful quantum computers reaching bad actors has no confirmed timeline so the security working group is tracking various milestone related to the advancement in error handling and the large scale quantum entanglement</li><li>Crypto Agility is a key to easily update in case of any contingecy. Crypto Agility is simple to abstract your cryptographic operation (both in SW and HW forms) from other code to make sure you can upgrade only the core algorithms without impact the full operation.</li></ol><h3><strong>Final thoughts</strong></h3><ul><li>Tracking industry news and quantum advancement is a key to stay up to date but always look at the scale, future milestones and rate of the advancement</li><li>Keep an eye on skeptic articles and paper around quantum significance and use cases outside cryptography and other drug/bio-tech simulations to understand the industry scale, funding and overall commercial interest</li><li>Take a look at another interesting train of thoughts which challenges the principle of cryptography that is based on mathematical problems and that we should not keep all the world secrets under a risk of a smart mathematician who can solve the cryptography hard problem. (You can start <a href="https://bitmintnews.medium.com/the-biggest-challenge-of-modern-cryptography-does-not-get-any-press-a1c46380a815">here</a>).</li></ul><p>Cheers!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8f09493af92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Meets GIS]]></title>
            <link>https://medium.com/@minafawzi/machine-learning-meets-gis-4040bd080c2f?source=rss-62bde90d91e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4040bd080c2f</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[openstreetmap]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mina Hanna]]></dc:creator>
            <pubDate>Mon, 06 May 2024 16:19:51 GMT</pubDate>
            <atom:updated>2024-05-06T16:19:51.274Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1: Data Collection</h3><p>Machine learning is poised to revolutionize various industries, particularly when combined with computer vision and the abundance of remote sensing data accessible for free today.</p><p>During recent months, I had the chance to dig into various applications that harness this powerful combination and was researching different topics around (just scratching the surface):</p><ul><li>Satellite image enhancements and denoising</li><li>Deprived area classifications</li><li>Building detection and footprint</li><li>City morphological classifications</li><li>Clustering and segmentation</li></ul><p>Each of these applications utilizes various techniques in image processing and machine learning, for example, satellite image enhancement can use <a href="https://ut3-toulouseinp.hal.science/hal-03778771/document">CNN autoencoders </a>to reduce noise and/or compress the image. Pre-trained models can be used to classify deprived areas and help prioritize development projects and track progress over the years.</p><p>This series will go through the different steps of basic definitions, data sourcing and model development to cover an end-to-end GIS projects utilizing modern machine learning techniques.</p><p>Data pipeline is always the crucial component in any ML project so understanding geographical data is a key. Here are some data types, utilities and formats used in the GIS space with very brief description.</p><ul><li><strong>Vector</strong>: a vector is a graphics that is represented by points, line and polygons and in GIS this is mostly shapes that represent borders or certain geographical boundaries.</li><li><strong>Raster</strong>: a raster is a bitmap where each pixel can represent data stored in bits.</li><li><strong>GeoTiff</strong>: tiff file format is a very well known raster format to store digital images without losing details in compression (like jpeg) and GeoTiff is a tiff file where every pixel has map projections (i.e. location) and other tags that can be encoded. (more on files and formats <a href="https://gisgeography.com/gis-formats/">here</a>)</li><li><strong>CRS</strong>: Coordinate Reference System which defines how points are referenced within maps (check out <a href="https://mgimond.github.io/Spatial/chp09_0.html">this </a>for perfect understanding)</li><li><strong>GIS Software:</strong> this is the software you will need to open, edit and play with maps like <a href="https://www.qgis.org/en/site/">QGIS</a>, <a href="https://www.arcgis.com/index.html">ArcGIS </a>or <a href="https://saga-gis.sourceforge.io/">SAGA GIS</a>. These are mostly free and open source tool (other tools are too expensive for individual exploration) and uses a famous framework called <a href="https://medium.com/planet-stories/a-gentle-introduction-to-gdal-part-1-a3253eb96082">GDAL</a>.</li><li><strong>Satellite Image Bands</strong>: each satellite is equipped with different sensors that can capture specific details beyond the natural RGB (Red, Green and Blue) bands that can associated into a standard pixel. A good example can be found <a href="https://gisgeography.com/sentinel-2-bands-combinations/">here</a>. A set of bands can be grouped together in one GeoTiff.</li><li><strong>Well-Known Text (WKT):</strong> this is a markup language define vector geometry and is commonly used to define polygons and borders of geographical regions (i.e. you can download a map based on a polygon coordinates defined in a WKT file). This is a great <a href="https://arthur-e.github.io/Wicket/sandbox-gmaps3.html">interactive tool</a> to export/read WKT.</li></ul><p>Now, where is the data ? here are some GIS data (just scratching the surface) that could potentially feed a machine learning model.</p><ol><li>Satellites Maps/Images</li><li>Buildings Data</li><li>OSM</li></ol><h3>Satellites Maps</h3><p>High-resolution satellite imagery is typically not freely available, except in limited circumstances such as disaster zones, sample areas, and specific regions of interest. Free satellite imagery, on the other hand, is typically of lower resolution and may lack some details. However, it has been used extensively by open source and research communities to validate models and support a wide range of research papers.</p><p>The suitability of freely available satellite imagery depends on the specific research context and the region of interest. For instance, in the case of the West African shores (see below image on the right when compared to the high resolution image on the left), the image quality is significantly hindered by reflections and low resolution. This makes such imagery less suitable for tasks such as building classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xj0thMzm4ooG_O1z0KBfMA.png" /></figure><p>Sentinel 2 satellite imagery from the <a href="https://www.copernicus.eu/en">European Space Agency</a> is one of the most popular free satellite imagery available. You can follow the steps <a href="https://gisgeography.com/how-to-download-sentinel-satellite-data/">here </a>to be able to download Sentinel 2 satellite imagery. I highly recommend checking the steps in this <a href="https://www.youtube.com/watch?v=XGxYVoX2jOY">video </a>that use an amazing plugin in QGIS software to download, process and view images in QGIS right away.</p><p>One of the important processing steps is to convert a GeoTiff map to other format that can be utilized in a machine learning pipeline (i.e. jpeg or PNG). There are a lot of plugins and functions in different GIS software that can do that but doing it programmatically can help automating your pipeline and give you more control.</p><p>The following code is a simple implementation for a PNG conversion which is split as follows:</p><pre>import numpy as np<br>from osgeo import gdal<br>from PIL import Image<br><br># read the file and construct a zero numpy<br>dataset = gdal.Open(input_file, gdal.GA_ReadOnly)<br>image = np.zeros((dataset.RasterYSize, dataset.RasterXSize, dataset.RasterCount),<br>                 dtype=float)</pre><p>The empty array will have the new bitmap file that will be the converted to PNG. It will have the same dimension X*Y and the total number of bands (i.e. 3 for RGB).</p><p>Now you need to read the bands in your raster and here it is very important to understand the bands in your GeoTiff. Sentinel-2 has 13 bands where bands 2,3 and 4 represents the blue, green and red visible colors. Please check the Satellite bands definition above for further reading.</p><pre># read the 4 bands in each geoTiff<br>band1 = dataset.GetRasterBand(1)<br>band2 = dataset.GetRasterBand(2)<br>band3 = dataset.GetRasterBand(3)</pre><p>The bands now can be combined in an array similar to the original geotiff size:</p><pre>image = np.zeros((dataset.RasterYSize, dataset.RasterXSize, dataset.RasterCount),<br>                 dtype=float)<br>image[:, :, 0] = band1.ReadAsArray()<br>image[:, :, 1] = band2.ReadAsArray()<br>image[:, :, 2] = band3.ReadAsArray()</pre><p>The next step is to make sure that the value of every pixel is between 0 and 255 which is the allowed values for an RGB image. In satellite GeoTiff images, this is not always the case so we have to normalize all the pixel values based on the minimum and maximum of the image.</p><pre># Normalize<br>temp = image[:,:,0]<br>image[:,:,0] = (temp - temp.min()) / (temp.max() - temp.min())<br><br>temp = image[:,:,1]<br>image[:,:,1] = (temp - temp.min()) / (temp.max() - temp.min())<br><br>temp = image[:,:,2]<br>image[:,:,2] = (temp - temp.min()) / (temp.max() - temp.min())<br><br># Get values in the range of 0-255<br><br> image= image*255<br><br># remove any decimal point<br>image= np.around(image, decimals=0)<br><br># Convert to image using PIL library<br>final_image= Image.fromarray(np.uint8(image))<br>final_image.save(path)</pre><p>Now that we have the image in PNG format we can apply different machine learning techniques like training a CNN for classifications.</p><h3>Buildings Data</h3><p>Building footprints reveal a wealth of information about an area, enabling a variety of applications, including population estimation based on building size and density, disaster response planning, mobility analysis, and many more. Machine learning techniques can further enhance the usability of this data.</p><p>Several major tech companies are actively involved in this field, with notable examples including<a href="https://sites.research.google/open-buildings/"> Google Open Building</a> Data, <a href="https://www.microsoft.com/en-us/maps/bing-maps/building-footprints">Microsoft Building Footprints</a>, and <a href="https://overturemaps.org/overture-maps-foundation-releases-first-world-wide-open-map-dataset/">Overture Open Maps</a>, which is backed by Amazon, Meta, Microsoft, and Tomtom. This data is freely available and accessible.</p><p>The building data itself was generated using deep learning models trained on high-resolution satellite imagery to identify buildings with varying confidence levels. We might not have the high-resolution images available but we have the buildings data.</p><p>The format of the building data is usually numerical record for each building containing the following fields (data is downloadable in csv format):</p><ul><li>Coordinates of the building (longitude and latitude)</li><li>Building shape (usually a polygon or multi-polygon geometry shape)</li><li>Area and other properties</li></ul><p>A good exercise to work on the dats might be converting it to images. To draw the building polygons within a specific boundary the following steps and code will do it (below code was using Google Open Building data):</p><ol><li>Load the open building data, define the boundary box for the desired clip and query the data to extract building polygons falling within the boundary box</li></ol><pre>all_bldgs = pd.read_csv(r&#39;Open_Building.csv&#39;)<br><br># Get pixel coordinates and define the 4 boundary coordinates<br># Based on the image resolution (0.00008333) represents 10 meters<br># The boundary box in this case is 100x100 meters calculated from a given coordinates<br>py, px = row[&#39;long&#39;], row[&#39;lat&#39;]<br>py1 = round(py + 5*0.00008333, 6)<br>py2 = round(py - 5*0.00008333, 6)<br>px1 = round(px + 5*0.00008333, 6)<br>px2 = round(px - 5*0.00008333, 6)<br><br># Query text to bound longitude and latitude within the boundaries<br>query_text = &#39;latitude  &lt;&#39; +str(px1)+ &#39; &amp; latitude &gt; &#39;+str(px2)+ &#39; &amp; longitude &lt; &#39; + str(py1)+&#39; &amp; longitude &gt; &#39; +str(py2)<br><br># Run query to have all building within the boundary box in the zone<br>zone = all_bldgs.query(query_text)<br><br># Now we can call a custom function (implementation below) to generate the image<br>image = generate_OB_Image(py2,px1,zone)</pre><p>The data extracted from the query line would look like this (assuming 2 building were within the defined boundary)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mT4-Oam_72NH0ornE7RuIQ.png" /></figure><p>2. The code to draw the building images will utilize the <a href="https://www.geeksforgeeks.org/python-pil-imagedraw-draw-polygon-method/">ImageDraw.Draw.polygon()</a> function and will format the data to fit the desired input format of the function.</p><pre>def generate_OB_Image(x,y,polygons):<br>    &quot;&quot;&quot;<br>    generate an image with building polygons<br>    Inputs:<br>        input_file (str) : the name of input tiff file<br>    return:<br>        image(np.array) : image<br>    &quot;&quot;&quot;<br>    # Create an empty image<br>    image = Image.new(&quot;RGB&quot;, (100, 100))<br>    draw = ImageDraw.Draw(image)<br>    <br>    # Iterate through all the rows (each row has a polygon that represents a building<br>    # Remove any text to end up with a stream of coordinates X and Y to fit with the Draw.polygon function<br>    for index, row in polygons.iterrows():<br>        polygon = row[&quot;geometry&quot;]<br>        polygon = polygon.replace(&#39;MULTIPOLYGON&#39;, &quot;&quot;).replace(&#39;POLYGON&#39;, &quot;&quot;).replace(&quot;(&quot;, &quot;&quot;).replace(&quot;)&quot;, &quot;&quot;)<br>        polygon = polygon.replace(&#39;,&#39;, &quot;&quot;).split(&quot; &quot;)<br>        polygon = np.array(polygon)<br>        polygon = polygon.astype(float)<br>        points = ()<br>        for j in range(0,len(polygon),2):<br>            # Use original coordinates of the boundary (which was the center of the box) to recalculate the points <br>            # The points values should be relative top left corner not center          <br>            element = (polygon[j]-x)/0.0000089999 , (y-polygon[j+1])/0.0000089999<br>            points = points + (element,)<br><br>        # Use the function to draw the polygon based on the points extracted and define the colors<br>        draw.polygon((points), fill =&quot;#eeeeff&quot;, outline =&quot;black&quot;)<br>    return image</pre><p>The outcome of this function is an image that contains building polygons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*vXTq3aC5OCVSyEre1CZWoA.png" /></figure><h3><strong>Open Street Map</strong></h3><p><a href="https://www.openstreetmap.org/">Open Street Map</a> (OSM) is crowdsourced map that is free, accessible and editable by everyone. Open Streep Map supports data access via <a href="https://wiki.openstreetmap.org/wiki/Overpass_API">overpass APIs</a> that can be used to retrieve OSM data objects.</p><p>This article will not cover the overpass API query logic to get a sense of it, here is a sample code that will utilize Overpass API to retrieve commercial objects within a certain boundary:</p><pre>import requests<br>import json<br>import pandas as pd<br><br><br>def check_commercial(lg,lt):<br><br># Capture the long and lat from the function parameters and ensure they are converted<br>    long = str(lg)<br>    lat = str(lt)<br><br># List of known commercial labels<br>    w1 = &quot;commercial&quot;<br>    w2 = &quot;retail&quot;<br>    w3 = &quot;market&quot;<br>    w4 = &quot;marketplace&quot;<br>    #w5 = &quot;shop&quot;<br><br># Define the API endpoint and the OSM query that retrieve OSM object <br># node, way or relation within a circle (&quot;around&quot;) or 55m radius<br>    overpass_url = &quot;http://overpass-api.de/api/interpreter&quot;<br>    overpass_query = &quot;&quot;&quot;<br>    [out:json][timeout:25];<br>    (<br>      node(around:55, {}, {});<br>      way(around:55, {}, {});<br>      relation(around:55, {}, {});<br><br>    );out body;&gt;; out skel qt;<br>    &quot;&quot;&quot;<br>    response = requests.get(overpass_url,params={&#39;data&#39;: overpass_query.format(lat, long, lat, long, lat, long)})<br><br>    data = response.json()<br>    print(data)<br>    data = json.dumps(data)<br><br># Check if the returned objects has any of the commercial labels listed above<br>    if w1 in data.lower():<br>        return True<br>    elif w2 in data.lower():<br>        return True<br>    elif w3 in data.lower():<br>        return True<br>    elif w4 in data.lower():<br>        return True<br>    else:<br>        return False</pre><p>There are far more in Open Street Map Data but this is just to show a simple query that can build a huge dataset across certain cities or boundaries which can be used later in a machine learning project.</p><p>In the next parts of this series, I will dig deeper on how to build a full datasets that can be used for a ML pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4040bd080c2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Convolutional Neural Networks to detect fake images]]></title>
            <link>https://medium.com/@minafawzi/using-convolutional-neural-network-to-detect-fake-images-b4c536d44dc5?source=rss-62bde90d91e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c536d44dc5</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[image-manipulation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Mina Hanna]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 03:05:01 GMT</pubDate>
            <atom:updated>2022-01-04T03:21:51.216Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will walk you through the following:</p><ol><li>Overview</li><li>Quick introduction to Image Forensic</li><li>PS-Battle Dataset</li><li>Data Preprocessing</li><li>CNN implementation</li><li><strong>Overview</strong></li></ol><p>“An image is worth a thousand words” is the famous statement by Henrik Ibsen¹ which implies the value and the impact of an image and how a complex message can be delivered with one visual rather than a lengthy verbal description. On the other hand, a fake image can have a severe negative impact on the overall public respect and confidence in news and other social communications.</p><p>The other threatening fact about fake media (images, videos, and news) is the availability and sophistication of tools and platforms that helps to easily fabricate such fake media and distribute it. This project aims to utilize deep learning models to classify images and be able to detect forged images which was manipulated using different techniques.</p><p>This project focuses on Image tampering detection using Convolutional Neural Network (CNN) classification based on popular filters and analysis used in today’s forensic image analysis like Error Level Analysis, Noise Analysis and Gradient Analysis (more explanation below). CNN has been very popular in classifying images and through this project we will try to train a CNN to classify original and manipulated images.</p><p>You will need basic understanding of <a href="https://towardsdatascience.com/simple-introduction-to-convolutional-neural-networks-cdf8d3077bac">Convolutional Neural Networks</a>, training and optimization.</p><p><strong>Note: </strong><a href="https://www.linkedin.com/in/mojahid-osman-45ba85151">Mr. Mojahid Osman</a> helped with the coding and CNN training for this project.</p><p><strong>2. Quick introduction to Image Forensic</strong></p><p>Before digging into the details, lets have a crash course in image tampering. First of all, image tampering can be defined as <em>“adding or removing important features from an image without leaving any obvious traces of tampering”</em>². The following are some examples³:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*fhq9KHPyOJvuNcbdFbQTgg.png" /></figure><p>Detecting image forgery follows Locard’s exchange principle “whenever two objects come in contact, there will always be an exchange”⁴. While this principle was coined for the physical world, it is still applicable in the digital world as well where each digital camera, digitization technique, compression algorithm or image editing applications has its unique touch to the image which can help with forgery analysis. Each image tampering technique requires certain tools and analysis to reveal such exchange and detect the tampered image. There are different techniques known in the digital image forensic (check this: <a href="https://29a.ch/photo-forensics/#forensic-magnifier">https://29a.ch/photo-forensics/</a>), but the report here will focus on the following listed techniques which will be used throughout this project:</p><ol><li><a href="https://en.wikipedia.org/wiki/Error_level_analysis"><strong>Error Level Analysis</strong></a><strong> (ELA)</strong></li></ol><p>Based on the lossy nature of the JPG algorithm, where each save introduce new compression error, ELA algorithm is designed to detect different error rates in the image</p><p><strong>2.</strong><a href="https://en.wikipedia.org/wiki/Image_noise"><strong> Noise Analysis</strong></a></p><p>Each image has its own natural noise based on the lens, lighting condition or other digitalization processes and this technique depends on detecting a change of the natural noise due to tampering the image.</p><p><strong>3. </strong><a href="https://en.wikipedia.org/wiki/Image_gradient"><strong>Gradient Analysis</strong></a></p><p>Detecting changes in the brightness level across the image and detect any anomalies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*lJm-b0gF4ZR5MD776VTMFA.png" /><figcaption>This images shows original and tampered image in the top row, followed by ELA, Noise analysis and Gradient analysis images in subsequent rows. Image created by author but original images from the dataset referenced below</figcaption></figure><p>The following simple python functions that can create the different filters listed above using <a href="https://docs.opencv.org/4.x/index.html">openCV</a>:</p><pre><strong>def create_ela(</strong>img<strong>):<br>    &quot;&quot;&quot; This creates a new image that contains the ELA of an image by saving it as jpg with different quality and<br>    then retrieve a weighted absolute differentce between the original and saved image<br>    Keyword arguments:<br>    img -- image to be analyzed for Error Level Analysis<br>    &quot;&quot;&quot;<br>    </strong>cv2.imwrite<strong>(&quot;temp.jpg&quot;</strong>, img, <strong>[</strong>cv2.IMWRITE_JPEG_QUALITY, 95<strong>])<br>    </strong>img2 <strong>= </strong>cv2.imread<strong>(&quot;temp.jpg&quot;)<br>    </strong>cv2.imwrite<strong>(&quot;temp.jpg&quot;</strong>, img2, <strong>[</strong>cv2.IMWRITE_JPEG_QUALITY, 90<strong>])<br>    </strong>img2 <strong>= </strong>cv2.imread<strong>(&quot;temp.jpg&quot;)<br>    </strong>diff <strong>= </strong>15 <strong>* </strong>cv2.absdiff<strong>(</strong>img, img2<strong>)<br>    return </strong>diff</pre><pre><strong>def create_noise_analysis(</strong>img<strong>):<br>    &quot;&quot;&quot; This creates a new image that contains the noise of an image by smoothing the image via a Denoising filter<br>    and then subtract the denoised version from the original to keep only the noise<br>    Keyword arguments:<br>    img -- image to be analyzed for noise<br>    &quot;&quot;&quot;<br>    </strong>#img2 = cv2.medianBlur(img, 3)<br>    img2 <strong>= </strong>cv2.fastNlMeansDenoisingColored<strong>(</strong>img, h<strong>=</strong>1<strong>)<br>    return </strong>img <strong>- </strong>img2</pre><pre><strong>def </strong>create_grad<strong>(</strong>img<strong>):<br>    &quot;&quot;&quot; This creates a new image that contains the Gradient of an image by convoluting a vertical and horizontal kernels<br>    on the original image (Sobel 3x3) and then calculate the absolute value of the gradient magnetiude<br>    Keyword arguments:<br>    img -- image to be analyzed for Gradient Analysis<br>    &quot;&quot;&quot;<br>    </strong>scale <strong>= </strong>1<br>    delta <strong>= </strong>0<br>    ddepth <strong>= </strong>cv2.CV_16S<br>    src <strong>= </strong>cv2.GaussianBlur<strong>(</strong>img, <strong>(</strong>3, 3<strong>)</strong>, 0<strong>)<br>    </strong>gray <strong>= </strong>cv2.cvtColor<strong>(</strong>src, cv2.COLOR_RGB2GRAY<strong>)<br></strong></pre><pre>    grad_x <strong>= </strong>cv2.Sobel<strong>(</strong>gray, ddepth, 1, 0, ksize<strong>=</strong>3, scale<strong>=</strong>scale, delta<strong>=</strong>delta, borderType<strong>=</strong>cv2.BORDER_DEFAULT<strong>)<br>    </strong>grad_y <strong>= </strong>cv2.Sobel<strong>(</strong>gray, ddepth, 0, 1, ksize<strong>=</strong>3, scale<strong>=</strong>scale, delta<strong>=</strong>delta, borderType<strong>=</strong>cv2.BORDER_DEFAULT<strong>)</strong></pre><pre><strong>    </strong>abs_grad_x <strong>= </strong>cv2.convertScaleAbs<strong>(</strong>grad_x<strong>)<br>    </strong>abs_grad_y <strong>= </strong>cv2.convertScaleAbs<strong>(</strong>grad_y<strong>)<br>    </strong>grad <strong>=  </strong>cv2.addWeighted<strong>(</strong>abs_grad_x, 0.5, abs_grad_y, 0.5, 0<strong>)<br>    </strong><br>    temp <strong>= </strong>np.zeros_like<strong>(</strong>img<strong>)<br>    </strong>temp<strong>[:</strong>,<strong>:</strong>,0<strong>] = </strong>grad<br>    temp<strong>[:</strong>,<strong>:</strong>,1<strong>] = </strong>grad<br>    temp<strong>[:</strong>,<strong>:</strong>,2<strong>] = </strong>grad<br>    <strong>return </strong>temp</pre><p>The approach that will be followed in the rest of this project is to create 4 different image datasets based on the original and the three filters explained above and use them to train our CNN and create different trained models, at the end we will use the best performing models for the final prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*6MbsybagSL5Xi1Z9jfmWag.png" /><figcaption>Image created by the author</figcaption></figure><p><strong>3. PS-Battle Dataset</strong></p><p>The dataset used in this project is the PS-Battles dataset which is gathered from a large community of image manipulation enthusiasts and provides a basis for media derivation and manipulation detection in the visual domain. The dataset consists of 102&#39;028 images grouped into 11&#39;142 subsets, each containing the original image as well as a varying number of manipulated derivatives.⁵ which means that original photos are 11,142 and the photoshopped photos are 90,886.</p><p>Each original image has a corresponding sub directory (having the same image name) under the photoshopped directory that contains the manipulated version of this image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*TAwBUo8QP1gM5lyN18_lRA.png" /><figcaption>Image shows original image on the top followed by a set of the corresponding manipulated images in the dataset. Image was created by author based on one image in the PS-Battles dataset</figcaption></figure><p>For more details on how to download the data, take a look at the following: <a href="https://github.com/mojahid/DATS6203-Final-Project/tree/master/Data">https://github.com/mojahid/DATS6203-Final-Project/tree/master/Data</a></p><p><strong>4. Data Processing</strong></p><p>The Data_Preprocessing.py, contains some exploratory functions to navigate through the dataset, functions to delete unwanted extension, functions to move the images to a folder structure required by the tensorflow <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/image_dataset_from_directory">image_dataset_from_directory</a> and functions to apply ELA, Noise and Gradient filters and save the new dataset in similar structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/0*X3Z03aPQyLlf5P4C.png" /><figcaption>Image created by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/0*e-acB95bdpHl9iO9.png" /><figcaption>Image created by author</figcaption></figure><p>The following is the order of processing to prepare the data before training the CNN:</p><ol><li>Download the data as per the instructions in the Data section of the Github link above</li><li>Create Classes01, Classes02, Classes03 and Classes04 folders (can be any name but this is what is followed in the project)</li><li>Under each of the directories created in step 2, create two directories: “original” and “photoshopped” as per the above image</li><li>Use update_image_directories() to copy images from the downloaded folders to Classes01 folders (this function also exclude any unreadable or extra small images)</li><li>Create test folder structure: Test01, Test02, Test03 and Test04 and under each directory create the same two directories: “original” and “photoshopped”</li><li>Pick ~500 image from each class under ./Classes01/original and ./Classes01/photoshopped and paste them under ./Test01/original and ./Test01/photoshopped resp.</li><li>Call process_filter_on_data() 3 times to populate the new training dataset with appropriate filter applied</li><li>process_filter_on_data(&#39;ela&#39;, &#39;Classes02&#39;)</li><li>process_filter_on_data(&#39;noise&#39;, &#39;Classes03&#39;)</li><li>process_filter_on_data(&#39;lum&#39;, &#39;Classes04&#39;) This will create the new dataset with the filter applied.</li><li>Update the dir_src_1 and dir_src_2 in the process_filter_on_data() and repeat the process for the test data</li><li>process_filter_on_data(&#39;ela&#39;, &#39;Test02&#39;)</li><li>process_filter_on_data(&#39;noise&#39;, &#39;Test03&#39;)</li><li>process_filter_on_data(&#39;lum&#39;, &#39;Test04&#39;)</li><li>this will create the filtered images under the different sub-directories to be used in testing</li></ol><p>Here are the full pro-processing code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ea56d756528b20f2756bfd64b139a5e/href">https://medium.com/media/7ea56d756528b20f2756bfd64b139a5e/href</a></iframe><p><strong>4. CNN implementation</strong></p><p>This is the part where you will need to be familiar with Deep Neural Networks especially Convolutional Neural Networks. The following is the architecture of the network that is implemented using tensorflow as per the code block below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*zP_gkrnOH597indpeQP4Bw.png" /><figcaption>Image created by author</figcaption></figure><p>The code is straight forward here are some highlights:</p><ul><li>Since image are classified already in the folder structure, we can directly use the tensorflow utility <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/image_dataset_from_directory">image_dataset_from_directory </a>which loads the images based on the folder structure.</li><li>The utility provides parameters to specify the root directory, label mode definition which is categorical in our case (original and fake), normalization of image size</li><li>This code was running on a GPU and to leverage the GPU processing in the <a href="https://www.tensorflow.org/tutorials/images/data_augmentation">image augmentation</a> (image augmentation is a process to apply random transformations on the image like flipping or zooming to expose the model to more data points using the same original set), the augmentation was added as a layer so it will be processed during the training process that is executed on the GPU</li><li>The network architecture itself went through different phases with the final one below with standard practice of Conv layers, batch normalization and dropouts to decrease likelihood of overfitting</li><li>Relu is used as an activation (or transfer) function across all inner layer, last layer uses sigmoid (if loss function is binary cross entropy) or SofMax (if loss function is categorical cross entropy).</li><li>Adam optimizer was giving the best results with a small learning rate</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23d8c5ff9baea5f21ed89ffd4a5fcae5/href">https://medium.com/media/23d8c5ff9baea5f21ed89ffd4a5fcae5/href</a></iframe><p>This network was trained different times using the 4 different datasets created in the previous step (unfiltered image, ELA, Noise, Gradient) with various hyperparameters, the following table shows some of the readings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ghHWilCgn6BN-n3hCRF5TA.png" /><figcaption>Image created by author</figcaption></figure><ul><li>It was obvious that ELA images provided the best results</li><li>Re-training the network with the same dataset using different seed (shuffling training and validation data) achieved better results which means it overcame a local minimum reached in previous iterations</li><li>Finally, the code plots the historical performance of the accuracy and loss, here is an example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lfXpV1myf_XruYe_ECn-mQ.png" /><figcaption>Image provide by author</figcaption></figure><p>Final Note: Picking best model through hard voting or ensembling will be explained in another article but I added a lot of explanations to the code on the <a href="https://github.com/mojahid/DATS6203-Final-Project/tree/master/Code">github</a></p><p>References:</p><p>[1] <a href="https://en.wikipedia.org/wiki/A_picture_is_worth_a_thousand_words">https://en.wikipedia.org/wiki/A_picture_is_worth_a_thousand_words</a></p><p>[2]J. Fridrich, D. Soukal and J. Lukas, “Detection of Copy-move forgery in digital images”, in Digital Forensic Research Workshop, 2003.</p><p>[3]COMPREHENSIVE STUDY OF DIFFERENT TYPES IMAGE FORGERIES<strong> </strong><a href="http://www.ijstm.com/images/short_pdf/1440486816_229P.pdf">http://www.ijstm.com/images/short_pdf/1440486816_229P.pdf</a></p><p>[4]<a href="http://aboutforensics.co.uk/edmond-locard/">http://aboutforensics.co.uk/edmond-locard/</a></p><p>[5]<a href="https://arxiv.org/pdf/1804.04866.pdf">Silvan Heller, Luca Rossetto and Heiko Schuldt Department of Mathematics and Computer Science University of Basel, Switzerland</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c536d44dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>