Showing posts with label Encryption. Show all posts
Showing posts with label Encryption. Show all posts

Sunday, 27 August 2023

Unveiling AES-256 Encryption: Safeguarding Data with Advanced Security.

 In the realm of modern cryptography, ensuring the security of sensitive data is paramount. Advanced Encryption Standard (AES) has emerged as one of the most widely used encryption algorithms, trusted by governments, corporations, and individuals alike. Among its variants, AES-256 stands out as the strongest and most robust encryption option. In this blog, we'll delve into the workings of the AES-256 algorithm, its significance, and how it maintains data confidentiality.

Understanding AES Encryption

AES, also known as Rijndael, was established as a U.S. federal government standard in 2001. It was designed to replace its predecessor, the Data Encryption Standard (DES), which was deemed inadequate against modern threats due to its relatively short key length and algorithmic vulnerabilities.

AES operates as a symmetric encryption algorithm, meaning it employs the same key for both encryption and decryption processes. However, the security lies in the complexity of the algorithm itself, making it practically impossible for unauthorized parties to deduce the original data from the encrypted version, even with knowledge of the algorithm.

AES Key Lengths

AES comes in three standard key lengths: 128 bits, 192 bits, and 256 bits. The numbers correspond to the length of the cryptographic key used in the algorithm. AES-256, the focus of this blog, utilizes a 256-bit key length, providing an immense number of possible key combinations. This large key space contributes significantly to the algorithm's security, as it becomes computationally infeasible to launch brute-force attacks.

AES-256 Encryption Process

Key Expansion: The initial 256-bit encryption key is expanded into a set of round keys. Each round key is used in subsequent rounds of the encryption process.

Initial Round: The data is divided into blocks, typically 128 bits each. In the initial round, each byte of the block is combined with the corresponding byte of the round key through a process called "AddRoundKey."

Main Rounds: The number of main rounds depends on the key length. For AES-256, there are 14 main rounds. Each main round consists of four operations: SubBytes, ShiftRows, MixColumns, and AddRoundKey. These operations introduce confusion and diffusion, making the relationship between the key and the ciphertext highly complex.

  • SubBytes: Non-linear substitution of each byte in the block using a predefined substitution table (S-box).
  • ShiftRows: Byte rows are shifted by varying offsets to introduce diffusion.
  • MixColumns: Columns are mixed through a mathematical transformation, enhancing the algorithm's security.
  • AddRoundKey: The round key is XORed with the block's state, adding a layer of confusion.

Final Round: The final round is similar to the main rounds but lacks the MixColumns operation.

Output: After the final round, the transformed block is the encrypted ciphertext, which can be transmitted or stored securely.

Security and Strengths

AES-256's strength lies in its combination of substitution, permutation, and mixing operations, making it highly resistant to cryptanalysis. The large key size and the multiple rounds of transformation contribute to its robustness against various attacks, including brute force, differential, and linear attacks. The security of AES-256 is also underpinned by its ability to effectively dissipate statistical patterns, ensuring that even small changes in input data result in significant changes in the ciphertext.

Decryption Process

The decryption process is essentially the reverse of encryption, involving the application of inverse operations to retrieve the original plaintext from the ciphertext. The same round keys used in encryption are applied in reverse order.

Conclusion

The AES-256 algorithm represents the pinnacle of data security through its robust encryption process and utilization of a 256-bit key length. Its widespread adoption in critical applications demonstrates its effectiveness against modern cryptographic threats. Understanding the complexities of AES-256 not only underscores the importance of data protection but also highlights the intricate beauty of cryptography in the digital age.

Wednesday, 15 March 2023

Mobile Development: Safeguarding Against Hacking with Advanced Security Measures.

 In the rapidly evolving landscape of mobile development, security and protection against hacking have become paramount concerns. As mobile devices store and transmit vast amounts of sensitive user data, developers must implement robust security measures to thwart potential cyber threats. In this technical blog post, we will delve into the intricate aspects of mobile app security, exploring advanced techniques to fortify applications against hacking attempts.

Understanding Mobile Threats and Vulnerabilities:

To effectively counter hacking attempts, mobile developers must comprehend the diverse range of threats and vulnerabilities present in the mobile ecosystem. These include but are not limited to malware attacks, SQL injection, cross-site scripting (XSS), session hijacking, and insecure data storage. Staying updated on emerging threat vectors and common vulnerabilities is essential for devising appropriate security strategies.

Secure Coding Techniques:

Secure coding practices form the foundation of robust mobile app security. Developers must adhere to industry-standard secure coding guidelines, such as the OWASP Mobile Top 10, to prevent common attack vectors. Key practices include input validation, output encoding, parameterized queries, and secure session management. By utilizing cryptographic algorithms for data encryption and hashing, developers can protect sensitive data from unauthorized access.

Secure Authentication and Authorization Mechanisms:

Authentication and authorization mechanisms play a critical role in mobile app security. Developers should adopt strong authentication methods, such as OAuth 2.0 or OpenID Connect, along with secure password storage techniques like salted hashes. Implementing granular access control mechanisms and token-based authentication can prevent unauthorized access and session hijacking attacks.

Data Encryption and Secure Data Transmission:

To safeguard sensitive data at rest and in transit, mobile developers must employ robust encryption techniques. Encryption algorithms like AES (Advanced Encryption Standard) and RSA (Rivest-Shamir-Adleman) ensure data confidentiality. Additionally, secure data transmission can be achieved by implementing transport layer security (TLS) protocols, including SSL/TLS certificate pinning to protect against man-in-the-middle attacks.

Secure Storage of User Data:

Mobile applications often store user data locally on the device. Developers must ensure that this data is securely stored to prevent unauthorized access. Leveraging secure storage techniques like SQLCipher or encrypted key-value stores adds an additional layer of protection. Moreover, sensitive information, such as authentication tokens or API keys, should be stored in secure hardware containers like the Android KeyStore or Apple's Secure Enclave.

Regular Security Assessments and Code Reviews:

Periodic security assessments, including penetration testing and code reviews, are indispensable for identifying vulnerabilities in mobile applications. Conducting dynamic analysis, examining the application's attack surface, and simulating real-world attack scenarios help uncover potential weaknesses. Swift remediation of identified issues and the integration of security patches are crucial to maintaining a robust security posture.

Runtime Application Self-Protection (RASP):

Runtime Application Self-Protection (RASP) solutions can actively monitor and protect mobile apps from potential attacks. RASP tools employ techniques such as code instrumentation, behavior monitoring, and anomaly detection to detect and mitigate runtime threats. Integrating RASP into mobile apps can help detect and respond to attacks in real-time, enhancing overall security.

Secure Backend Infrastructure:

Securing the backend infrastructure is as important as securing the mobile app itself. Developers must ensure the use of secure APIs, validate and sanitize inputs, and employ strong access controls. Implementing Web Application Firewalls (WAFs), Intrusion Detection Systems (IDS), and Intrusion Prevention Systems (IPS) can help protect against server-side attacks and unauthorized access to backend resources.

Conclusion:

Building secure mobile applications requires a thorough understanding of the technical aspects of security and hacking. By following secure coding practices, implementing encryption and authentication mechanisms, securing data transmission, and conducting regular security assessments, developers can significantly mitigate risks. By prioritizing mobile app security from the development stage to ongoing maintenance, developers can build trustworthy applications that protect user data and provide a secure user experience.

Tuesday, 14 May 2019

HB Blog 167: How To Integrate Google Pay Payment Gateway In Android.

Google Pay  is a digital wallet platform and online payment system developed by Google to power in-app and tap-to-pay purchases on mobile devices, enabling users to make payments with Android phones, tablets or watches.

Google Pay uses Near Field Communication (NFC) to transmit card information facilitating funds transfer to the retailer. It replaces the credit or debit card chip and PIN or magnetic stripe transaction at point-of-sale terminals by allowing the user to upload these in the Google Pay wallet. It is similar to contactless payments already used in many countries, with the addition of two-factor authentication. The service lets Android devices wirelessly communicate with point of sale systems using a near field communication (NFC) antenna, host-based card emulation (HCE), and Android's security.

