How does the app prevent packet capture

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .

foreword

App security is very important, especially data security. But we know that tools such as Charles can capture packets of App's network requests. If our data is not encrypted, this information will be removed and extracted, and will be used by criminals. There are many ways to ensure data security. Today, we will briefly talk about how to prevent packet capture in a few simple steps.

text

When we make a network request, we generally establish a connection through the openConnection of the URL. The code is as follows:

URLConnection conn = url.openConnection()
复制代码

In fact, there is also a version of the openConnection function, which can pass in a proxy object. The code is as follows:

public URLConnection openConnection(Proxy proxy)
    throws java.io.IOException
复制代码

In this way, we pass in a Proxy.NO_PROXY when establishing a connection through this function, which can achieve the effect of preventing packet capture. For example, packet capture tools such as Charles cannot see our link information. The code is as follows

URLConnection conn = url.openConnection(Proxy.NO_PROXY)
复制代码

The official description of Proxy.NO_PROXY is as follows:

/**
 * A proxy setting that represents a {@code DIRECT} connection,
 * basically telling the protocol handler not to use any proxying.
 * Used, for instance, to create sockets bypassing any other global
 * proxy settings (like SOCKS):
 * <P>
 * {@code Socket s = new Socket(Proxy.NO_PROXY);}
 *
 */
public final static Proxy NO_PROXY = new Proxy();

// Creates the proxy that represents a {@code DIRECT} connection.
private Proxy() {
    type = Type.DIRECT;
    sa = null;
}
复制代码

We can see that NO_PROXY is actually a Proxy object whose type attribute is DIRECT. There are three types of this type:

  • DIRECT
  • HTTP
  • SOCKS

The official description is as follows:

public enum Type {
    /**
     * Represents a direct connection, or the absence of a proxy.
     */
    DIRECT,
    /**
     * Represents proxy for high level protocols such as HTTP or FTP.
     */
    HTTP,
    /**
     * Represents a SOCKS (V4 or V5) proxy.
     */
    SOCKS
};
复制代码

This is because it is a direct connection, so there is no proxy. Therefore, tools such as Charles cannot catch the packet, which ensures the security of the data to a certain extent.

Of course, this method only fails to capture packets through the proxy, but it is still possible to capture packets directly through routing.

Guess you like

Origin juejin.im/post/7078077090506997767