Showing posts with label Hack. Show all posts
Showing posts with label Hack. Show all posts

Saturday, 16 September 2023

Cloaked in Pixels: Unveiling the Art and Science of Steganography.

 In a world where data privacy and security are of paramount importance, the age-old art of steganography continues to intrigue and fascinate. Steganography, derived from the Greek words "steganos" (meaning concealed) and "graphy" (meaning writing), is the practice of hiding information within other non-secret data. Unlike encryption, which scrambles the content of a message, steganography focuses on concealing the existence of the message itself. In this blog, we'll delve into the fascinating world of steganography, exploring its history, techniques, and modern-day applications.

A Brief History of Steganography

Steganography has a long and storied history, dating back to ancient times. The earliest recorded use of steganography can be traced to Herodotus, the ancient Greek historian, who described how a message was tattooed on a messenger's shaved head, which was then allowed to grow back before dispatching him. The message could only be read when the messenger's hair was shaved again. Steganography was also employed during World War II when secret messages were hidden within the text of innocent-looking letters.

Techniques of Steganography

Image Steganography: One of the most common forms of steganography is hiding information within digital images. This technique exploits the least significant bit (LSB) of the pixel data in an image, making subtle changes that are imperceptible to the human eye. By altering the LSB of the pixel's color values, messages or data can be embedded within an image. Tools like Photoshop or specialized steganography software make this process relatively straightforward.

Audio Steganography: Similar to image steganography, audio steganography involves concealing information within audio files. The human ear is less sensitive to minor alterations in audio data, making it possible to hide messages within sound files. This technique has applications in the transmission of covert information or watermarking audio content.

Text Steganography: In text-based steganography, information is hidden within a text document by using various methods such as altering spacing, font styles, or even inserting extra words or characters. The recipient is usually provided with a key or a set of instructions to extract the hidden message.

Video Steganography: Video files can also be used as a carrier for hidden information. By subtly altering frames or embedding data in video streams, steganographers can conceal information within videos. This can be useful in surveillance, digital watermarking, and content authentication.

Modern Applications of Steganography

  • Digital Watermarking: Steganography is commonly used in digital watermarking, where hidden information is embedded within multimedia files to establish ownership or verify authenticity. For instance, photographers may embed their copyright information into their images, making it easier to track unauthorized use.
  • Secure Communication: Steganography can be employed to ensure secure communication channels. By hiding messages within seemingly innocuous files, individuals can exchange sensitive information without arousing suspicion. This can be vital in scenarios where encryption alone might attract unwanted attention.
  • Cybersecurity: Steganography is also a tool used by both attackers and defenders in the realm of cybersecurity. Cybercriminals may use steganography to conceal malware within legitimate files, making it harder for security systems to detect and quarantine malicious software. Conversely, cybersecurity experts can use steganalysis techniques to detect hidden threats and vulnerabilities.
  • Data Smuggling: Criminal organizations may use steganography to smuggle data across borders or evade law enforcement. By embedding illicit information within legal documents or media files, they can transport data discreetly.
How it works

Steganography is a technique used to hide information within a cover medium (such as an image, audio file, or text) in such a way that the presence of the hidden information is difficult to detect. Let's delve into the technical details of how steganography works:

Embedding Data:
  • Select a Cover Medium: The first step in steganography is choosing a cover medium. This could be an image, audio file, video, or even text.
  • Convert Data: The information you want to hide, often referred to as the "payload" or "secret message," needs to be converted into a format suitable for embedding within the cover medium. This may involve encoding or compressing the data, depending on the steganography method used.
  • Embedding Algorithm: Steganography techniques use various algorithms to embed the secret data within the cover medium. 
Here's a simplified explanation of how this works for image steganography, which is one of the most common forms:

Image Steganography Example:
  • Pixel Manipulation: In image steganography, the cover image is typically in a format like BMP, PNG, or JPEG. Each pixel in the image consists of color components (usually red, green, and blue, represented as RGB values). In many cases, the least significant bit (LSB) of each color component is used for embedding.
  • Replacing LSBs: To embed data, you replace the LSBs of the pixel values with bits from your secret message. For example, if the original pixel value in the red channel is 11010011, and you want to embed "101," you would change it to 11010010 (changing the least significant bit from 1 to 0).
  • Capacity and Detection: The amount of data you can hide depends on the size of the cover image and how much you're willing to alter it. Embedding too much data can degrade the quality of the cover image, making it easier to detect. Thus, steganographers often balance between hiding data and maintaining cover medium quality.