Google Pay takes advantage of physical authentications such as fingerprint ID where available. On devices without fingerprint ID, Google Pay is activated with a passcode. When the user makes a payment to a merchant, Google Pay does not send the credit or debit card number with the payment. Instead it generates a virtual account number representing the user's account information. This service keeps customer payment information private, sending a one-time security code instead of the card or user details.


Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//build.gradle
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.elitetechnologies.googlepay"
        minSdkVersion 20
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.razorpay:checkout:1.5.1'
}

//activity_main.xml
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00b1e1"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:orientation="vertical"
        android:gravity="center"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="110dp"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:layout_alignParentBottom="true"
                android:background="#E2E2E2"
                android:gravity="center"
                >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingTop="35dp"
                    android:paddingBottom="0dp"
                    android:textSize="12sp"
                    android:text="Order #RZP42"
                    />

            </LinearLayout>

            <ImageView
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_centerHorizontal="true"
                android:background="#FFFFFF"
                android:src="@mipmap/ic_launcher"
                />

        </RelativeLayout>

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:paddingTop="15dp"
            android:background="#f2f2f2"
            android:gravity="center"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:paddingTop="0dp"
                android:paddingBottom="5dp"
                android:textSize="20sp"
                android:text="Razorpay T-Shirt"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:paddingTop="0dp"
                android:paddingBottom="0dp"
                android:textSize="12sp"
                android:text="INR 1.00"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:paddingTop="5dp"
                android:paddingBottom="0dp"
                android:textSize="12sp"
                android:textStyle="italic"
                android:text="This is a real transaction"
                />

            <Button
                android:id="@+id/btn_pay"
                android:layout_width="wrap_content"
                android:layout_height="36dp"
                android:layout_marginTop="20dp"
                android:layout_marginBottom="20dp"
                android:layout_gravity="center_horizontal"
                android:paddingRight="20dp"
                android:paddingLeft="20dp"
                android:background="@drawable/green_button"
                android:textSize="14sp"
                android:textColor="#fcfcfc"
                android:text="Purchase"
                />

        </LinearLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:background="@drawable/secured_by_bg"
            android:textSize="12sp"
            android:textColor="#a1ddee"
            android:textStyle="italic"
            android:text="Secure Payments by Razorpay"
            />

    </LinearLayout>

</RelativeLayout>

//MainActivity.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
package com.elitetechnologies.googlepay;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.razorpay.Checkout;
import com.razorpay.PaymentResultListener;

import org.json.JSONObject;

public class MainActivity extends Activity implements PaymentResultListener {
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        /*
         To ensure faster loading of the Checkout form,
          call this method as early as possible in your checkout flow.
         */
        Checkout.preload(getApplicationContext());

        // Payment button created by you in XML layout
        Button button = (Button) findViewById(R.id.btn_pay);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPayment();
            }
        });
    }

    public void startPayment() {
        /*
          You need to pass current activity in order to let Razorpay create CheckoutActivity
         */
        final Activity activity = this;

        final Checkout co = new Checkout();

        try {
            JSONObject options = new JSONObject();
            options.put("name", "Razorpay Corp");
            options.put("description", "Demoing Charges");
            //You can omit the image option to fetch the image from dashboard
            options.put("image", "https://s3.amazonaws.com/rzp-mobile/images/rzp.png");
            options.put("currency", "INR");
            options.put("amount", "100");

            JSONObject preFill = new JSONObject();
            preFill.put("email", "test@razorpay.com");
            preFill.put("contact", "9876543210");

            options.put("prefill", preFill);

            co.open(activity, options);
        } catch (Exception e) {
            Toast.makeText(activity, "Error in payment: " + e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
            e.printStackTrace();
        }
    }

    /**
     * The name of the function has to be
     * onPaymentSuccess
     * Wrap your code in try catch, as shown, to ensure that this method runs correctly
     */
    @SuppressWarnings("unused")
    @Override
    public void onPaymentSuccess(String razorpayPaymentID) {
        try {
            Toast.makeText(this, "Payment Successful: " + razorpayPaymentID, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "Exception in onPaymentSuccess", e);
        }
    }

    /**
     * The name of the function has to be
     * onPaymentError
     * Wrap your code in try catch, as shown, to ensure that this method runs correctly
     */
    @SuppressWarnings("unused")
    @Override
    public void onPaymentError(int code, String response) {
        try {
            Toast.makeText(this, "Payment failed: " + code + " " + response, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "Exception in onPaymentError", e);
        }
    }
}

