<?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 italo gouveia on Medium]]></title>
        <description><![CDATA[Stories by italo gouveia on Medium]]></description>
        <link>https://medium.com/@italogouvei14?source=rss-b38cb3542e70------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J5OjselTCUUqDCCLOYH9tQ.jpeg</url>
            <title>Stories by italo gouveia on Medium</title>
            <link>https://medium.com/@italogouvei14?source=rss-b38cb3542e70------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:32:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@italogouvei14/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[Obfuscating code in Java]]></title>
            <link>https://systemweakness.com/obfuscating-code-in-java-f58079bd8f91?source=rss-b38cb3542e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/f58079bd8f91</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[obfuscation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[proguard]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[italo gouveia]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 21:58:01 GMT</pubDate>
            <atom:updated>2024-06-27T09:26:52.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p><strong>Definition of Obfuscation</strong>:</p><p>Obfuscation is a software programming technique that alters code to make it more challenging for humans to understand without affecting its functionality. This technique is commonly used in applications containing sensitive information or proprietary algorithms to deter unauthorized access and reverse engineering.</p><p>This is a technique largely utilized in applications that have sensitive information or complex algorithms that need to be protected from being unauthorized copied or suffering malicious attacks. This works by applying transformations in the original code, these transformations can include, names without sense, insertion of instructions that are not necessary or redundant, addition of dead codes, or updates on the logic structure of the program. It`s important to know that these changes don`t affect the workflow of the code.</p><p>Also, obfuscation has a lot of benefits for the developers, the main ones are the protection of the code from suffering reverse engineering, the protection as well sensitive information like passwords, cryptography keys, and proprietary algorithms, and the extraction by analysis of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PHtow2GZkXcEGlld.jpg" /><figcaption>Image: Reproduction/Internet</figcaption></figure><p><strong>Problems that obfuscation can bring</strong>:</p><p>While obfuscation offers significant benefits, it also introduces challenges. Excessive obfuscation can lead to diminished code readability and efficiency. For example, renaming variables excessively or applying aggressive code transformations may obscure the original logic to the point where debugging and maintenance become cumbersome. Furthermore, over-optimization through obfuscation can inadvertently increase application size or degrade runtime performance in certain scenarios. It’s crucial for developers to find a balance that protects their intellectual property without compromising code manageability and performance.</p><h3>Why Obfuscate Code in Java?</h3><p>So, you can talk! Why do I need to obfuscate my Java code? Because Java already compiles my code to a bytecode that it’s too hard to understand. Well, let’s work with the following example. Let’s suppose that I have this code on Java:</p><pre>package com.example.obfuscation.obfuscation_example;<br><br>import java.io.*;<br>import java.security.*;<br>import javax.crypto.*;<br>import java.util.Arrays;<br>import java.util.Objects;<br><br>public class EncryptDecryptRSA {<br><br>    public static final String ALGORITHM = &quot;RSA&quot;;<br>    public static final String PRIVATE_KEY_PATH = &quot;C:/keys/private.key&quot;;<br>    public static final String PUBLIC_KEY_PATH = &quot;C:/keys/public.key&quot;;<br><br>    public static void generateKeys() {<br>        try {<br>            KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);<br>            keyGen.initialize(1024);<br>            KeyPair keyPair = keyGen.generateKeyPair();<br><br>            File privateKeyFile = new File(PRIVATE_KEY_PATH);<br>            privateKeyFile.getParentFile().mkdirs(); // Ensure parent directory exists<br>            privateKeyFile.createNewFile();<br><br>            ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFile));<br>            privateKeyOS.writeObject(keyPair.getPrivate());<br>            privateKeyOS.close();<br><br>            File publicKeyFile = new File(PUBLIC_KEY_PATH);<br>            publicKeyFile.getParentFile().mkdirs(); // Ensure parent directory exists<br>            publicKeyFile.createNewFile();<br><br>            ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFile));<br>            publicKeyOS.writeObject(keyPair.getPublic());<br>            publicKeyOS.close();<br><br>        } catch (Exception e) {<br>            System.out.println(&quot;Exception occurred during key generation&quot;.concat(e.getMessage()));<br>        }<br>    }<br><br>    public static boolean checkIfKeysExist() {<br>        File privateKeyFile = new File(PRIVATE_KEY_PATH);<br>        File publicKeyFile = new File(PUBLIC_KEY_PATH);<br><br>        return privateKeyFile.exists() &amp;&amp; publicKeyFile.exists();<br>    }<br><br>    public static byte[] encrypt(String plainText, PublicKey key) {<br>        try {<br>            Cipher cipher = Cipher.getInstance(ALGORITHM);<br>            cipher.init(Cipher.ENCRYPT_MODE, key);<br>            return cipher.doFinal(plainText.getBytes());<br>        } catch (Exception e) {<br>            System.out.println(&quot;Exception occurred during encryption&quot;.concat(e.getMessage()));<br>            return null;<br>        }<br>    }<br><br>    public static String decrypt(byte[] encryptedText, PrivateKey key) {<br>        try {<br>            Cipher cipher = Cipher.getInstance(ALGORITHM);<br>            cipher.init(Cipher.DECRYPT_MODE, key);<br>            byte[] decryptedText = cipher.doFinal(encryptedText);<br>            return new String(decryptedText);<br>        } catch (Exception e) {<br>            System.out.println(&quot;Exception occurred during encryption&quot;.concat(e.getMessage()));<br>            return null;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        try {<br>            if (!checkIfKeysExist()) {<br>                generateKeys();<br>            }<br><br>            final String originalMessage = &quot;Example message&quot;;<br>            ObjectInputStream inputStream;<br><br>            inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_PATH));<br>            PublicKey publicKey = (PublicKey) inputStream.readObject();<br>            byte[] encryptedMessage = encrypt(originalMessage, publicKey);<br><br>            inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_PATH));<br>            PrivateKey privateKey = (PrivateKey) inputStream.readObject();<br>            String decryptedMessage = decrypt(encryptedMessage, privateKey);<br><br>            System.out.println(&quot;Original Message: &quot;.concat(originalMessage));<br>            System.out.println(&quot;Encrypted Message: &quot;.concat(Arrays.toString(encryptedMessage)));<br>            System.out.println(&quot;Decrypted Message: &quot;.concat(Objects.requireNonNull(decryptedMessage)));<br><br>        } catch (Exception e) {<br>            System.out.println(&quot;Exception occurred in main method&quot;.concat(e.getMessage()));<br>        }<br>    }<br>}</pre><p>So, now, I will compile this code, using this:</p><pre>javac EncryptDecryptRSA.java</pre><p>After the bytecode is generated, let’s look into that using the following command:</p><pre>javap -c EncryptDecryptRSA</pre><p>So now, we have the following content:</p><pre>Compiled from &quot;EncryptDecryptRSA.java&quot;<br>public class com.example.obfuscation.obfuscation_example.EncryptDecryptRSA {<br>  public static final java.lang.String ALGORITHM;<br><br>  public static final java.lang.String PRIVATE_KEY_PATH;<br><br>  public static final java.lang.String PUBLIC_KEY_PATH;<br><br>  public com.example.obfuscation.obfuscation_example.EncryptDecryptRSA();<br>    Code:<br>       0: aload_0<br>       1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V<br>       4: return<br><br>  public static void generateKeys();<br>    Code:<br>       0: ldc           #9                  // String RSA<br>       2: invokestatic  #11                 // Method java/security/KeyPairGenerator.getInstance:(Ljava/lang/String;)Ljava/security/KeyPairGenerator;<br>       5: astore_0<br>       6: aload_0<br>       7: sipush        1024<br>      10: invokevirtual #17                 // Method java/security/KeyPairGenerator.initialize:(I)V<br>      13: aload_0<br>      14: invokevirtual #21                 // Method java/security/KeyPairGenerator.generateKeyPair:()Ljava/security/KeyPair;<br>      17: astore_1<br>      18: new           #25                 // class java/io/File<br>      21: dup<br>      22: ldc           #27                 // String C:/keys/private.key<br>      24: invokespecial #29                 // Method java/io/File.&quot;&lt;init&gt;&quot;:(Ljava/lang/String;)V<br>      27: astore_2<br>      28: aload_2<br>      29: invokevirtual #32                 // Method java/io/File.getParentFile:()Ljava/io/File;<br>      32: invokevirtual #36                 // Method java/io/File.mkdirs:()Z<br>      35: pop<br>      36: aload_2<br>      37: invokevirtual #40                 // Method java/io/File.createNewFile:()Z<br>      40: pop<br>      41: new           #43                 // class java/io/ObjectOutputStream<br>      44: dup<br>      45: new           #45                 // class java/io/FileOutputStream<br>      48: dup<br>      49: aload_2<br>      50: invokespecial #47                 // Method java/io/FileOutputStream.&quot;&lt;init&gt;&quot;:(Ljava/io/File;)V<br>      53: invokespecial #50                 // Method java/io/ObjectOutputStream.&quot;&lt;init&gt;&quot;:(Ljava/io/OutputStream;)V<br>      56: astore_3<br>      57: aload_3<br>      58: aload_1<br>      59: invokevirtual #53                 // Method java/security/KeyPair.getPrivate:()Ljava/security/PrivateKey;<br>      62: invokevirtual #59                 // Method java/io/ObjectOutputStream.writeObject:(Ljava/lang/Object;)V<br>      65: aload_3<br>      66: invokevirtual #63                 // Method java/io/ObjectOutputStream.close:()V<br>      69: new           #25                 // class java/io/File<br>      72: dup<br>      73: ldc           #66                 // String C:/keys/public.key<br>      75: invokespecial #29                 // Method java/io/File.&quot;&lt;init&gt;&quot;:(Ljava/lang/String;)V<br>      78: astore        4<br>      80: aload         4<br>      82: invokevirtual #32                 // Method java/io/File.getParentFile:()Ljava/io/File;<br>      85: invokevirtual #36                 // Method java/io/File.mkdirs:()Z<br>      88: pop<br>      89: aload         4<br>      91: invokevirtual #40                 // Method java/io/File.createNewFile:()Z<br>      94: pop<br>      95: new           #43                 // class java/io/ObjectOutputStream<br>      98: dup<br>      99: new           #45                 // class java/io/FileOutputStream<br>     102: dup<br>     103: aload         4<br>     105: invokespecial #47                 // Method java/io/FileOutputStream.&quot;&lt;init&gt;&quot;:(Ljava/io/File;)V<br>     108: invokespecial #50                 // Method java/io/ObjectOutputStream.&quot;&lt;init&gt;&quot;:(Ljava/io/OutputStream;)V<br>     111: astore        5<br>     113: aload         5<br>     115: aload_1<br>     116: invokevirtual #68                 // Method java/security/KeyPair.getPublic:()Ljava/security/PublicKey;<br>     119: invokevirtual #59                 // Method java/io/ObjectOutputStream.writeObject:(Ljava/lang/Object;)V<br>     122: aload         5<br>     124: invokevirtual #63                 // Method java/io/ObjectOutputStream.close:()V<br>     127: goto          146<br>     130: astore_0<br>     131: getstatic     #74                 // Field java/lang/System.out:Ljava/io/PrintStream;<br>     134: ldc           #80                 // String Exception occurred during key generation<br>     136: aload_0<br>     137: invokevirtual #82                 // Method java/lang/Exception.getMessage:()Ljava/lang/String;<br>     140: invokevirtual #86                 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;<br>     143: invokevirtual #92                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>     146: return<br>    Exception table:<br>       from    to  target type<br>           0   127   130   Class java/lang/Exception<br><br>  public static boolean checkIfKeysExist();<br>    Code:<br>       0: new           #25                 // class java/io/File<br>       3: dup<br>       4: ldc           #27                 // String C:/keys/private.key<br>       6: invokespecial #29                 // Method java/io/File.&quot;&lt;init&gt;&quot;:(Ljava/lang/String;)V<br>       9: astore_0<br>      10: new           #25                 // class java/io/File<br>      13: dup<br>      14: ldc           #66                 // String C:/keys/public.key<br>      16: invokespecial #29                 // Method java/io/File.&quot;&lt;init&gt;&quot;:(Ljava/lang/String;)V<br>      19: astore_1<br>      20: aload_0<br>      21: invokevirtual #97                 // Method java/io/File.exists:()Z<br>      24: ifeq          38<br>      27: aload_1<br>      28: invokevirtual #97                 // Method java/io/File.exists:()Z<br>      31: ifeq          38<br>      34: iconst_1<br>      35: goto          39<br>      38: iconst_0<br>      39: ireturn<br><br>  public static byte[] encrypt(java.lang.String, java.security.PublicKey);<br>    Code:<br>       0: ldc           #9                  // String RSA<br>       2: invokestatic  #100                // Method javax/crypto/Cipher.getInstance:(Ljava/lang/String;)Ljavax/crypto/Cipher;<br>       5: astore_2<br>       6: aload_2<br>       7: iconst_1<br>       8: aload_1<br>       9: invokevirtual #105                // Method javax/crypto/Cipher.init:(ILjava/security/Key;)V<br>      12: aload_2<br>      13: aload_0<br>      14: invokevirtual #109                // Method java/lang/String.getBytes:()[B<br>      17: invokevirtual #113                // Method javax/crypto/Cipher.doFinal:([B)[B<br>      20: areturn<br>      21: astore_2<br>      22: getstatic     #74                 // Field java/lang/System.out:Ljava/io/PrintStream;<br>      25: ldc           #117                // String Exception occurred during encryption<br>      27: aload_2<br>      28: invokevirtual #82                 // Method java/lang/Exception.getMessage:()Ljava/lang/String;<br>      31: invokevirtual #86                 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;<br>      34: invokevirtual #92                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>      37: aconst_null<br>      38: areturn<br>    Exception table:<br>       from    to  target type<br>           0    20    21   Class java/lang/Exception<br><br>  public static java.lang.String decrypt(byte[], java.security.PrivateKey);<br>    Code:<br>       0: ldc           #9                  // String RSA<br>       2: invokestatic  #100                // Method javax/crypto/Cipher.getInstance:(Ljava/lang/String;)Ljavax/crypto/Cipher;<br>       5: astore_2<br>       6: aload_2<br>       7: iconst_2<br>       8: aload_1<br>       9: invokevirtual #105                // Method javax/crypto/Cipher.init:(ILjava/security/Key;)V<br>      12: aload_2<br>      13: aload_0<br>      14: invokevirtual #113                // Method javax/crypto/Cipher.doFinal:([B)[B<br>      17: astore_3<br>      18: new           #87                 // class java/lang/String<br>      21: dup<br>      22: aload_3<br>      23: invokespecial #119                // Method java/lang/String.&quot;&lt;init&gt;&quot;:([B)V<br>      26: areturn<br>      27: astore_2<br>      28: getstatic     #74                 // Field java/lang/System.out:Ljava/io/PrintStream;<br>      31: ldc           #117                // String Exception occurred during encryption<br>      33: aload_2<br>      34: invokevirtual #82                 // Method java/lang/Exception.getMessage:()Ljava/lang/String;<br>      37: invokevirtual #86                 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;<br>      40: invokevirtual #92                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>      43: aconst_null<br>      44: areturn<br>    Exception table:<br>       from    to  target type<br>           0    26    27   Class java/lang/Exception<br><br>  public static void main(java.lang.String[]);<br>    Code:<br>       0: invokestatic  #122                // Method checkIfKeysExist:()Z<br>       3: ifne          9<br>       6: invokestatic  #125                // Method generateKeys:()V<br>       9: new           #128                // class java/io/ObjectInputStream<br>      12: dup<br>      13: new           #130                // class java/io/FileInputStream<br>      16: dup<br>      17: ldc           #66                 // String C:/keys/public.key<br>      19: invokespecial #132                // Method java/io/FileInputStream.&quot;&lt;init&gt;&quot;:(Ljava/lang/String;)V<br>      22: invokespecial #133                // Method java/io/ObjectInputStream.&quot;&lt;init&gt;&quot;:(Ljava/io/InputStream;)V<br>      25: astore_1<br>      26: aload_1<br>      27: invokevirtual #136                // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;<br>      30: checkcast     #140                // class java/security/PublicKey<br>      33: astore_2<br>      34: ldc           #142                // String Example message<br>      36: aload_2<br>      37: invokestatic  #144                // Method encrypt:(Ljava/lang/String;Ljava/security/PublicKey;)[B<br>      40: astore_3<br>      41: new           #128                // class java/io/ObjectInputStream<br>      44: dup<br>      45: new           #130                // class java/io/FileInputStream<br>      48: dup<br>      49: ldc           #27                 // String C:/keys/private.key<br>      51: invokespecial #132                // Method java/io/FileInputStream.&quot;&lt;init&gt;&quot;:(Ljava/lang/String;)V<br>      54: invokespecial #133                // Method java/io/ObjectInputStream.&quot;&lt;init&gt;&quot;:(Ljava/io/InputStream;)V<br>      57: astore_1<br>      58: aload_1<br>      59: invokevirtual #136                // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;<br>      62: checkcast     #148                // class java/security/PrivateKey<br>      65: astore        4<br>      67: aload_3<br>      68: aload         4<br>      70: invokestatic  #150                // Method decrypt:([BLjava/security/PrivateKey;)Ljava/lang/String;<br>      73: astore        5<br>      75: getstatic     #74                 // Field java/lang/System.out:Ljava/io/PrintStream;<br>      78: ldc           #154                // String Original Message:<br>      80: ldc           #142                // String Example message<br>      82: invokevirtual #86                 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;<br>      85: invokevirtual #92                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>      88: getstatic     #74                 // Field java/lang/System.out:Ljava/io/PrintStream;<br>      91: ldc           #156                // String Encrypted Message:<br>      93: aload_3<br>      94: invokestatic  #158                // Method java/util/Arrays.toString:([B)Ljava/lang/String;<br>      97: invokevirtual #86                 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;<br>     100: invokevirtual #92                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>     103: getstatic     #74                 // Field java/lang/System.out:Ljava/io/PrintStream;<br>     106: ldc           #164                // String Decrypted Message:<br>     108: aload         5<br>     110: invokestatic  #166                // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;<br>     113: checkcast     #87                 // class java/lang/String<br>     116: invokevirtual #86                 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;<br>     119: invokevirtual #92                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>     122: goto          141<br>     125: astore_1<br>     126: getstatic     #74                 // Field java/lang/System.out:Ljava/io/PrintStream;<br>     129: ldc           #172                // String Exception occurred in main method<br>     131: aload_1<br>     132: invokevirtual #82                 // Method java/lang/Exception.getMessage:()Ljava/lang/String;<br>     135: invokevirtual #86                 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;<br>     138: invokevirtual #92                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>     141: return<br>    Exception table:<br>       from    to  target type<br>           0   122   125   Class java/lang/Exception<br>}</pre><p>Now that we have our Java code compiled, let’s explore why obfuscating it is crucial. Java compiles its source code into bytecode, an intermediate form that closely resembles the original source and contains significant amounts of meaningful information. This bytecode can be decompiled back into readable Java source code with relative ease, especially in scenarios where obfuscation techniques haven’t been applied effectively.</p><p>Bytecode in Java serves as an intermediate representation of the source code, maintaining much of its structure and logic. Unlike lower-level machine code, bytecode isn’t directly executable and retains symbolic references to classes, methods, and variables. Decompilers can use this information to reconstruct Java source code, albeit with limitations such as losing parameter names and local variables. This vulnerability makes bytecode susceptible to reverse engineering attempts, underscoring the importance of effective obfuscation.</p><p>When malicious parties attempt to decompile code, they often search for embedded strings in application or server logs. This unethical practice allows them to pinpoint specific functionalities within the codebase easily. Since bytecode stores strings in plain text, they can comb through all “.class” files for sensitive information. For instance, if an exception message like “invalid username” appears, it becomes a target for their search, potentially compromising security and intellectual property. Furthermore, visible strings in the graphical user interface and other labels may also be exploited to gain unauthorized insights into the application’s operations.</p><p>Obfuscation mitigates these risks by obscuring bytecode, making it harder for humans to comprehend and reverse-engineer. This process involves removing details such as debugging information (e.g., variable tables, line numbers) and renaming packages, classes, and methods. While debugging information aids in matching bytecode to its original source during decompilation, it’s optional for code execution. Despite alterations made by advanced obfuscators, the obfuscated bytecode remains valid and functional while presenting a formidable barrier to reverse engineering.</p><p>Advanced obfuscators may go beyond renaming and structural alterations to insert dummy code snippets that do not affect functionality but obfuscate the code’s logical flow. Despite these modifications, obfuscated bytecode retains its intended functionality and remains executable.</p><p>Obfuscators analyze Java class files, apply predefined rules to modify internal structures, and save them as new files. These transformed files behave identically to the originals during execution but pose a significant challenge to reverse engineering due to their altered format and obscured logic.</p><p>Now, you understand that it’s too important to obfuscate code in Java right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*vuJIqCJef0g2QFAV.gif" /><figcaption>Image: Reproduction/Internet</figcaption></figure><p>Another Benefit of obfuscation is that can optimize code size and improve runtime performance by removing unused code and renaming classes, methods, and variables. Follow how it does:</p><ol><li>Firstly, one significant benefit of obfuscation is the removal of unused code paths and resources. During the obfuscation process, tools analyze the application’s codebase and eliminate portions of code that are unreachable or redundant. This reduction in code size directly translates to improved runtime performance because the runtime environment has fewer instructions to process and manage.</li><li>Secondly, obfuscation often involves renaming classes, methods, and variables to shorter, less descriptive names. While this primarily serves to obscure the code’s logic and hinder reverse engineering, it can also positively impact performance. Smaller and more concise identifiers can lead to reduced memory usage and faster execution times, especially in environments with limited resources or under heavy load(thinking of decreasing costs of cloud storage usage for example).</li><li>Additionally, obfuscation tools may optimize bytecode structure and organization, leading to more streamlined execution paths. By restructuring the code’s flow and eliminating unnecessary branches or checks, obfuscation can enhance the efficiency of critical operations within the application.</li></ol><p>Overall, while the primary goal of obfuscation is to enhance security by making code harder to understand and reverse engineer, it also offers tangible performance benefits. These include reducing code size, optimizing memory usage, and improving runtime execution speed, which is advantageous in environments where performance optimization is crucial. Thus, obfuscation serves a dual purpose of both safeguarding intellectual property and enhancing the operational efficiency of software applications.</p><p>Oh, let’s take a break here, take a cup of water, stretch your legs and Breathe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VfCvN3ksNUIcCuEr" /><figcaption>Image: reproduction/internet</figcaption></figure><h3>Techniques of Obfuscation</h3><ul><li><strong>Classes, Variables, and Functions Renaming:</strong> This technique involves replacing classes, variables, and function names with nonsensical names, making the code harder to understand. For example, a class named UserService, which is clear and descriptive, might be renamed to something like a, b, or c. Similarly, method names like getUserById could be renamed to a, b, or c, while variable names such as userId could become a, b, or c.</li><li><strong>Insertion of Unnecessary Instructions:</strong> This technique adds unnecessary instructions to the code, such as empty loops or redundant mathematical operations. These instructions do not affect the software’s functionality but complicate code comprehension.</li><li><strong>Addition of Dead Code:</strong> This technique involves adding code segments that will never be executed during the program’s execution. These code segments do not affect the software’s functionality but make code analysis more difficult.</li><li><strong>Modification of Program’s Logical Structure:</strong> This technique involves altering the program’s logical structure to make it harder to understand. For example, the code can be reorganized to obscure control flows and conditional structures.</li><li><strong>Code Simplification</strong>: Highlight techniques that remove debugging information, comments, and formatting to make the code more compact and less readable, that can be: <strong>Removal of Debugging Information</strong>(This helps reduce the size of the compiled code and removes information that aids reverse engineering.), <strong>Comment Removal</strong>(This reduces the amount of textual information available in the source code, making it less informative to someone analyzing it.)<strong>, Formatting Minimization </strong>(This not only reduces file size but also makes the code harder to read by removing visual cues like indentation and spacing.)<strong>, Consolidation of Redundant Code</strong>(This simplifies the codebase by reducing the number of lines and improving maintainability without affecting functionality.), <strong>Inline Expansion</strong>(This optimization technique can improve runtime performance by eliminating the overhead associated with function calls.), <strong>Dead Code Elimination</strong>(By eliminating dead code, the size of the executable or bytecode is reduced, and the codebase becomes cleaner and more efficient). Theese techniques</li><li><strong>String Encryption</strong>: Have methods to encrypt strings used in the code to prevent straightforward extraction of sensitive information, like <strong>Symmetric Encryption with AES (Advanced Encryption Standard), Obfuscation with Custom Encryption Algorithms, Dynamic Decryption at Runtime, Key Management, and Secure Storage, Integration with Code Obfuscation Techniques, </strong>and other ways to encrypt that I will not spend a lot of time explaining this here, because that’s not the objective, if you like, you can follow to other articles about this specific topic, or ask in Chat GPT for some information about these techniques that it will give you some summary.</li></ul><h3>Popular Java Obfuscation Tools</h3><p>Among the available obfuscators, popular choices include Klassmaster, ProGuard, Retro Guard, Dash-O, and JShrink. Klassmaster and Retro Guard are paid options, while ProGuard, Dash-O, and JShrink are free.</p><p><strong>Klassmaster</strong> stands out among paid options for its comprehensive feature set, including removing debug information, name obfuscation, string encoding, inserting corrupted code, eliminating unused code, bytecode optimization, and unique control flow alteration capabilities. It’s a recommended investment for robust code obfuscation, typically priced around $200.</p><p><strong>ProGuard</strong>, a leading free obfuscator, offers essential functionalities like removing debug information, name obfuscation, and eliminating unused code. However, it lacks features such as string encoding and control flow alteration.</p><p>For our study case, we will use ProGuard:</p><h3>ProGuard</h3><p>ProGuard is primarily used for code shrinking, optimization, and obfuscation.</p><p><strong>Key Features of ProGuard:</strong></p><ul><li><strong>Automatic Optimization</strong>: ProGuard optimizes bytecode by removing unused code and applying performance enhancements, leading to significant improvements in application performance.</li><li><strong>Customizable Configuration</strong>: Developers can tailor ProGuard’s behavior using configuration files, specifying which classes, methods, or fields should be preserved from optimization or obfuscation.</li><li><strong>Library Support</strong>: ProGuard seamlessly processes commonly used Java libraries and frameworks, ensuring consistent application of optimizations and obfuscations across dependencies.</li><li><strong>Build Tool Integration</strong>: ProGuard integrates smoothly with popular Java build tools like Ant, Maven, and Gradle, facilitating automated integration into build pipelines for optimization and obfuscation.</li><li><strong>Compatibility</strong>: ProGuard supports Java bytecode versions up to Java 11, ensuring compatibility with modern Java applications and libraries.</li><li><strong>Guardian Classes</strong>: ProGuard can generate guardian classes to protect obfuscated code from reflection-based attacks, enhancing overall security measures.</li></ul><h3>Best Practices and Considerations</h3><p>Although obfuscation tools generally do a good job, we must be cautious when using them, as there are situations where problems can arise due to obfuscation. Among these, we need to pay attention to dynamically loaded classes using Class.forName() or ClassLoader.loadClass(), passing the original class name that is not obfuscated. Reflection can also pose issues since it requires compile-time knowledge of method and field names. Additionally, serialization problems and violations of EJB patterns that require methods with specific names and signatures can occur.</p><p><strong>Best Practices and Considerations</strong></p><p>While obfuscation tools generally enhance security, caution is advised:</p><ul><li><strong>Selective Obfuscation</strong>: Obfuscate critical parts of the code selectively to maintain readability for debugging and maintenance purposes.</li><li><strong>Testing and Verification</strong>: Thoroughly test applications post-obfuscation to ensure expected behavior and performance.</li><li><strong>Legal Implications</strong>: Consider legal aspects and licensing requirements when obfuscating third-party libraries or components.</li></ul><p>Now, it’s time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*H7oM6LR0v9ZZAP8x" /><figcaption>image: reproduction/internet</figcaption></figure><h3>Case Study:</h3><p>Now, we are applying ProGuard to this Project.<br>We will use the following Maven plugin:</p><p>First of all, create a simple maven project, here I will use a spring boot maven project so simple, after I create this project, I will add to my pom.xml the following plugin in the plugins section inside the build section:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;com.github.wvengen&lt;/groupId&gt;<br>    &lt;artifactId&gt;proguard-maven-plugin&lt;/artifactId&gt;<br>    &lt;executions&gt;<br>     &lt;execution&gt;<br>      &lt;phase&gt;package&lt;/phase&gt;<br>      &lt;goals&gt;&lt;goal&gt;proguard&lt;/goal&gt;&lt;/goals&gt;<br>     &lt;/execution&gt;<br>    &lt;/executions&gt;<br>....<br>&lt;/plugin&gt;</pre><p>Let me explain a little bit about this structure, first of all, I’m using the proguard.maven.plugin hosted on com.github.wvengen, and in the executions section, I’m specifying the phase package from maven that executes on goal the Proguard. This part it’s straightforward, so, following, we have the configurations section:</p><pre>&lt;plugin&gt;<br>...<br>  &lt;configuration&gt;<br>       &lt;obfuscate&gt;true&lt;/obfuscate&gt;<br>       &lt;injar&gt;${project.build.finalName}.jar&lt;/injar&gt;<br>       &lt;outjar&gt;${project.build.finalName}-small.jar&lt;/outjar&gt;<br>       &lt;outputDirectory&gt;${project.build.directory}&lt;/outputDirectory&gt;<br>       &lt;proguardInclude&gt;${basedir}/proguard.conf&lt;/proguardInclude&gt;<br>       &lt;injarNotExistsSkip&gt;true&lt;/injarNotExistsSkip&gt;<br>       &lt;options&gt;<br>        &lt;option&gt;-libraryjars &amp;lt;java.home&amp;gt;/lib/&lt;/option&gt;<br>       &lt;/options&gt;<br>       &lt;libs&gt;<br>        &lt;lib&gt;${java.home}/jmods/java.base.jmod&lt;/lib&gt;<br>        &lt;lib&gt;${java.home}/lib/jrt-fs.jar&lt;/lib&gt;<br>       &lt;/libs&gt;<br>  &lt;/configuration&gt;<br>...<br>&lt;/plugin&gt;</pre><p>Here we have to specify the configurations that we would like to be executed by Proguard, so at first, we use<strong> </strong>&lt;obfuscate&gt;true&lt;/obfuscate&gt;to specify that we will obfuscate the project. &lt;injar tag we put the name of the jar that is generated by the clean package before be obfuscated, we are repackaging the project with Proguard in the next steps, so for this reason, we put &lt;outjar&gt; with a similar name with something to differentiate like &quot;-small” or &quot;-obfuscated”suffix. We specify &lt;outputDirectory&gt;to let Proguard know where the directory of the application is built.</p><p>&lt;proguardInclude&gt;<strong> </strong>It`s an essential thing here, we are specifying to Proguard that we will include Proguard configuration files that will include each important specific configuration for our projects, think that the configurations on pom.xml are the most general configurations that will be very similar for any project that you will work with Proguard, and this &quot;proguard.conf” it will contain a lot of other configs that are only specific to your current project, we will take a look at this file soon.</p><p>&lt;injarNotExistsSkip&gt;true&lt;/injarNotExistsSkip&gt;just say to skip when doesn’t find a jar on dependencies of our project.<strong> </strong>&lt;options&gt; section we only put one option that we will let Proguard know where it’s our library jars on Java home. We will do the same for the libs section but specify the java.base.jmod file and jrt-fs.jar file (if you are using Java 8 or before, you will need to specify in another way) something like:</p><pre>&lt;libs&gt;<br>    &lt;lib&gt;${java.home}/jre/lib/rt.jar&lt;/lib&gt;<br>    &lt;lib&gt;${java.home}/jre/lib/jsse.jar&lt;/lib&gt;<br>    &lt;lib&gt;${java.home}/jre/lib/jce.jar&lt;/lib&gt;<br>    &lt;!-- Add more libraries as needed for your application --&gt;<br>&lt;/libs&gt;</pre><p>this are the configuration steps.</p><p>Finally, you need to put the dependencies section specifying the Proguard version, at the time, I’m using version <strong>7.2.2</strong>:</p><pre>&lt;plugin&gt;<br>...<br>  &lt;dependencies&gt;<br>       &lt;dependency&gt;<br>        &lt;groupId&gt;com.guardsquare&lt;/groupId&gt;<br>        &lt;artifactId&gt;proguard-base&lt;/artifactId&gt;<br>        &lt;version&gt;${proguard.version}&lt;/version&gt;<br>       &lt;/dependency&gt;<br>   &lt;/dependencies&gt;<br>....<br>&lt;/plugin&gt;</pre><p>After I add another plugin configuration for the Maven spring project to define my main method, this is very important to recognize where the start of the application is to work the project after the jar is obfuscated.</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;executions&gt;<br>     &lt;execution&gt;<br>      &lt;goals&gt;<br>       &lt;goal&gt;repackage&lt;/goal&gt;<br>      &lt;/goals&gt;<br>      &lt;configuration&gt;&lt;mainClass&gt;com.example.obfuscation.obfuscation_example.ObfuscationExampleApplication&lt;/mainClass&gt;&lt;/configuration&gt;<br>     &lt;/execution&gt;<br>    &lt;/executions&gt;<br>   &lt;/plugin&gt;</pre><p>Remember that I said before that we will repackage the application? It’s very necessary to specify here, the goals of the spring-boot-maven-plugin, and in configuration, I’m specifying the main class to Proguard recognize the entry point of my application.</p><p>So now, we will have something like this in our build section:</p><pre> &lt;build&gt;<br>  &lt;plugins&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;com.github.wvengen&lt;/groupId&gt;<br>    &lt;artifactId&gt;proguard-maven-plugin&lt;/artifactId&gt;<br>    &lt;executions&gt;<br>     &lt;execution&gt;<br>      &lt;phase&gt;package&lt;/phase&gt;<br>      &lt;goals&gt;&lt;goal&gt;proguard&lt;/goal&gt;&lt;/goals&gt;<br>     &lt;/execution&gt;<br>    &lt;/executions&gt;<br>    &lt;configuration&gt;<br>     &lt;obfuscate&gt;true&lt;/obfuscate&gt;<br>     &lt;injar&gt;${project.build.finalName}.jar&lt;/injar&gt;<br>     &lt;outjar&gt;${project.build.finalName}-small.jar&lt;/outjar&gt;<br>     &lt;outputDirectory&gt;${project.build.directory}&lt;/outputDirectory&gt;<br>     &lt;proguardInclude&gt;${basedir}/proguard.conf&lt;/proguardInclude&gt;<br>     &lt;injarNotExistsSkip&gt;true&lt;/injarNotExistsSkip&gt;<br>     &lt;options&gt;<br>      &lt;option&gt;-libraryjars &amp;lt;java.home&amp;gt;/lib/&lt;/option&gt;<br>     &lt;/options&gt;<br>     &lt;libs&gt;<br>      &lt;lib&gt;${java.home}/jmods/java.base.jmod&lt;/lib&gt;<br>      &lt;lib&gt;${java.home}/lib/jrt-fs.jar&lt;/lib&gt;<br>     &lt;/libs&gt;<br>    &lt;/configuration&gt;<br>    &lt;dependencies&gt;<br>     &lt;dependency&gt;<br>      &lt;groupId&gt;com.guardsquare&lt;/groupId&gt;<br>      &lt;artifactId&gt;proguard-base&lt;/artifactId&gt;<br>      &lt;version&gt;${proguard.version}&lt;/version&gt;<br>     &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>   &lt;/plugin&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;executions&gt;<br>     &lt;execution&gt;<br>      &lt;goals&gt;<br>       &lt;goal&gt;repackage&lt;/goal&gt;<br>      &lt;/goals&gt;<br>      &lt;configuration&gt;&lt;mainClass&gt;com.example.obfuscation.obfuscation_example.ObfuscationExampleApplication&lt;/mainClass&gt;&lt;/configuration&gt;<br>     &lt;/execution&gt;<br>    &lt;/executions&gt;<br>   &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br> &lt;/build&gt;</pre><p>Now, it’s time to configure our Proguard file proguard.conf.I created the file on the root directory of the project and added the following lines:</p><pre># proguard.conf<br><br># Keep public classes and their main methods (if any)<br>-keep public class com.example.obfuscation.obfuscation_example.EncryptDecryptRSA {<br>    public static void main(java.lang.String[]);<br>}<br><br># Keep serialization-related classes and members<br>-keepclassmembers class * implements java.io.Serializable {<br>    static final long serialVersionUID;<br>    private static final java.io.ObjectStreamField[] serialPersistentFields;<br>    private void writeObject(java.io.ObjectOutputStream);<br>    private void readObject(java.io.ObjectInputStream);<br>    java.lang.Object writeReplace();<br>    java.lang.Object readResolve();<br>}</pre><p>-keep it a reserved word to specify to Proguard that these classes are important to our project run, I’m saying that I’m using this in some place of my business logic code <strong>(remember the class that we saw previously on this article EncryptDecryptRSA)</strong>. We use here to specify the main method inside this class(different from our main spring method) by the pattern: <br>-keep + declaration of the type of filepublic class+ Package com.example.obfuscation.obfuscation_example.EncryptDecryptRSA+ open and close keys operator that is used to define the content inside of this class we need to keep here we specify the main method with your parameters public static void main(java.lang.String[]);</p><p>-keepclassmembersworks similarly, but we specify the members inside a class that it`s necessary for our application to run class * implements java.io.Serializablewe pass how it’s declared the class, using wildcard *that we are saying here to Proguard, that we need all classes that implement java.io.Serializable. We open and close keys to inform the necessary methods and properties, here I put:</p><pre>static final long serialVersionUID;<br>private static final java.io.ObjectStreamField[] serialPersistentFields;<br>private void writeObject(java.io.ObjectOutputStream);<br>private void readObject(java.io.ObjectInputStream);<br>java.lang.Object writeReplace();<br>java.lang.Object readResolve();</pre><p>see that I don`t need to specify the implementation only the method signature. If I want, I can remove all these lines and put the wildcard operator * to say to Proguard that I need all from these classes, but I like to explain the two ways.</p><p>Finally added these configurations, you can run a: mvn clean package on your project and you will have a generated jar obfuscated.</p><h3><strong>Checking the generated obfuscated files:</strong></h3><ol><li><strong>Extract the JAR File:</strong> Use any zip extraction tool (like WinRAR, 7-Zip, or command-line tools) to extract the contents of the JAR file to a directory on your system.</li></ol><pre>mkdir jar_contents<br>cd jar_contents<br>jar xf path/to/your-jar-file.jar</pre><p><strong>Look for Obfuscated Classes:</strong> Navigate through the extracted directory structure to find the .class files. Obfuscated classes typically have names that are not easily recognizable (such as single characters or random strings) compared to their original names in the source code.</p><pre>cd jar_contents<br>find . -name &quot;*.class&quot; <br>(or just go to the file if this find doesn`t work)</pre><p>Finally, we will have this obfuscated code, if you go to your file system and search the file, you will see this:</p><p>�������A���w�x�z�{�|�}�~��������������������������������������������� ��V</p><p>�</p><p>�D</p><p>�</p><p>�E</p><p>��B</p><p>��H</p><p>��J</p><p>��P</p><p>��U</p><p>��B</p><p>��?</p><p>��@</p><p>��X</p><p>��A</p><p>��F</p><p>��[</p><p>��W</p><p>��O</p><p>��&gt;</p><p>��C</p><p>��G</p><p>��L</p><p>��Q</p><p>��R</p><p>��K</p><p>��M</p><p>��T</p><p>��Z</p><p>��Y</p><p>��I</p><p>��N</p><p>��S �v�b �v�g �v�h �v�i �v�o �v�r ���p ���t ���b ���l ���c ���s ���c ���_ ���d ���m ���n ���^ ���\ ���` ���a ���f ���e ���c ���� ���o ���] ���j ���q ���k�()Ljava/io/File;�()Ljava/lang/Object;�()Ljava/lang/String;�()Ljava/security/KeyPair;�()Ljava/security/PrivateKey;�()Ljava/security/PublicKey;�()V�()Z�()[B�(I)V�(ILjava/security/Key;)V�(Ljava/io/File;)V�(Ljava/io/InputStream;)V�(Ljava/io/OutputStream;)V�&amp;(Ljava/lang/Object;)Ljava/lang/Object;�(Ljava/lang/Object;)V�&amp;(Ljava/lang/String;)Ljava/lang/String;�4(Ljava/lang/String;)Ljava/security/KeyPairGenerator;�)(Ljava/lang/String;)Ljavax/crypto/Cipher;�(Ljava/lang/String;)V�/(Ljava/lang/String;Ljava/security/PublicKey;)[B�([B)Ljava/lang/String;�([B)V�([B)[B�0([BLjava/security/PrivateKey;)Ljava/lang/String;�([Ljava/lang/String;)V�&lt;init&gt;�C:/keys/private.key�C:/keys/public.key�Code�Decrypted Message: �Encrypted Message: �Example message�$Exception occurred during encryption�(Exception occurred during key generation�!Exception occurred in main method�Ljava/io/PrintStream;�!Original Message: Example message�RSA�</p><p>StackMapTable�[B�[Ljava/lang/String;�a�close�=com/example/obfuscation/obfuscation_example/EncryptDecryptRSA�concat�</p><p>createNewFile�doFinal�exists�generateKeyPair�getBytes� getInstance�</p><p>getMessage�</p><p>getParentFile�</p><p>getPrivate� getPublic�init�</p><p>initialize� java/io/File�java/io/FileInputStream�java/io/FileOutputStream�java/io/ObjectInputStream�java/io/ObjectOutputStream�java/io/PrintStream�java/lang/Exception�java/lang/Object�java/lang/String�java/lang/System�java/security/KeyPair�java/security/KeyPairGenerator�java/security/PrivateKey�java/security/PublicKey�java/util/Arrays�java/util/Objects�javax/crypto/Cipher�main�mkdirs�out�println�</p><p>readObject�requireNonNull�toString� writeObject�!�</p><p>��������v�b��y��������*��0������</p><p>���p��y���M�����’</p><p>��&lt;YM+��=,*��3��;�M��,��/��2��.������������� ��������</p><p>���t��y���S�����-</p><p>��&lt;YM+��=,*��;K��Y*��1�M��,��/��2��.������������� �������� ���u��y��e����/��Y��”K��Y��”L*��$��+��$�������</p><p>��7YK���8*��6L��Y��”YK��%��&amp;W*��#W��Y��Y*��(��+YK+��4��-*��,��Y��”YK��%��&amp;W*��#W��Y��Y*��(��+YK+��5��-*��,��K��*��/��2��.��Y��Y��’��)YK��*��K*�� L��Y��Y��’��)YK��*��K+*��!K�� ��.��+��9��2��.��*��:����2��.�K��*��/��2��.���*�����������������&amp;@��}���h���</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*wF6WEJ6GxDRePtsK" /><figcaption>image: reproduction/internet</figcaption></figure><p>Here I cannot do a good indentation because the medium code block tool does not recognize more like code, see how it’s hardest to do reverse engineering now. Almost impossible.</p><p>So, you now have your code obfuscated, practice by yourself, check documentation and the options that are possible to you.</p><p>We will discuss these possibilities in a future article.</p><h3><strong>Summary</strong>:</h3><p>In this article, we covered:</p><ul><li><strong>What is Obfuscation</strong> and its role in protecting Java code.</li><li><strong>ProGuard</strong>, a powerful tool for Java code obfuscation.</li><li><strong>Best Practices</strong> for implementing obfuscation techniques.</li><li><strong>Case Study</strong> using ProGuard in a Maven project to secure Java applications.</li></ul><h3><strong>Next Steps</strong></h3><p>Explore advanced configurations in ProGuard, such as custom optimizations and further obfuscation techniques tailored to specific project needs. Stay tuned for more insights and updates on cybersecurity practices and tools.</p><h3>How to Stay Updated:</h3><ul><li><strong>Follow Security Blogs and Publications</strong>: Stay informed on emerging obfuscation techniques.</li><li><strong>Attend Security Conferences and Webinars</strong>: Participate in events discussing cybersecurity advancements.</li><li><strong>Engage with the Security Community</strong>: Join forums and communities dedicated to cybersecurity discussions.</li><li><strong>Monitor Vendor Updates</strong>: Stay updated on software updates and new security features.</li><li><strong>Continuous Learning</strong>: Keep learning through courses and certifications to stay abreast of evolving cybersecurity trends.</li></ul><h3><strong>Share Your Experience:</strong></h3><p>Have you implemented obfuscation in your projects? Share your approach and experiences in the comments. If this article has been helpful, leave a comment and like it! Follow for more updates and articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m0yBVIfqz0sHjSG5.jpg" /><figcaption>Image: Reproduction/Internet</figcaption></figure><h3>References</h3><p>Repository from this project:</p><p><a href="https://github.com/italo-gouveia/obfuscation-example">https://github.com/italo-gouveia/obfuscation-example</a></p><p>Other references:</p><ul><li><a href="https://github.com/wvengen/proguard-maven-plugin">https://github.com/wvengen/proguard-maven-plugin</a></li><li><a href="https://www.guardsquare.com/manual/quickstart">https://www.guardsquare.com/manual/quickstart</a></li><li><a href="https://wvengen.github.io/proguard-maven-plugin/">https://wvengen.github.io/proguard-maven-plugin/</a></li><li><a href="https://www.zdnet.com/article/a-question-of-security-what-is-obfuscation-and-how-does-it-work/">https://www.zdnet.com/article/a-question-of-security-what-is-obfuscation-and-how-does-it-work/</a></li><li><a href="https://www.freecodecamp.org/news/make-your-code-secure-with-obfuscation/">https://www.freecodecamp.org/news/make-your-code-secure-with-obfuscation/</a></li><li><a href="https://en.wikipedia.org/wiki/Obfuscation">https://en.wikipedia.org/wiki/Obfuscation</a></li><li><a href="https://owasp.org/www-community/controls/Bytecode_obfuscation">https://owasp.org/www-community/controls/Bytecode_obfuscation</a></li><li><a href="https://owasp.org/www-project-mobile-top-10/2016-risks/m9-reverse-engineering">https://owasp.org/www-project-mobile-top-10/2016-risks/m9-reverse-engineering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f58079bd8f91" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/obfuscating-code-in-java-f58079bd8f91">Obfuscating code in Java</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criando minha primeira API REST com Node.js, Express, Sequelize, e MySQL para cadastro de usuários]]></title>
            <link>https://medium.com/italo-gouveia/criando-minha-primeira-api-rest-com-node-js-express-sequelize-e-mysql-para-cadastro-de-usu%C3%A1rios-1131a3e44ba1?source=rss-b38cb3542e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/1131a3e44ba1</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[italo gouveia]]></dc:creator>
            <pubDate>Wed, 06 Jun 2018 16:33:33 GMT</pubDate>
            <atom:updated>2018-06-06T16:33:33.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Resultado de imagem para wallpaper nodejs" src="https://cdn-images-1.medium.com/proxy/1*aeWo6e6FC8InJwBl3TmpDw.jpeg" /></figure><p>Neste artigo estarei descrevendo uma das muitas formas para se construir uma API Web utilizando os recursos do protocolo REST. Utilizaremos aqui o NodeJS, MySQL e alguns dos pacotes do Node.</p><p>Antes de mais nada vamos criar o nosso banco e a tabela utilizando os seguintes comandos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*_KqJhBmLXWY86US4jj42jg.png" /><figcaption>Comando para criação do banco e da tabela no MySQL.</figcaption></figure><h3>Instalar as libs necessárias globalmente e criação do projeto:</h3><p>Utilizando o terminal de sua preferência, faça a instalação dos seguintes pacotes:</p><blockquote><em>npm install -g sequelize-cli express-generator</em></blockquote><p>Logo em seguida iremos criar o nosso projeto usando o Express para gerar a estrutura inicial do projeto, no terminal, digite o seguinte comando:</p><blockquote><em>express –view=pug projeto_rest</em></blockquote><p>Após concluir, você terá a seguinte estrutura dentro da pasta de instalação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*4jszFwDDzU0IfLlSfmqhhg.png" /><figcaption>Estrutura inicial de pastas e arquivos do projeto.</figcaption></figure><h3>Instalando as dependências do projeto:</h3><p>Feito isso, navegue até a pasta e instale as dependências do projeto usando o comando:</p><blockquote><em>cd projeto_rest &amp;&amp; npm install</em></blockquote><p>Ainda no terminal, você deverá instalar os pacotes do Sequelize e do MySQL utilizando o seguinte comando:</p><blockquote><em>npm install — save sequelize –save mysql2</em></blockquote><p>Seu projeto já estará com a estrutura pronta e agora podemos ir para a programação.</p><h3><strong>Configurando o banco:</strong></h3><p>Antes de configurarmos o arquivo do banco vamos inicializar o Sequelize com o comando <em>sequelize init</em>, ao utilizar esse comando, a CLI do Sequelize irá gerar nas pasta do seu projeto os seguintes diretórios: migrations, seeders, config e models, juntamente com o arquivo config.json dentro da pasta config.</p><blockquote><strong>***Atenção***</strong></blockquote><p>Se você estiver usando o Windows será necessário fazer um pequeno ajuste no arquivo index.js que se encontra na pasta model, navegue até ele e mude o seguinte trecho:</p><blockquote><em>var config = require(__dirname + ‘/..\config\config.json’)[env];</em></blockquote><blockquote>para: <em>var config = require(__dirname + ‘/../config/config.json’)[env];</em></blockquote><p>Agora sim, iremos configurar nosso banco de dados MySQL no projeto, abra o arquivo config.json na pasta config do projeto, dentro dele você encontrará a seguinte estrutura:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*5UoHBRjdL-IyJZIZcenLDA.png" /><figcaption>Arquivo de configurações do banco de dados.</figcaption></figure><p>Para configurar o seu banco basta substituir os dados, se a porta que o seu MySQL estiver rodando for diferente de 3306, você deverá adicionar essa configuração ao config também após configurar com os seus dados, você terá algo parecido com isso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*vhs0E492VoUjPCqay5xK7w.png" /><figcaption>Arquivo de configurações do banco alterado.</figcaption></figure><h3><strong>Criando os models e migrations:</strong></h3><p>Para criar os arquivos de model e migration do User você pode gerar pelo comando no terminal, ou escrever o código em um arquivo dentro das respectivas pastas models e migrations, mostrarei aqui o comando para gerar a estrutura inicial e depois farei algumas alterações no model:</p><blockquote><em>sequelize model:create — name User –attributes id:int,name:string,cpf:string,date_of_birth:date</em></blockquote><p>Coloque o comando inteiro em uma linha apenas.</p><p>Após o Sequelize gerar os arquivos você terá as seguintes estruturas:</p><p><strong>Migration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*sDnV5CUfTq6ZaltZKsyUBQ.png" /><figcaption>Arquivo de migration.</figcaption></figure><p><strong>Model:</strong></p><p>Irei alterar alguns campos no Model para adaptá-lo melhor ao projeto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*glZPUrHRxFOGUFYJ9WACMQ.png" /><figcaption>Arquivo de model.</figcaption></figure><p>Note um detalhe importante, as chaves como id, name, cpf e date_of_birth representam as colunas na tabela usuários no banco de dados, e são seguidas dos seus tipos utilizando o objeto DataTypes através do tipo do atributo desejado, como String, decimal etc. Onde encontra-se o timestamps a sua propriedade será false, nessa parte do código o valor só será diferente se você for fazer migrações, como esse não é o foco do artigo iremos ao próximo passo.</p><p><strong>DAO/ Route:</strong></p><p>No novo modelo do Express 4 deve-se ter um arquivo de rota para chama-lo no arquivo app.js/server.js. Ressalto aqui que não aplicarei o modelo MVC de fato, mas farei uma adaptação do mesmo. Veja abaixo um exemplo do arquivo DAO/route que deve ser criado na pasta routes do seu projeto (se você criou pelo comando do terminal basta substituir o código), primeiro, vamos detalhar os requires do arquivo:</p><blockquote><em>var express = require(‘express’);</em></blockquote><blockquote><em>var router = express.Router();</em></blockquote><blockquote><em>var model = require(‘../models/index’);</em></blockquote><p>Veja aqui que fizemos a requisição do modulo do Express e logo em seguida da função Router do Express que irá mapear as requisições para nosso projeto, e em seguida temos o require à um model chamado index que contêm as configurações do nosso banco de dados requisitando-as ao arquivo config.json, veja abaixo sua estrutura:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*0rkq5a-IMwLvnrRdHz964Q.png" /><figcaption>Arquivo index.js responsável por ler o config e gerenciar as conexões.</figcaption></figure><p>Ok, visto isso vamos voltar para as rotas. Em primeiro lugar temos o GET, com ele direcionamos a requisição ao serviço para nos exibir todos os usuários cadastrados, primeiramente o router.get define aqui que todas as requisição do tipo GET que tiverem a mesma URI do primeiro parâmetro, no nosso caso apenas ”/” irão buscar a função contida em sua estrutura, na função de call-back passamos como parâmetro a requisição (dados e cabeçalho), chamamos então a variável de conexão a banco model acessando o método findAll de User. Caso haja resultados, a resposta à requisição retornará um JSON contendo os dados obtidos na consulta e retornado que não houve nenhum erro, caso contrário, captura o erro ocorrido e passa como resposta da requisição. A estrutura é bem parecida para os outros métodos, tendo apenas algumas alterações:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*0l0bnjnEpKqpVqcT4upD3A.png" /><figcaption>Método GET.</figcaption></figure><p>Seguimos então com o POST, que será responsável por controlar as inserções de dados no banco, sua estrutura será essa logo abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*hDqNljvIW0zWatYywIENGg.png" /><figcaption>Método POST.</figcaption></figure><p>Perceba que a diferença é que aqui passamos como parâmetro da requisição os dados name, cpf e date_of_birth que vem no body da requisição, utilizamos o método create passando os mesmos e caso dê certo, o método retornará mensagem de sucesso e o código de status 201, se der erro, haverá uma captura do erro e será exibido ao usuário.<br> <br> Em terceiro faremos o PUT que irá redirecionar as requisições de alteração dos dados no banco de acordo com o seguinte método:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*kasrus9czqwP9Im74wFX9w.png" /><figcaption>Método PUT.</figcaption></figure><p>A uri da requisição foi alterada para receber um parâmetro que será o id do objeto à ser alterado, temos também os dados semelhante ao post e por fim executamos o método update, retornando mensagem de sucesso e código de status 201, ou os detalhes do erro, caso aconteça.</p><p>Por fim temos o delete, que também deverá receber no parâmetro da uri o id que será deletado do banco, através do método destroy passando o id como parâmetro do where, a função irá retornar código 201 e mensagem de usuário deletado com sucesso, ou retornará a descrição do erro, caso ocorra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*VYZVzfpdfIBYuddEcSCcxw.png" /><figcaption>METODO DELETE.</figcaption></figure><p>Finalmente devemos exportar esse modulo do router para utilizarmos no arquivo app.js, veja logo abaixo que fiz algumas alterações no arquivo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*KKXq9AIWWJ5pgTIf-BxADw.png" /><figcaption>App.js, arquivo inicial do nosso serviço que servirá como o controller de uris.</figcaption></figure><p>Utilizando o comando app.use() defino nos parâmetros o objeto da rota e a uri que deverá ser utilizada para requisitar essa rota. Também coloquei aqui uma implementação de CORS, não irei falar sobre, mas futuramente estarei escrevendo um artigo sobre o assunto. Há alguns métodos para captura de erros para os caso de 404 e 500, por fim o comando app.listen serve para definir a porta que o servidor irá rodar.</p><h3><strong>Rodando a api:</strong></h3><p>Para rodar a nossa api através do terminal localize a pasta do projeto e use o comando:</p><blockquote><em>node app</em></blockquote><p>Se tudo der certo, irá aparecer na saída do terminal o console.info que deixamos na chamada da função do app.listen.</p><h3><strong>Vamos testar então:</strong></h3><p>Já que não temos nenhum dado no banco irei fazer o POST primeiro, na interface do postman, tenha a estrutura abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*U8onPiDqWGobujGi25Kj-w.png" /><figcaption>Método POST no Postman.</figcaption></figure><p>No body da requisição informe os dados desejados utilizando a formatação raw do tipo application/json. O resultado será exibido logo à baixo retornando dados criados, mensagem de sucesso e código 201.</p><p>Farei outro post aqui para termos 2 dados, veja agora o método GET com os dois usuários:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*M1s84OK2HnDPJwmDVDnG9w.png" /><figcaption>Método GET no Postman.</figcaption></figure><p>Vejam que o GET já me retorna os valores cadastrados e o status 200.</p><p>Vamos alterar o usuário João Ferreira Leite através do PUT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*uQNCB7cFQSdrIYBOAZRQuQ.png" /><figcaption>Método PUT no Postman.</figcaption></figure><p>Mensagem de sucesso e status 201. Veja que aqui passamos na uri o parâmetro 3 indicando o id que alteramos.</p><p>Por último, faremos a operação de exclusão:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*nzucpiizE_ocCsT7DQ4a9A.png" /><figcaption>Método DELETE no Postman.</figcaption></figure><p>Mensagem de sucesso e código de status 201. Novamente utilizamos o id como parâmetro informando qual usuário iriamos deletar.</p><p>E aí está, sua primeira API REST utilizando o NodeJS juntamente com Sequelize, Express e MySQL, espero que tenham gostado do artigo, deixem o seu feedback para que eu esteja melhorando nos próximos artigos e trazendo um melhor conteúdo para ajudar a comunidade. Meu intuito aqui é única e exclusivamente trazer maior facilidade para todos que assim como eu estão começando em suas carreiras como desenvolvedores, ou até para profissionais experientes mas que nunca tenham trabalhado com NodeJS, obrigado a todos, e até a próxima.</p><h3>Guia de Referências:</h3><p>· Arjunphp, build a restful api using node express Sequelize. Disponível em: &lt;<a href="https://arjunphp.com/build-restful-api-using-node-express-sequelize/">https://arjunphp.com/build-restful-api-using-node-express-sequelize/</a>&gt; Data Acesso em 06 de junho de 2018.</p><p>· Sequelize JS, documentation. Disponível em: &lt;<a href="http://docs.sequelizejs.com/">http://docs.sequelizejs.com/</a>&gt; Acesso em 06 de junho de 2018.</p><p>· MySQL, documentation. Disponível em: &lt;<a href="https://dev.mysql.com/doc/">https://dev.mysql.com/doc/</a>&gt; Acesso em 06 de junho de 2018.</p><p>· Express 4, documentation. Disponível em: &lt;<a href="http://expressjs.com/en/4x/api.html">http://expressjs.com/en/4x/api.html</a>&gt; Acesso em 06 de junho de 2018.</p><p>· NodeJS, documentation. Disponível em: &lt;<a href="https://nodejs.org/en/docs/">https://nodejs.org/en/docs/</a>&gt; Acesso em 06 de junho de 2018.</p><p>· Postman, documentation. Disponível em: &lt;<a href="https://www.getpostman.com/docs/v6/">https://www.getpostman.com/docs/v6/</a>&gt; Acesso em 06 de junho de 2018.</p><p>· GitHub, API completa feita por mim. Disponível em: &lt;https://github.com/italo-gouveia/Javascript-and-Frameworks/tree/master/NodeJS/projeto_rest&gt; Acesso em 06 de junho de 2018.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1131a3e44ba1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/italo-gouveia/criando-minha-primeira-api-rest-com-node-js-express-sequelize-e-mysql-para-cadastro-de-usu%C3%A1rios-1131a3e44ba1">Criando minha primeira API REST com Node.js, Express, Sequelize, e MySQL para cadastro de usuários</a> was originally published in <a href="https://medium.com/italo-gouveia">Italo Gouveia</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>