Extracting Hidden Data:
  • Extraction Algorithm: To retrieve the hidden data from a steganographic medium, you need an extraction algorithm. This algorithm is aware of the method used for embedding and knows where to look (e.g., LSBs in the case of image steganography).
  • Scanning: The extraction algorithm scans the cover medium, looking for patterns or indicators that reveal the presence of hidden data. In image steganography, it examines the LSBs of the pixel values.
  • Reconstructing Data: Once the extraction algorithm identifies the hidden bits, it reconstructs the original secret message.
It's important to note that the success of steganography depends on several factors:
  • The choice of cover medium: Some media types are better suited for steganography due to their complexity and the ability to hide changes effectively.
  • Embedding method: Different steganographic techniques and algorithms have varying levels of complexity and effectiveness. More advanced techniques are harder to detect.
  • Analysis tools: The availability of steganalysis tools and techniques to detect hidden data is an ongoing challenge for steganographers.
  • Payload size vs. detectability: There's always a trade-off between the amount of data you can hide and the likelihood of detection. Embedding too much data can make it easier to detect the hidden information.
In summary, steganography is a technique that leverages the imperceptibility of small changes in data to hide information within a cover medium. The success of steganography depends on careful selection of the cover medium, embedding method, and the ability to avoid detection by steganalysis techniques.

Conclusion

Steganography, the ancient art of concealing messages within other data, continues to play a significant role in the modern world. Its applications range from securing sensitive communications to protecting digital assets and even aiding in criminal activities. While it's a powerful tool for those who understand and use it, it also poses challenges for security professionals tasked with detecting hidden information.

As technology continues to advance, so does steganography. Researchers and security experts must remain vigilant and develop new techniques and tools for detecting and countering this covert form of communication. In a world where information is power, the age-old art of steganography reminds us that sometimes, the most valuable secrets are hidden in plain sight.

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.

Friday, 1 September 2017

HB Blog 143: Implementing Video Call using Sinch Android SDK.

Introduction

The Sinch SDK is a product that makes adding voice calling and/or instant messaging to mobile apps easy. It handles all the complexity of signalling and audio management while providing you the freedom to create a stunning user interface.
Refer the below link for complete sample code:-

Download Sample Code

First time setup

Below is a step-by-step guide on setting up the Sinch SDK for the first time.

Register an Application
1.    Register a Sinch Developer account at http://www.sinch.com/signup.
2.    Setup a new Application using the Dashboard where you can then obtain an Application Key and an Application Secret.

Download
The Sinch SDK can be downloaded at www.sinch.com/download/. It contains: the library aar, this user guide, reference documentation, and sample apps for calling and instant messaging.

Add the Sinch library
The Sinch SDK library is distributed in AAR format. To use it in your project choose File -> New -> New Module -> Import .JAR/.AAR Package option

Permissions
A minimum set of permissions are needed for the app to use the Sinch SDK. These are specified in the AndroidManifest.xml file. If the calling functionality will be used, all five permissions listed here are needed. However, if the calling functionality isn’t used, the last three (RECORD_AUDIO, MODIFY_AUDIO_SETTINGS and READ_PHONE_STATE) can be omitted.
1
2
3
4
5
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Note: By default, the Sinch SDK hangs up any Sinch call if the regular phone app has an active call. This functionality requires the permission READ_PHONE_STATE. However, if this default functionality isn’t wanted, turn it off by calling sinchClient.getCallClient().setRespectNativeCalls(false); and the permission READ_PHONE_STATE is not needed.

Sinch client

The SinchClient is the Sinch SDK entry point. It is used to configure the user’s and device’s capabilities, as well as to provide access to feature classes such as the CallClient, MessageClient and AudioController.

Create a SinchClient
1
2
3
4
5
6
7
8
// Instantiate a SinchClient using the SinchClientBuilder.
android.content.Context context = this.getApplicationContext();
SinchClient sinchClient = Sinch.getSinchClientBuilder().context(context)
.applicationKey("<application key>")
.applicationSecret("<application secret>")
.environmentHost("sandbox.sinch.com")
.userId("<user id>")
.build();
The Application Key and Application Secret are obtained from the Sinch Developer Dashboard. The User ID should uniquely identify the user on the particular device.
Note: All listener callbacks emitted from the Sinch SDK are invoked on the same thread that the call to SinchClientBuilder.build is made on. If the invoking thread is not the main-thread, it needs to have an associated Looper.