Thursday, 14 June 2018

HB Blog 156: Secure Communication For OkHttpClient Web-service API.

In cryptography, encryption is the process of encoding messages or information in such a way that only authorized parties can read it. We have seen this in my old blog HB Blog 41: Encryption And Decryption Process Of String. In that post we saw how to encrypt a string, lets see how to do similar process with web service for secure communication.
Here, we will use  java.security package for AES - 256 encryption and decryption during webservice call with OkHttpClient,
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//EncryptionUtility.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package com.harshalbenake.apiencryptionaes;

import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Encrypt and decrypt messages using AES 256 bit encryption that are compatible with AESCrypt-ObjC and AESCrypt Ruby.
 */
public final class EncryptionUtility {
    //AESCrypt-ObjC uses CBC and PKCS7Padding
    private static final String AES_MODE = "AES/CBC/ISO10126Padding";
    private static final String CHARSET = "UTF-8";

    /**
     * Encrypt and encode message using 256-bit AES with key generated from password.
     *
     * @param key     : secrete key
     * @param message the thing you want to encrypt assumed String UTF-8
     * @return Base64 encoded CipherText
     * @throws GeneralSecurityException if problems occur during encryption
     */
    public static String encrypt(final String key, String message, String IV)
            throws GeneralSecurityException {
        try {
            byte[] ivBytes = IV.getBytes();
            byte[] keyBytes = key.getBytes("UTF-8");

            final SecretKeySpec secreteKey = new SecretKeySpec(keyBytes, "AES");
            byte[] cipherText = encrypt(secreteKey, ivBytes, message.getBytes(CHARSET));
            String encoded = Base64.encodeToString(cipherText, Base64.NO_WRAP);

            return encoded;
        } catch (UnsupportedEncodingException e) {
            throw new GeneralSecurityException(e);
        }
    }


    /**
     * More flexible AES encrypt that doesn't encode
     *
     * @param key     AES key typically 128, 192 or 256 bit
     * @param iv      Initiation Vector
     * @param message in bytes (assumed it's already been decoded)
     * @return Encrypted cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message)
            throws GeneralSecurityException {
        byte[] cipherText = new byte[0];
        try {
            final Cipher cipher = Cipher.getInstance(AES_MODE);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
            cipherText = cipher.doFinal(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }

    /**
     * Decrypt and decode ciphertext using 256-bit AES with key generated from password
     *
     * @param key
     * @param base64EncodedCipherText the encrpyted message encoded with base64
     * @return message in Plain text (String UTF-8)
     * @throws GeneralSecurityException if there's an issue decrypting
     */
    public static String decrypt(final String key, String base64EncodedCipherText, String IV)
            throws GeneralSecurityException {

        try {
            byte[] ivBytes = IV.getBytes();
            byte[] keyBytes = key.getBytes("UTF-8");

            final SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
            byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.NO_WRAP);
            byte[] decryptedBytes = decrypt(secretKey, ivBytes, decodedCipherText);
            String message = new String(decryptedBytes, CHARSET);

            return message;
        } catch (UnsupportedEncodingException e) {
            throw new GeneralSecurityException(e);
        } catch (Exception e) {
            System.out.println(" Sys : " + e);
            throw new RuntimeException(e);
        }
    }


    /**
     * More flexible AES decrypt that doesn't encode
     *
     * @param key               AES key typically 128, 192 or 256 bit
     * @param iv                Initiation Vector
     * @param decodedCipherText in bytes (assumed it's already been decoded)
     * @return Decrypted message cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] decrypt(final SecretKeySpec key, final byte[] iv, final byte[] decodedCipherText)
            throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_MODE);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(decodedCipherText);
        return decryptedBytes;
    }
}

//OKHTTPService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.harshalbenake.apiencryptionaes;

import android.util.ArrayMap;
import android.util.Log;

import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * This class is used fto get and post service response to server using okhttp.
 */
public class OKHTTPService {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final String mStrUrl="Url";
    public static final String mStrRequestJson="RequestJson";
    public static final String mStrRequestEncoded="RequestEncoded";
    public static final String mStrResponseEncoded="ResponseEncoded";
    public static final String mStrResponseJson="ResponseJson";


