Exploring Fingerprint Api in Android M or 6.0

Hello developers google recently launched there latest Android version which was called Marshmallow in which it has added various new features.

One of them is Fingerprint api which allows developers to add an extra layer to security for apps related to money or storing there secure data.

I haven’t myself explored much but some basic methods i have tried and they worked quite well.

First of all for this you will need latest sdk i.e. Android api level 23.

First we need to initialize FingerPrint Manager like this

private FingerprintManagerCompat fingerprintManagerCompat;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);
    fingerprintManagerCompat = FingerprintManagerCompat.from(this);
    if(fingerprintManagerCompat.isHardwareDetected()){
        Toast.makeText(this,"Successful",Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this,"UnSuccessful",Toast.LENGTH_SHORT).show();
    }
}

The above method detects whether system have hardware feature for fingerprint and if yes it is functional or not.

fingerprintManagerCompat.hasEnrolledFingerprints()

This one works to determine if there is at least one fingerprint enrolled and returns true if at least one fingerprint is present.

/**
 * Request authentication of a crypto object. This call warms up the fingerprint hardware
 * and starts scanning for a fingerprint. It terminates when
 * {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)} or
 * {@link AuthenticationCallback#onAuthenticationSucceeded(AuthenticationResult) is called, at
 * which point the object is no longer valid. The operation can be canceled by using the
 * provided cancel object.
 *
 * @param crypto object associated with the call or null if none required.
 * @param flags optional flags; should be 0
 * @param cancel an object that can be used to cancel authentication
 * @param callback an object to receive authentication events
 * @param handler an optional handler for events
 */
public void authenticate(@Nullable CryptoObject crypto, int flags,
        @Nullable CancellationSignal cancel, @NonNull AuthenticationCallback callback,
        @Nullable Handler handler) {
    IMPL.authenticate(mContext, crypto, flags, cancel, callback, handler);
}

This method is used for authentication and return results to call back.

Try this out in your supported phones, i will explore more and update you guys on this. Till then Happy Developing 🙂

Thanks for reading. 🙂

Securing Your Code Using ProGuard In Android

Hello Developers have you ever given a thought about securing your code so that no one could look at it by reverse engineering your apk. If yes then this blog will help you learning about ProGuard. Proguard is a tool which shrinks,optimize and obfuscate your code. It removes unused code and changes classes, variables name to unreadable form so that it is hard to reverse engineer your .apk. The other advantage of  ProGuard tool is it reduces the size of your .apk file. Important points about ProGuard tool in android are:

  • Android build system already comes integrated with ProGuard tool so you do not have to do anything extra.
  • ProGuard tool only runs in release mode so that in debug mode you don’t have to deal with obfuscate code.
  • ProGuard is completely optional but it is highly recommended that you use this in release mode.