Start the Sinch client
Before starting the client, add a client listener
1
2
3
4
5
6
7
8
sinchClient.addSinchClientListener(new SinchClientListener() {
public void onClientStarted(SinchClient client) { }
public void onClientStopped(SinchClient client) { }
public void onClientFailed(SinchClient client, SinchError error) { }
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration registrationCallback) { }
public void onLogMessage(int level, String area, String message) { }
});
sinchClient.start();
Terminate the Sinch client
When the app is done using the SinchClient, it should be stopped. If the client is currently listening for incoming events, it needs to stop listening as well. After terminate is called, any object retrieved directly from the client object (that is, CallClient, MessageClient, and AudioController) is considered invalid.
Terminating the client:
1.    sinchClient.stopListeningOnActiveConnection();
2.    sinchClient.terminate();

Setting up a video call
Just like audio calls, video calls are placed through the CallClient and events are received using the CallClientListener. The call client is owned by the SinchClient and accessed using sinchClient.getCallClient(). Calling is not enabled by default. 

Showing the video streams
Once you have created a VideoCallListener and added it to a call, the onVideoTrackAdded() method will be called.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@Override
public void onVideoTrackAdded(Call call) {
// Get a reference to your SinchClient, in the samples this is done through the service interface:
VideoController vc = getSinchServiceInterface().getVideoController();
View myPreview = vc.getLocalView();
View remoteView = vc.getRemoteView();
// Add the views to your view hierarchy
}

After the call has ended, dont forget to remove the views from your view hierarchy again.
@Override
public void onCallEnded(Call call) {
// Remove Sinch video views from your view hierarchy
}
Pausing video stream
To pause the local video stream, use the pauseVideo() method on the call.
1.        // User pause the video stream
2.        call.pauseVideo();

Resuming video stream
To resume the local video stream, use the resumeVideo() method on the call.
1.       // User resumes the video stream
2.       call.resumeVideo();

Pausing video stream delegates
Once you have created a VideoCallListener and added it to a call, the onVideoTrackPaused() method will be called when the remote user pause the video stream.
1.       @Override
2.       public void onVideoTrackPaused(Call call) {
3.            // Implement what to be done when remote user pause video stream.
4.       }

Resuming video stream delegates
Once you have created a VideoCallListener and added it to a call, the onVideoTrackResumed() method will be called when the remote user resumes the video stream..
1.       @Override
2.       public void onVideoTrackResumed(Call call) {
3.            // Implement what to be done when remote user resumes video stream.
4.       }

Video content fitting and aspect ratio
How the remote video stream is fitted into a view can be controller by the setResizeBehaviour() method with possible arguments VideoScalingType.ASPECT_FIT, VideoScalingType.ASPECT_FILL and VideoScalingType.ASPECT_BALANCED. The local preview will always use VideoScalingType.ASPECT_FIT.

Switching capturing device
The capturing device can be switched using videoController.setCaptureDevicePosition(int facing) with possible values Camera.CameraInfo.CAMERA_FACING_FRONT and Camera.CameraInfo.CAMERA_FACING_BACK. Use videoController.toggleCaptureDevicePosition() to alternate the two.

Accessing video frames of the remote streams
The Sinch SDK can provide access to raw video frames via a callback function. This callback can be used to achieve rich functionality such as applying filters, adding stickers to the video frames, or saving the video frame as an image.
Your video frame handler needs to implement VideoFrameListener interface by implementing the onFrame() callback. Note that it is important to explicitly release the video frame by calling release().
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Example:
import com.sinch.android.rtc.video.VideoFrame;
import com.sinch.android.rtc.video.VideoFrameListener;
public class YourVideoFrameHandler implements VideoFrameListener {
public synchronized void onFrame(String callId, VideoFrame videoFrame) {
// Process videoFrame
videoFrame.release(); // Release videoFrame}}

Use setVideoFrameListener() to register your video frame handler as the callback to receive video frames.

Example:
YourVideoFrameHandler videoFrameHandler = new YourVideoFrameHandler();
VideoController vc = getSinchServiceInterface().getVideoController();
vc.setVideoFrameListener(videoFrameHandler);

Tuesday, 15 August 2017

HB Blog 142: Android Configure Using Build Variants - Part 2.

Hello friends, Thanks for reading my previous post on HB Blog 141: Android Configure Build Variants - Part 1.
This post will show you how you can configure build variants to create different versions of your app from a single project, and how to properly manage your dependencies and signing configurations.
Build variants are the result of Gradle using a specific set of rules to combine settings, code, and resources configured in your build types and product flavors. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Each build variant represents a different version of your app that you can build. For example, you might want to build one version of your app that's free, with a limited set of content, and another paid version that includes more. You can also build different versions of your app that target different devices, based on API level or other device variations.

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
 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
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.harshalbenake.buildvariant"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }

    /**
     * The following sample specifies an applicationIdSuffix for the debug build type,
     * and configures a "jnidebug" build type that is initialized using settings from
     * the debug build type.
     */
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            applicationIdSuffix ".debug"
        }