    public OKHTTPService() {
    }

    /**
     * gets Ok Http Service
     *
     * @param strUrl
     * @param strJson
     * @return
     */
    public static HashMap<String,String> requestACallToServer(String strUrl, String strJson) {
        HashMap<String,String> hashMap=new HashMap<String, String>();
        try {
            System.out.println("OkHttp get Request: " + strJson);
            String strEncodedRequest = EncryptionUtility.encrypt("YourKey",strJson, "YourKey");            System.out.println("OkHttp get EncodedRequest: " + strEncodedRequest);
            RequestBody body = RequestBody.create(JSON, strEncodedRequest);
            Request request = new Request.Builder()
                    .url(strUrl)
                    .post(body)
                    .build();
            OkHttpClient.Builder builder = new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1));
            builder.connectTimeout(3, TimeUnit.MINUTES)
                    .writeTimeout(3, TimeUnit.MINUTES)
                    .readTimeout(3, TimeUnit.MINUTES);
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("HttpLogging", message);
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .protocols(Arrays.asList(Protocol.HTTP_1_1))
                    .addInterceptor(logging)
                    .connectTimeout(3, TimeUnit.MINUTES)
                    .writeTimeout(3, TimeUnit.MINUTES)
                    .readTimeout(3, TimeUnit.MINUTES)
                    .build();
            Response response = okHttpClient.newCall(request).execute();
            String strEncodedResponse = response.body().string();
            System.out.println("OkHttp get EncodedResponse: " + strEncodedResponse);
            String strResponse = EncryptionUtility.decrypt("YourKey", strEncodedResponse, "YourKey");            System.out.println("OkHttp get Response: " + strResponse);
            hashMap.put(mStrUrl,strUrl);
            hashMap.put(mStrRequestJson,strJson);
            hashMap.put(mStrRequestEncoded,strEncodedRequest);
            hashMap.put(mStrResponseEncoded,strEncodedResponse);
            hashMap.put(mStrResponseJson,strResponse.replaceAll("\\r\\n", ""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hashMap;
    }
}

//DataService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.harshalbenake.apiencryptionaes;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.util.HashMap;

/**
 * Data Service AsyncTask
 */
public class DataService extends AsyncTask<String, String, HashMap<String, String>> {
    MainActivity mContext;
    private ProgressDialog mProgressDialog;

    public DataService(MainActivity context) {
            this.mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (NetworkUtility.isOnline(mContext)) {
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();
        } else {
            Toast.makeText(mContext, "Not connected to Internet", Toast.LENGTH_SHORT).show();
            cancel(true);
        }
    }

    @Override
    protected HashMap<String, String> doInBackground(String... params) {
        HashMap<String, String> hashMap=null;
        if (!isCancelled()) {
            try {
                String strUrl ="xxxURLxxx";
                String strJsonData="xxxJsonDataxxx";
                 hashMap = OKHTTPService.requestACallToServer(strUrl,strJsonData.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return hashMap;
    }

    @Override
    protected void onPostExecute(HashMap<String, String> resultMap) {
        super.onPostExecute(resultMap);
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing() == true) {
                mProgressDialog.dismiss();
            }
            if(resultMap!=null && resultMap.size()>0){
                mContext.mtv_url.setText(OKHTTPService.mStrUrl+": "+resultMap.get(OKHTTPService.mStrUrl)+"\n");
                mContext.mtv_requestjson.setText(OKHTTPService.mStrRequestJson+": "+resultMap.get(OKHTTPService.mStrRequestJson)+"\n");
                mContext.mtv_requestencoded.setText(OKHTTPService.mStrRequestEncoded+": "+resultMap.get(OKHTTPService.mStrRequestEncoded)+"\n");
                mContext.mtv_responsencoded.setText(OKHTTPService.mStrResponseEncoded+": "+resultMap.get(OKHTTPService.mStrResponseEncoded)+"\n");
                mContext.mtv_responsejson.setText(OKHTTPService.mStrResponseJson+": "+resultMap.get(OKHTTPService.mStrResponseJson)+"\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}