Browse Author: Ankita Deshmukh

Convert String to PrivateKey

Below code works to convert string to PrivateKey

public static class DecryptionUtil {
    private static final String ASYMMETRIC_ALGO =

    public static byte[] decryptUsingPrivateKey(PrivateKey privateKey, byte[] data)
            throws IOException, GeneralSecurityException {
        Cipher pkCipher = Cipher.getInstance(ASYMMETRIC_ALGO);
        pkCipher.init(Cipher.DECRYPT_MODE, privateKey);
        return pkCipher.doFinal(data);

    public static byte[] decryptUsingSymmetricKey(byte[] symmetricKey, byte[]
            data) throws InvalidCipherTextException {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new
                AESEngine(), new PKCS7Padding());
        cipher.init(false, new KeyParameter(symmetricKey));
        int outputSize = cipher.getOutputSize(data.length);
        byte[] tempOP = new byte[outputSize];
        int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
        int outputLen = cipher.doFinal(tempOP, processLen);
        byte[] result = new byte[processLen + outputLen];
        System.arraycopy(tempOP, 0, result, 0, result.length);
        return result;

public static PrivateKey getPrivateKey(String privateString) {

    PrivateKey privateKey = null;

    try {
       // String privateString = getString(key, context);
            byte[] binCpk = Base64.decode(privateString,Base64.DEFAULT);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA","BC");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binCpk);
            privateKey = keyFactory.generatePrivate(privateKeySpec);

    catch(Exception e){
        String r="";
    return privateKey;

Uploading image to Google Drive from Android

Below code will help to upload image directly to your google drive

private void saveFileToDrive() {

    final Bitmap image = mBitmapToSave;
            .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {

                public void onResult(DriveApi.DriveContentsResult result) {

                    if (!result.getStatus().isSuccess()) {
                        Log.i("ERROR", "Failed to create new contents.");

                    final DriveContents driveContents = result.getDriveContents();

                    new Thread() {
                        public void run() {
                            // write content to DriveContents
                            OutputStream outputStream = driveContents.getOutputStream();
                            // Write the bitmap data from it.
                            ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
                            image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
                            try {
                            } catch (IOException e1) {
                                Log.i("ERROR", "Unable to write file contents.");
                            // Create the initial metadata - MIME type and title.
                            // Note that the user will be able to change the title later.
                            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                    .setMimeType("image/jpeg").setTitle("Android Photo.png").build();
                            // Create an intent for the file chooser, and start it.
                            IntentSender intentSender = Drive.DriveApi
                            try {
                                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
                            } catch (IntentSender.SendIntentException e) {
                                Log.i("ERROR", "Failed to launch file chooser.");


Volley Library to make network connection from Android App

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley comes with lot of features. Some of them are

1. Effective request cache and memory management
2. Cancelling the requests

To use volley library just make below changes in your build.gradle file:

dependencies {
    compile 'com.mcxiaoke.volley:library:1.0.17'

Now add below code to make network calls

StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
            public void onResponse(String response) {
               //get response 
        new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) { 
        }) {
    protected Map<String, String> getParams() {
           // send parameters for post
        return map;


To set connection timeout add below code:
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
RequestQueue requestQueue = Volley.newRequestQueue(context);

First onsite experience in my dream country … Australia

1610868_897869220236745_5334705507768285628_n 1622788_895949123762088_7174656833152448812_n 10885195_892058004151200_8731903846153530047_nDSC00545

It was my school days dream that I wanted to go Australia and now I still cant believe that I got an opportunity to work onsite for the first time in Australia and that too in the capital city CANBERRA. I was shocked as well as surprised when I came to know that Nanostuffs have chosen me for this opportunity .

The biggest hurdle for me to grab the opportunity was getting the passport as well the visa on time. Client had an immediate requirement and

I had to manage everything within 15 days. Finally I got the passport and sad thing was my visa got rejected for the first time. I was very sad when I came to know about it. but then Nishant & Ankita consoled me and we applied one more time. This time ball was in our court and visa was granted. I had to fly in next 2 days . It was again an amazing experience to manage everything in two days.

I was very excited and at same time had butterflies in my stomach as I was flying for the first time. I was quite nervous when I reached the client office on the first day. Everyone was new to me. But as days passed I got settled and everything worked smoothly. I loved the work culture of Australia.

People are very helpful and polite here. I never felt that I was new to this country. people are so caring & friendly.

I got an opportunity to visit Crazy, Picturesque Scenic, Modern, Dynamic city like SYDNEY. It was a dream come true experience. I got to see their National Animal Kangaroo and even Koalas. Even I visited Parliament house of Australia which is a rare experience. I got attached to Australia in very less time I never felt like coming back. 🙂

Overall it was a memorable experience for me and I thank Nishant and Ankita for giving me this wonderful opportunity at such a young age. Cheers Nanostuffs.

…. Ankita Deshmukh, Senior Android Developer, Nanostuffs.


How to Login via Facebook,get facebook friendlist and their details, post on friends wall and get newsfeeds details

How to Login with Facebook:

follow the below steps to add login via facebook:

step1: register app on

step 2: get the app_id , add it to strings file and add following code to manifest file:



android:value=”@string/app_id” />

//add meta-data inside appication tag.

<activity android:name=”com.facebook.LoginActivity” >

step 3: Download latest facebooksdk and import it as project in your project

step 4: add following code onclick of login with facebook button:

try {

PackageInfo info = getPackageManager().getPackageInfo( “package_name”, PackageManager.GET_SIGNATURES);

for (Signature signature : info.signatures)


MessageDigest md = MessageDigest.getInstance(“SHA”); md.update(signature.toByteArray());

Log.d(“KeyHash:”, Base64.encodeToString(md.digest(), Base64.DEFAULT));


} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
} //


//Get keyhash from above code and add it to developers.facebook in your project
session1 = Session.getActiveSession();

if (session1 == null)

{ session1 = new Session(Login.this);


if (session1.getState().equals( SessionState.CREATED_TOKEN_LOADED))


session1.openForRead(new Session.OpenRequest(Login.this) .setCallback(statusCallback));

access_token = session1.getAccessToken();



if (!session1.isOpened() && !session1.isClosed())


session1.openForRead(new Session.OpenRequest(Login.this) .setCallback(statusCallback));

access_token = session1.getAccessToken();

} else


Session.openActiveSession(Login.this, true, statusCallback);

access_token = session1.getAccessToken();



/// Add this method to your code:

private Session.StatusCallback statusCallback = new Session.StatusCallback() {
@Override public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

public void onCompleted(GraphUser user, Response response) {
if (user != null) {


fbid = user.getId();

fbname = user.getName();
} } });
} }


//override this method of activity:

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

Session.getActiveSession() .onActivityResult(this, requestCode, resultCode, data);



–>How to Get Facebook friendlist:

Create async task and use below url to get facebookfriend list:”session access_token”

Note: parse the data using Json .

–>How to share on friends wall:

add below code to share on friends wall:

private void publishFeedDialog(int position) {


Bundle params = new Bundle();

params.putString(“message”,”YOUR MESSAGE” );

params.putString(“to”,”Friends userid”);

WebDialog feedDialog = (   new WebDialog.FeedDialogBuilder(Context,  Session.getActiveSession(),    params))                .setOnCompleteListener(null)   .build();;

} catch(Exception e){

e.printStackTrace(); }



–> How to Get NewsFeed:

Use below url to get newsfeed:


Note: use Json parsing to retrive details of each newsfeed.


Loading image from url using AQuery

Download android-query.jar from below link:


Add following code where you want to load image :

public ImageLoader imageLoader;

imageLoader = new ImageLoader(this);

AQuery androidAQuery=new AQuery(getApplicationContext());, true, true, 100,default_pic);


Note: if you dont want to store image in cache memory set true parameters to false.