        /**
         * The 'initWith' property allows you to copy configurations from other build types,
         * so you don't have to configure one from the beginning. You can then configure
         * just the settings you want to change. The following line initializes
         * 'jnidebug' using the debug build type, and changes only the
         * applicationIdSuffix and versionNameSuffix settings.
         */
        jnidebug {
            // This copies the debuggable attribute and debug signing configurations.
            initWith debug

            applicationIdSuffix ".jnidebug"
            jniDebuggable true
        }
    }

    // Specifies the flavor dimensions you want to use. The order in which you
    // list each dimension determines its priority, from highest to lowest,
    // when Gradle merges variant sources and configurations. You must assign
    // each product flavor you configure to one of the flavor dimensions.
    flavorDimensions "api", "mode"

    /**
     * The following code sample creates "demo" and "full" product flavors
     * which provide their own applicationIdSuffix and versionNameSuffix.
     * The following code sample uses the flavorDimensions property
     * to create a "mode" flavor dimension to group the "full" and "demo" product flavors,
     * and an "api" flavor dimension to group product flavor configurations based on API level
     */
    productFlavors {
        demo {
            applicationIdSuffix ".demo"
            versionNameSuffix "-demo"
            // Assigns this product flavor to the "mode" flavor dimension.
            dimension "mode"
            resValue "string", "app_name", "HB Demo"
        }
        full {
            applicationIdSuffix ".full"
            versionNameSuffix "-full"
            dimension "mode"
            resValue "string", "app_name", "HB Full"
        }

        // Configurations in the "api" product flavors override those in "mode"
        // flavors and the defaultConfig block. Gradle determines the priority
        // between flavor dimensions based on the order in which they appear next
        // to the flavorDimensions property above--the first dimension has a higher
        // priority than the second, and so on.
        minApi24 {
            dimension "api"
            minSdkVersion '24'
            // To ensure the target device receives the version of the app with
            // the highest compatible API level, assign version codes in increasing
            // value with API level. To learn more about assigning version codes to
            // support app updates and uploading to Google Play, read Multiple APK Support
            versionCode 30000 + android.defaultConfig.versionCode
            versionNameSuffix "-minApi24"
        }

        minApi23 {
            dimension "api"
            minSdkVersion '23'
            versionCode 20000  + android.defaultConfig.versionCode
            versionNameSuffix "-minApi23"
        }

        minApi21 {
            dimension "api"
            minSdkVersion '21'
            versionCode 10000 + android.defaultConfig.versionCode
            versionNameSuffix "-minApi21"
        }
}

    /**
     * Using the build configuration from the previous section as an example,
     * suppose you plan to support only API levels 23 and higher for the demo version of the app.
     * You can use the variantFilter block to filter out all build variant configurations that
     * combine the "minApi21" and "demo" product flavors.
     */
    variantFilter { variant ->
        def names = variant.flavors*.name
        // To check for a certain build type, use variant.buildType.name == "<buildType>"
        if (names.contains("minApi23") && names.contains("full")) {
            // Gradle ignores any variants that satisfy the conditions above.
            setIgnore(true)
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.3.1'
}

Tuesday, 1 August 2017

HB Blog 141: Android Configure Using Build Variants - Part 1.

The Android build system compiles app resources and source code, and packages them into an Android Application Package (APK), that you can test, deploy, sign, and distribute.  Android Studio uses Gradle, an advanced build toolkit, to automate and manage the build process, while allowing you to define flexible custom build configurations.
 The build process for a typical Android app module follows these general steps:
  1.     The compilers convert your source code into DEX (Dalvik Executable) files, which include the bytecode that runs on Android devices, and everything else into compiled resources.
  2.     The APK Packager combines the DEX files and compiled resources into a single APK. Before your app can be installed and deployed onto an Android device, however, the APK must be signed.
  3.     Before generating your final APK, the packager uses the zipalign tool to optimize your app to use less memory when running on a device.
At the end of the build process, you have either a debug APK or release APK of your app that you can use to deploy, test, or release to external users.

Gradle and the Android plugin help you configure the following aspects of your build:

 Build Types :-
    Build types define certain properties that Gradle uses when building and packaging your app, and are typically configured for different stages of your development lifecycle. For example, the debug build type enables debug options and signs the APK with the debug key, while the release build type may shrink, obfuscate, and sign your APK with a release key for distribution. You must define at least one build type in order to build your app—Android Studio creates the debug and release build types by default.

 Product Flavors :-
    Product flavors represent different versions of your app that you may release to users, such as free and paid versions of your app. You can customize product flavors to use different code and resources, while sharing and reusing the parts that are common to all versions of your app. Product flavors are optional and you must create them manually.

 Build Variants :-
    A build variant is a cross product of a build type and product flavor, and is the configuration Gradle uses to build your app. Using build variants, you can build the debug version of your product flavors during development, or signed release versions of your product flavors for distribution. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Creating additional build types or product flavors also creates additional build variants.

 Manifest Entries :-
    You can specify values for some properties of the manifest file in the build variant configuration. These build values override the existing values in the manifest file. This is useful if you want to generate multiple APKs for your modules where each of the apk files has a different application name, minimum SDK version, or target SDK version.

 Dependencies :-
    The build system manages project dependencies from your local filesystem and from remote repositories. This prevents you from having to manually search, download, and copy binary packages of your dependencies into your project directory.

 Signing :-
    The build system enables you to specify signing settings in the build configuration, and it can automatically sign your APKs during the build process. The build system signs the debug version with a default key and certificate using known credentials to avoid a password prompt at build time. The build system does not sign the release version unless you explicitly define a signing configuration for this build.
For more details, visit my post, HB Blog 120: How To Sign Your APKs Using Android Studio.

 ProGuard :-
    The build system enables you to specify a different ProGuard rules file for each build variant. The build system can run ProGuard to shrink and obfuscate your classes during the build process.
For more details, visit my post, HB Blog 139: ProGuard - Shrinks, Optimizes, And Obfuscates Your Code.

 Multiple APK Support :-
    The build system enables you to automatically build different APKs that each contain only the code and resources needed for a specific screen density or Application Binary Interface (ABI).

Custom Build Configurations :-

Creating custom build configurations requires you to make changes to one or more build configuration files, or build.gradle files. These plain text files use Domain Specific Language (DSL) to describe and manipulate the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM).