Now for using ProGuard in your project perform the following steps:

  • Go to project-properties file which is present in the root folder of your project.
  • Edit this file and uncomment the “proguard.config” line and assign the path of your sdk like this “proguard.config=/home/ankitkhare/Android/Sdk/tools/proguard/proguard-android.txt:proguard-project.txt“(as i am using ubuntu so i have given this path in windows it would be like E:/android/sdk/tools/proguard/proguard-android.txt:proguard-project.txt” or where ever your sdk is installed).
  • If you are using Android Studio then in your project  you must have file named proguard – rules.pro and the build.gradle. Inside build.gradle add android { buildTypes { release { // Following lines to run progaurd in android. minifyEnabled true proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’ } }
  • Then export your project in release mode.
  • Once you are done with this there would be a ProGuard folder added to your project(If not then there must be some error).

Now navigate to your .apk file(the path of apk you mentioned while exporting application) and unzip it. Open any file and you will see that the file is in unreadable form to be more precise it is Obfuscated. I have created a demo project https://github.com/ankitkhare0804/ProguardDemo In next part would cover the important points to remember  while using ProGuard, how to use retrace and also debugging considerations for published applications. Hope you found this helpful. Thanks for reading :).

Securing Content in Google play In-app Billing

Hello Developers i am sure you all have worked on Google play In-app Billing(if not don’t worry you will be doing it in future). In-app billing is responsible for making purchase through your app. User buys an item through an app and pay money through their bank details.The whole process is achieved via Google play In-app Billing and we are here to discuss about the things which the developers should keep in mind while publishing In-app billing app to Play store. These points will help an application

Here are few points which you should keep in mind while you are working on In-app billing

  • Do not put your content in bundled in the apk as attackers can extract it and distribute it, so instead of putting them in apk trying to put them on a remote server and parse them as per your needs. This will ensure your content is safe and it is always fresh.
  • Use tools like Proguard to shrink optimize and obfuscate your code so that it would be difficult for the attackers to reverse engineer your code and the data integrity is ensured.
  • Do verification process on server side instead to doing it on device, doing verification this way will prevent attackers to know about the verification process by reverse engineering your apk.
  • Prevent your Google play API key at all cost try to manipulate it using bit manipulation to hide actual key.
  • In In-App billing version 3 API there is a developer payload string which is used for sending any details of purchase to Google play and Google play reverts back with the same string in response. Pass this string as token in your application, this will help you identifying the user who made purchase and whether that transaction was genuine or not.
  • If you have created the application by taking the sample application code then don’t forget to modify your code before releasing the app for production purpose and try to use sample provided by Google only.

Make sure you follow these points before publishing your application. as this would prevent the malicious attacks on your applications.

For more details on this go through the following link

http://developer.android.com/google/play/billing/billing_best_practices.html

Hope you find this useful.

Thanks for reading :).

Updating Security Provider Asynchronously In Android

SSL refers to Secure Socket layer which is responsible for secure communication between client and server. SSL encrypts data when it is being transferred over network, thereby securing the communication between client and server.

In android this work is done by security provider. Security provider provides secure communication over network. So security provider must remain updated all the time to prevent exploitation attacks.

This can be achieved by using Google Play Services. Google Play Services consists of ProviderInstaller which can be used to update device security provider.

Provider Installer is used to check whether device security provider is updated or not, if not it automatically updates the provider. It contains two method’s which are used to check whether the security provider is updated or not and they are

  • installIfNeeded().
  • InstallIfNeededAsync().

These two methods provides a way to update security provider either synchronously or asynchronously.

Here we will update the provider asynchronously.

Here are the steps which are required before updating the provider

  • Use Google Play Services(which can be found in your adt → sdk → extras → Google →Google_play_services → libproject → google-play-services_lib . If not found please open sdk manager and under extras tick Google play services and update) as library project in your application.
  • Set meta data tag in your android manifest inside application tag.
    <meta-data
       android:name="com.google.android.gms.version"
       android:value="@integer/google_play_services_version" />

Here is the class which is used to update the security provider.

/**
* This class checks for Security provider update , if it's not updated then the
* update is installed.
* 
* @author Ankit Khare
*/
public class MainActivity extends Activity implements ProviderInstallListener {
/**
* Updating provider asynchronously.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Update the provider asynchronously
ProviderInstaller.installIfNeededAsync(this, this);
}
/**
* The provider is already installed and up-to-date.
*/
@Override
public void onProviderInstalled() {
Toast.makeText(this, "Provider Installed.Google play Services are up-to-date", Toast.LENGTH_SHORT).show();
}
/**
* Provider Installation failed. Check errorCode whether it is recoverable
* or not.
*/
@Override
public void onProviderInstallFailed(int errorCode, Intent intent) {
if (GooglePlayServicesUtil.isUserRecoverableError(errorCode)) {
// Retry to install update in case of recoverable error.
ProviderInstaller.installIfNeededAsync(this, this);
} else {
// Please update your Google Play Services.
}
}
}

This class updates the security provider asynchronously by using callbacks to ProviderInstallListener. If the provider is already updated onProviderInstalled() is called otherwise the call goes to onPorviderInstallFailed().

For Detail Information refer to

https://developer.android.com/training/articles/security-gms-provider.html

Thanks for reading 🙂

Overview Of Android Security Structure

Android is world’s most popular mobile OS. The reason behind it’s popularity is it’s open nature. Applications can use hardware as per it’s requirements with no restrictions, at the same time maintaining it’s security aspects. Android design structure reduces the security concerns so that the developers do not have to worry about the security issues and have to focus only about the design and logic of the application.

Key Issues which a OS needs to worry about are

  • Prevent the misuse of hardware resources.
  • Prevent the application data from misuse.
  • Secured IPC(Interprocess Communication).
  • Restricting applications to perform malicious attacks.

These all issues were kept in mind while developing android, below are the points on which on which android focuses on.

Key Security Features of Android are 

  • *Sand-boxing of the applications.
  • Applications are signed before they are published.
  • **ASLR(Address Space Layout Randomization).
  • Before applications are installed on device permissions are displayed to the user so that he can choose whether to provide these permissions or not or in short install application or not.
  • Secured IPC(Interprocess Communication).

These all features reduces the pain of developers so that they only have to focus on application design and logic but not on security concerns.

All though Android provide most of the security features itself but the developers have to keep in mind the following points while creating an applications:

  • Only set those permissions which are required by the application for eg. if you want to access the images from sd card for read only purpose and have to intention to modify them, then you must only  provide “android.permission.READ_EXTERNAL_STORAGE” and not “android.permission.WRITE_EXTERNAL_STORAGE“.
  • If you are creating content provider in your application and it’s not intended to be shared among other applications then you  must mention “android:exported=false” in your application manifest otherwise another application can access  your application data.
  • Perform validations where necessary such as email or phone number.

For Detail Information visit the link.

http://developer.android.com/training/articles/security-tips.html

Thanks for reading 🙂

*Sandbox refers to separating your application data and code execution from other applications.

**https://khareankit0804.wordpress.com/2014/09/30/aslr-in-android/ 

AES Encryption In Android

AES stands for Advanced Encryption Standard is an encryption algorithm which is used to encrypt data so that it is converted to such a form which cannot be interpreted by anyone. AES is a symmetric algorithm which means same key is used to encrypt and decrypt the data. In AES the key which is used for encryption is in multiple of 32 bits with a minimum of 128 bits and maximum of 256 bits. There are three types of AES which are categorized on the basis of it’s key length. So “AES-128”, ”AES-192” and “AES-256” are all AES algorithm, but the major difference between them is of key length.

Here is AES Encryption class which contains all the methods which are required for encryption and decryption of data.

/**
* This is AES symmetric encryption helper which contains methods for encryption and decryption.
* @author Ankit Khare
*/
public class EncryptionHelper {
private static final String AES = "AES";
private Activity mActivity;
public EncryptionHelper(Activity iActivity) {
mActivity = iActivity;
}
/**
* This method generates the key with the help of which encryption and decryption is done.
* @param secretKey
* @return
* @throws NoSuchAlgorithmException
*/
public SecretKeySpec generateSecretKeySpec(String secretKey) throws NoSuchAlgorithmException {
SecureRandom secureRandom = new SecureRandom(secretKey.getBytes());
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(256, secureRandom);
SecretKeySpec keySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), AES);
return keySpec;
}
/**
* This method returns the encrypted form of the data.
* @param secretKey the key which is used for encryption. It should be of 128 bits.
* @param data data to be encrypted.
* @return encrypted string
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public String getEncodedString(String secretKey, String data) throws IllegalBlockSizeException, BadPaddingException {
byte[] encodedBytes = null;
try {
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
encodedBytes = cipher.doFinal(data.getBytes());
}
catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
Toast.makeText(mActivity, "Encryption failed!", Toast.LENGTH_SHORT).show();
}
if (encodedBytes != null)
return Base64.encodeToString(encodedBytes, Base64.DEFAULT);
else
return null;
}
/**
* This method is used to decrypt the encrypted data.
* @param secretKey the key which is used for encryption. It should be of 128 bits.
* @param encryptString encrypt string which is to be decrypted.
* @return the original data.
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
*/
public String getDecodedString(String secretKey, String encryptString) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
byte[] decodedBytes = null;
try {
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), AES);
Cipher cipher = Cipher.getInstance(AES);
byte[] encodedBytes = Base64.decode(encryptString.getBytes(), Base64.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
decodedBytes = cipher.doFinal(encodedBytes);
}
catch (IllegalBlockSizeException | BadPaddingException e) {
Toast.makeText(mActivity, "Decryption failed!", Toast.LENGTH_SHORT).show();
}
if (decodedBytes != null)
return new String(decodedBytes);
else
return null;
}
}

Use this code in your activity to encrypt and decrypt the data.

Thanks for reading 🙂