When starting a new project, Android Studio automatically creates some of these files for you, as shown in below image, and populates them based on sensible defaults.
 ......Continue, to read more on Build Variant gradle in my next post, Android Configure Using Build Variants - Part 2.

Saturday, 1 July 2017

HB Blog 139: ProGuard - Shrinks, Optimizes, And Obfuscates Your Code.

The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are Licensing Your Applications.

ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to deal with obfuscated code when you build your application in debug mode. Having ProGuard run is completely optional, but highly recommended.
1. Shrinking – detects and removes unused classes, fields, methods, and attributes.
2. Optimization – analyzes and optimizes the bytecode of the methods.
3. Obfuscation – renames the remaining classes, fields, and methods using short meaningless names.

How to Enable Proguard in Android Studio ?
  • In Android Studio project, the minifyEnabled  property in the build.gradle file enables and disables Proguard for release builds.
  • The minifyEnabled property is part of the buildTypes release block that controls the settings applied to release builds.
  • The getDefaultProguardFile(‘proguard-android.txt’) method obtains the default Proguard settings from the Android SDK tools/proguard folder.
  • Android Studio adds the proguard-rules.pro file at the root of the module, which helps to add custom Proguard rules.

Wednesday, 1 March 2017

HB Blog 130: How To Scan Network With Nmap GUI.

Nmap is popular network scanner software that can actively probe a particular host or a network to infer in-depth information about them. Nmap can conduct host discovery, service detection, OS version identification, port scanning, network stack fingerprinting, etc. It will help you to discover hosts, protocols, open ports, services and its configuration and vulnerabilities on networks. While Nmap itself is a command-line utility, you can run it along with its GUI front-end called Zenmap. Network Mapper is an Android frontend for well known Nmap scanner. Frontend will help you to download and install Nmap as well as use it. Frontend supports all known Android architectures: arm, mips and x86. Nmap binaries are transferred using HTTPS by default.

In this tutorial, I will describe how to scan particular hosts or networks by using Nmap GUI.
The following screenshot shows the main window of Zenmap.
Scan Particular Host(s):-
Using Zenmap interface, you can probe a particular host. Fill in the IP address or host name of a destination host in "Target" field, and choose a desired scan profile from "Profile" drop down menu. Then, click on "Scan" button. For multiple hosts, you can specify them in a comma-separated list.
To check the detailed system information of a particular host after scanning, highlight a host in the left panel, and click on "Host Details" tab on the right panel.
To view available services and open ports of a host, click on "Ports / Hosts" tab.
Scan an Entire Network:-
Zenmap can also probe an entire local network by specifying an address prefix (e.g., 192.168.1.0/24) in the "Target" field.
Once network scanning is completed, you can view the topology of discovered hosts by clicking on "Topology" tab.
To view a list of available services, click on "Services" button on the left panel. You can see a list of all discovered services and their associated hosts, as shown below.

Wednesday, 1 February 2017

HB Blog 128: Android Jack And Jill Toolchain.

Jack is a new Android toolchain that compiles Java source into Android dex bytecode. It replaces the previous Android toolchain, which consists of multiple tools, such as javac, ProGuard, jarjar, and dx.
For information related to Android Build System visit post HB Blog 51: Android Build System - How Android Apk Is Built.

The Jack toolchain provides the following advantages:
  • Completely open source
    Available in AOSP; partners are welcome to contribute. 
  • Speeds compilation time
    Jack has specific supports to reduce compilation time: pre-dexing, incremental compilation and a Jack compilation server. 
  • Handles shrinking, obfuscation, repackaging and multidex
    Using a separate package such as ProGuard is no longer necessary.
Jack has its own .jack file format, which contains the pre-compiled dex code for the library, allowing for faster compilation (pre-dex).
The Jill tool translates the existing .jar libraries into the new library format, as shown below.
How to use Jack in Android build?
You don’t have to do anything differently to use Jack — just use your standard makefile commands to compile the tree or your project. Jack is the default Android build toolchain for M.
The first time Jack is used, it launches a local Jack compilation server on your computer:
  •     This server brings an intrinsic speedup, because it avoids launching a new host JRE JVM, loading Jack code, initializing Jack and warming up the JIT at each compilation. It also provides very good compilation times during small compilations (e.g. in incremental mode).
  •     The server is also a short-term solution to control the number of parallel Jack compilations, and so to avoid overloading your computer (memory or disk issue), because it limits the number of parallel compilations.
The Jack server shuts itself down after an idle time without any compilation. It uses two TCP ports on the localhost interface, and so is not available externally. All these parameters (number of parallel compilations, timeout, ports number, etc) can be modified by editing the $HOME/.jack file.

Jack and Jill are available in Build Tools version 21.1.1, and greater, via the SDK Manager. Complementary Gradle and Android Studio support is also already available in the Android 1.0.0+ Gradle plugin.'
Using Gradle, add the following to your module-level build config file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
android {
    ...
    buildToolsVersion '21.1.2'
    defaultConfig {
      // Enable the experimental Jack build tools.
       jackOptions {
         enabled true
       }
    }
    ...
}

Jack limitations:
  • The Jack server is mono-user by default, so can be only used by one user on a computer. If it is not the case, please, choose different port numbers for each user and adjust SERVER_NB_COMPILE accordingly. You can also disable the Jack server by setting SERVER=false in your $HOME/.jack.  
  •  CTS compilation is slow due to current vm-tests-tf integration. 
  •  Bytecode manipulation tools, like JaCoCo, are not supported. 

Tuesday, 1 November 2016

HB Blog 122: Android Tools For Analyzing RAM Usage.

Random-access memory (RAM) is a valuable resource in any software development environment, but it's even more valuable on a mobile operating system where physical memory is often constrained. Although both the Android Runtime (ART) and Dalvik virtual machine perform routine garbage collection, this does not mean you can ignore when and where your app allocates and releases memory. You still need to avoid introducing memory leaks, usually caused by holding onto object references in static member variables, and release any Reference objects at the appropriate time as defined by lifecycle callbacks.
Tools for analyzing RAM usage :-
Before you can fix the memory usage problems in your app, you first need to find them. Android Studio and the Android SDK include several tools for analyzing memory usage in your app,

  1. The Device Monitor has a Dalvik Debug Monitor Server (DDMS) tool that allows you to inspect memory allocation within your app process. You can use this information to understand how your app uses memory overall. For example, you can force a garbage collection event and then view the types of objects that remain in memory. You can use this information to identify operations or actions within your app that allocate or leave excessive amounts of objects in memory. 
  2. The Memory Monitor in Android Studio shows you how your app allocates memory over the course of a single session. The tool shows a graph of available and allocated Java memory over time, including garbage collection events. You can also initiate garbage collection events and take a snapshot of the Java heap while your app runs. The output from the Memory Monitor tool can help you identify points when your app experiences excessive garbage collection events, leading to app slowness.
  3. Garbage collection events also show up in the Traceview viewer. Traceview allows you to view trace log files as both a timeline and as a profile of what happened within a method. You can use this tool to determine what code was executing when a garbage collection event occurred. 
  4. The Allocation Tracker tool in Android Studio gives you a detailed look at how your app allocates memory. The Allocation Tracker records an app's memory allocations and lists all allocated objects within the profiling snapshot. You can use this tool to track down parts of your code that allocate too many objects.

Saturday, 1 October 2016

HB Blog 120: How To Sign Your APKs Using Android Studio.

                 Android is open source but, it has security checks at its own level too. It requires that all APKs be digitally signed with a certificate before they can be installed. This tutorial describes how to sign your APKs using Android Studio.
A public-key certificate, also known as a digital certificate or an identity certificate, contains the public key of a public/private key pair, as well as some other metadata identifying the owner of the key (for example, name and location). The owner of the certificate holds the corresponding private key.
When you sign an APK, the signing tool attaches the public-key certificate to the APK. The public-key certificate serves as as a "fingerprint" that uniquely associates the APK to you and your corresponding private key. This helps Android ensure that any future updates to your APK are authentic and come from the original author.
A keystore is a binary file that contains one or more private keys. When you sign an APK for release using Android Studio, you can choose to generate a new keystore and private key or use a keystore and private key you already have. You should choose a strong password for your keystore, and a separate strong password for each private key stored in the keystore. You must keep your keystore in a safe and secure place. You must use the same certificate throughout the lifespan of your app in order for users to be able to install new versions as updates to the app.
You can use Android Studio to manually generate signed APKs, either one at a time, or for multiple build variants at once. Instead of manually signing APKs, you can also configure your Gradle build settings to handle signing automatically during the build process.

To sign your APK for release in Android Studio, follow these steps:
  1. In the menu bar, click Build > Generate Signed APK.
  2. Select the module you would like to release from the drop down, and click Next.
  3. If you already have a keystore, go to step 5. If you want to create a new keystore, click Create new.
  4. On the New Key Store window, provide the following information for your keystore and key, as shown below,
    Keystore
  •         Key store path: Select the location where your keystore should be created.
  •         Password: Create and confirm a secure password for your keystore.
    Key
  •         Alias: Enter an identifying name for your key.
  •         Password: Create and confirm a secure password for your key. This should be different from the password you chose for your keystore
  •         Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
  •         Certificate: Enter some information about yourself for your certificate. This information is not displayed in your app, but is included in your certificate as part of the APK.
Once you complete the form, click OK.
    5. On the Generate Signed APK Wizard window, select a keystore, a private key, and enter the passwords for both. (If you created your keystore in the last step, these fields are already populated for you.) Then click Next.
    6. On the next window, select a destination for the signed APK(s), select the build type, (if applicable) choose the product flavor(s), and click Finish.
When the process completes, you will find your signed APK in the destination folder you selected above. You may now distribute your signed APK through an app marketplace like the Google Play Store, or using the mechanism of your choice.  For more about how to publish your signed APK to the Google Play Store, you can follow my blog,  How To Publish Android Application On Google Play.

Friday, 2 September 2016

HB Blog 118: Cell Broadcast - The Mobile Technology For Mass Message Broadcast.

Cell Broadcast (CB) is a mobile technology that allows messages (currently of up to 15 pages of up to 93 characters) to be broadcast to all mobile handsets and similar devices within a designated geographical area. The broadcast range can be varied, from a single cell to the entire network.
This technology is used in deploying location-based subscriber services, such as regional auctions, local weather, traffic conditions and 'nearest' services (like requesting the nearest service station or restaurant).
It is designed for simultaneous delivery of messages to multiple users in a specified area. Whereas the Short Message Service (SMS) is a one-to-one and one-to-a-few service, It is one-to-many geographically focused service.
It enables messages to be communicated to multiple mobile phone customers who are located within a given part of its network coverage area at the time the message is broadcast. Cell Broadcast is more akin to other mass distribution media such as teletext or Radio Data System (RDS).
It  is a technology that allows a text or binary message to be defined and distributed to all mobile terminals connected to a set of cells. Whereas SMS messages are sent point-to-point, Cell Broadcast (SMS-CB) messages are sent point-to-area. This means that one SMS-CB message can reach a huge number of terminals at once. In other words, SMS-CB messages are directed to radio cells, rather than to a specific terminal. SMS-CB is an unconfirmed push service, meaning that the originator of the message does not know who has received the message, allowing for services based on anonymity.

A Cell Broadcast Entity (CBE) is a multi-user front-end that allows the definition and control of SMS-CB messages. A CBE can be located at the site of a content provider. At the site of the operator a so-called Cell Broadcast Centre (CBC) is located. The CBC is the heart of the Cell Broadcast System and acts as a server for all CBE clients. It takes care of the administration of all SMS-CB messages it receives from the CBEs and does the communication towards the GSM network. The GSM network itself takes care of delivering the SMS-CB messages to the mobile terminals.
Cell Broadcast can be used for a number of different services and has been de-ployed by several network operators.

Early Warning System (EWS) for citizen alert
Cell Broadcast on mobile telephones can be used for Early Warning Systems (EWS) by Governments. A few countries in the world have already adopted this technique, in addition to older and already existing forms of communication like siren, or radio and TV. The advantage of this system is that it allows sending messages without having to know the phone numbers of the users in the region. Instead of sending a message to a specific known mobile phone you can send a text to all mobile phones in a specific zone. Mass communication, very fast, in case it really matters.

Advertising
Retail outlets in certain areas would be interested in sending customers and potential customers information about special offers and attractions such as sales, special offers, extended opening times and so on. Shopping centers, exhibition halls, airports and sports stadiums are the kinds of location that could be targeted for Cell Broadcast based services.

Information Services
Cell Broadcast is ideal for delivering local or regional information which is suited to all the people in that area, rather than just one or a few people. Examples include hazard warnings, cinema programs, local weather, flight or bus delays, tourist information, parking and traffic information. Cell Broadcast can also be used for managing and communicating with a remote but local team such as emergency services or airport staff. The emergency services could send an encrypted message out to all officers or other staff in a certain area to respond to an incident. This is particularly useful for standby workers who only need to be called in and present in a certain place when certain events occur.

SMS versus Cell Broadcast: -

Short Message Service (SMS)
Characteristic
Cell Broadcast (CELL BROADCAST)
Messages sent point-to-point
Transmission type
Messages sent point-to-area
Required. Requires specific phone numbers to be known
Mobile Number dependency
Independent. Does not require phone numbers to be known
No. Only pre-registered numbers will be notified; message will be received regardless of actual location
Location based targeting
Yes. All phones within a targeted geographical area (cells) will be notified.
Static messages will be sent to pre-registered numbers.
Message type
Location specific. Tailored messages can be sent to different areas.
Direct. Users can receive messages and respond directly to the sender via SMS.
Bi-directionality
Indirect. The message should contain a URL or number to reply.
Subject to network congestion. Delivery is queued. Congestion can occur
Congestion and delay
CELL BROADCAST is always available.
140-160 characters. Longer 'concatenated' messages are supported.
Message length
93 characters. Longer 'multiple page’ messages are supported.
Poor authenticity. The source of the message cannot be verified.
Security
Good security. Only the mobile operator can broadcast messages.
No barring.
Service barring
Yes. Users can turn off CELL BROADCAST reception or a specific channel.
By default. When phone is turned on messages can be received.
Reception
Requires action. CELL BROADCAST needs to be turned on in order to receive messages.
Yes. Senders can request delivery confirmation.
Delivery confirmation
No. Confirmation of delivery to the handset is not available, however actual broadcast in the network is.
No repetition rate.
Repetition rate
Yes. Can be repeated between 2 seconds and 32 minutes.
No. Identical to all receivers.
Language selection
Yes. Messages can be broadcasted in subscriber’s preferred language
Yes.
Message storage
Handset dependant.