MD5 in Java

The MD5 or Message-Digest Algorithm is a commonly used hash function, which produces a 128 bit hash value, commonly expressed as a 32 digit hex number. It is commonly used by web developers to store passwords or sensitive information in their databases. It is to be noted that an MD5 string cannot be converted back into the original string.
Although this hashing method is now considered "cryptographically broken or not suitable for further use" as of 2005, it is still widely used. In PHP, performing MD5 is very simple - one just has to call a function with the message to be digested as the argument($digest = md5("message"); ). But it is not that simple in java.

Here is a java class which you can place in your project to perform MD5 hashing.



import java.security.MessageDigest;

public class MD5
{
public static final String salt = "aq32nngetg45678";

public static String getMd5(String value)
{
try
{
 char[] hexDigits =  {'0','1','2','3','4','5','6','7','8','9','a','b','c','d' ,'e','f'};
 MessageDigest md5 = MessageDigest.getInstance("MD5");
 md5.update(value.getBytes("UTF-8"));
 byte[] messageDigest = md5.digest();
 StringBuilder sb = new StringBuilder(32);


 for (byte b : messageDigest) //for zero padding, ie make '1' '01'
 {
   sb.append(hexDigits[(b >> 4) & 0x0f]); //0x0f in hex = 15 in decimal. If b=1
   sb.append(hexDigits[b & 0x0f]);// sb += hexDigits[0] + hexDigits[1](sb += "01")
 }
 return sb.toString();
}
catch(Exception e)
{
 return "ERROR";
}
}

}
After placing this class in your project, you can perform md5 hashing by
String digest = MD5.getMd5("message");
It is a good practice to append a random string to your original string before performing hashing. This random string is called 'salt'. Salt is added to prevent dictionary attacks and rainbow table attacks.

>> is the signed right shift operator and it shifts a bit pattern to right. Its syntax is bit_pattern_to_shift >> no_of_positions_to_shift. Hence, here, before placing a digit into the final string,it is padded.

Android - Simple Multi-Contacts Picker with Listview and Checkbox

I assume the reader to have basic android programming skills. This post will cover the making of a simple android contact picker with the following features
  • Asynchronous loading of contact with AsyncTask
  • Display of all contacts in a Listview with the help of an Adapter
  • Multi Contact Select with Checkbox
  • Contact Search/Filtering
  • The Activity will return the contacts
Final Result

Step by step guide

Step 1: Get required permission in the manifest file


<uses-permission android:name="android.permission.READ_CONTACTS" />
This should be written outside the application tag.

Step 2: Set up the contacts picker activity

The contacts picker activity will display a list of contacts and a search box, which will enable the end-user to select multiple contacts. The following is the layout file for the activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="sachinmuralig.me.simplemulticontactpicker.ContactsPickerActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt_filter"
        android:hint="@string/txt_search"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt_load_progress"
        android:layout_below="@+id/txt_filter"
        android:text="Loading..."
        />


    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt_load_progress"
        android:layout_above="@+id/btn_done"
        android:id="@+id/lst_contacts_chooser"
    />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_done"
        android:layout_alignParentBottom="true"
        android:text="@string/txt_done"
        />



</RelativeLayout>
The layout is pretty straight forward - an EditText for the search input, a ListView for contacts display and a 'Done' Button.

Step 3 : Represent a Contact as a class


package sachinmuralig.me.simplemulticontactpicker;

import android.os.Parcel;
import android.os.Parcelable;


public class Contact implements Parcelable {

    public String id,name,phone,label;

    Contact(String id, String name,String phone,String label){
        this.id=id;
        this.name=name;
        this.phone=phone;
        this.label=label;
    }

    protected Contact(Parcel in) {
        id = in.readString();
        name = in.readString();
        phone = in.readString();
        label = in.readString();
    }

    public static final Creator<Contact> CREATOR = new Creator<Contact>() {
        @Override
        public Contact createFromParcel(Parcel in) {
            return new Contact(in);
        }

        @Override
        public Contact[] newArray(int size) {
            return new Contact[size];
        }
    };

    @Override
    public String toString()
    {
        return name+" | "+label+" : "+phone;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(name);
        dest.writeString(phone);
        dest.writeString(label);
    }
}
The Class implements Parcelable so that the selected contacts can be easily returned to another activity. Read more about parcelable here Not that the toString() method was overridden to return a presentable view of the contact data. The contact data that is used here is minimal(id, name, phone, label) to keep it simple and the data members can be easily populated using the Constructor.

Step 4 : The Contacts List Class

This adds another level of abstraction. We will be basically working with Contacts List. An instance of contacts list will contain all the contacts that is in the phone, another contacts list will hold the filtered contacts, which are filtered according to the search input and a third contact list will contain the contacts selected by the end-user, and this third list will be returned as the result.
package sachinmuralig.me.simplemulticontactpicker;


import java.util.ArrayList;


public class ContactsList{

    public ArrayList<Contact> contactArrayList;

    ContactsList(){

        contactArrayList = new ArrayList<Contact>();
    }

    public int getCount(){

        return contactArrayList.size();
    }

    public void addContact(Contact contact){
        contactArrayList.add(contact);
    }

    public  void removeContact(Contact contact){
        contactArrayList.remove(contact);
    }

    public Contact getContact(int id){

        for(int i=0;i<this.getCount();i++){
            if(Integer.parseInt(contactArrayList.get(i).id)==id)
                return contactArrayList.get(i);
        }

        return null;
    }
}
An ArrayList will hold the instances of Contact class and the methods aid in manipulating this list.

Step 5: Contacts List Adapter

The ContactsListAdapter will serve as the adapter for the contacts listview in our activity.
package sachinmuralig.me.simplemulticontactpicker;

import android.app.Activity;
import android.content.Context;
import android.database.DataSetObservable;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;


import java.util.ArrayList;


public class ContactsListAdapter extends BaseAdapter {

    Context context;
    ContactsList contactsList,filteredContactsList,selectedContactsList;
    String filterContactName;

    ContactsListAdapter(Context context, ContactsList contactsList){

        super();
        this.context = context;
        this.contactsList = contactsList;
        this.filteredContactsList=new ContactsList();
        this.selectedContactsList = new ContactsList();
        this.filterContactName = "";
    }

    public void filter(String filterContactName){



        filteredContactsList.contactArrayList.clear();

        if(filterContactName.isEmpty() || filterContactName.length()<1){
            filteredContactsList.contactArrayList.addAll(contactsList.contactArrayList);
            this.filterContactName = "";

        }
        else {
            this.filterContactName = filterContactName.toLowerCase().trim();
            for (int i = 0; i < contactsList.contactArrayList.size(); i++) {

                if (contactsList.contactArrayList.get(i).name.toLowerCase().contains(filterContactName))
                    filteredContactsList.addContact(contactsList.contactArrayList.get(i));
            }
        }
        notifyDataSetChanged();

    }

    public void addContacts(ArrayList<Contact> contacts){
        this.contactsList.contactArrayList.addAll(contacts);
        this.filter(this.filterContactName);

    }

    @Override
    public int getCount() {
        return filteredContactsList.getCount();
    }

    @Override
    public Contact getItem(int position) {
        return filteredContactsList.contactArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return Long.parseLong(this.getItem(position).id);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;

        if(convertView==null){
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();

            convertView = inflater.inflate(R.layout.contact_item, parent, false);

            viewHolder = new ViewHolder();
            viewHolder.chkContact = (CheckBox) convertView.findViewById(R.id.chk_contact);
            convertView.setTag(viewHolder);

        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.chkContact.setText(this.filteredContactsList.contactArrayList.get(position).toString());
        viewHolder.chkContact.setId(Integer.parseInt(this.filteredContactsList.contactArrayList.get(position).id));
        viewHolder.chkContact.setChecked(alreadySelected(filteredContactsList.contactArrayList.get(position)));

        viewHolder.chkContact.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Contact contact = filteredContactsList.getContact(buttonView.getId());

                if(contact!=null && isChecked && !alreadySelected(contact)){
                    selectedContactsList.addContact(contact);
                }
                else if(contact!=null && !isChecked){
                    selectedContactsList.removeContact(contact);
                }
            }
        });

        return convertView;
    }

    public boolean alreadySelected(Contact contact)
    {
        if(this.selectedContactsList.getContact(Integer.parseInt(contact.id))!=null)
            return true;

        return false;
    }

    public static class ViewHolder{

        CheckBox chkContact;
    }
}
contactsList - will hold the entire contacts in the device, filteredContactsList will hold a subset of the contactsList and is filtered based on the contact name, selectedContactsList also contains a subset of contactsList and this holds the contacts that are selected from the list using the checkbox. The getView method inflates a layout that basically just contains a checkbox, for each contact that is to be displayed. You can modify this, if you want to add other fields like email or contact image etc.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/chk_contact"

        />

</LinearLayout>
The 'filter' method is the one performing the filter actions and displaying the filtered contacts.

Step 6: Loading the contacts Asynchronously

The contactsList in the Adapter must be populated in a separate thread. An AsyncTask is used for the same.
package sachinmuralig.me.simplemulticontactpicker;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;


public class ContactsLoader extends AsyncTask<String,Void,Void> {

    ContactsListAdapter contactsListAdapter;
    Context context;
    private ArrayList<Contact> tempContactHolder;
    TextView txtProgress;
    int totalContactsCount,loadedContactsCount;


    ContactsLoader(Context context,ContactsListAdapter contactsListAdapter){
        this.context = context;
        this.contactsListAdapter = contactsListAdapter;
        this.tempContactHolder= new ArrayList<>();
        loadedContactsCount=0;
        totalContactsCount=0;
        txtProgress=null;
    }

    @Override
    protected Void doInBackground(String[] filters) {


        String filter = filters[0];

        ContentResolver contentResolver = context.getContentResolver();

        Uri uri = ContactsContract.Contacts.CONTENT_URI;

        String[] projection = new String[]{
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.HAS_PHONE_NUMBER
        };
        Cursor cursor;
        if(filter.length()>0) {
            cursor = contentResolver.query(
                    uri,
                    projection,
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
                    new String[]{filter},
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC"
            );
        }else {

            cursor = contentResolver.query(
                    uri,
                    projection,
                    null,
                    null,
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC"
            );

        }
        totalContactsCount = cursor.getCount();
        if(cursor!=null && cursor.getCount()>0){



            while(cursor.moveToNext()) {
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


                    Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                            new String[]{id},
                            null
                    );

                    if (phoneCursor != null && phoneCursor.getCount() > 0) {

                        while (phoneCursor.moveToNext()) {
                            String phId = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));

                            String customLabel = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));

                            String label = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(),
                                    phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)),
                                    customLabel
                            );

                            String phNo = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


                            tempContactHolder.add(new Contact(phId, name, phNo, label));



                        }
                        phoneCursor.close();

                    }

                }
                loadedContactsCount++;

                publishProgress();


            }
            cursor.close();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void[] v){




        if(this.tempContactHolder.size()>=100) {


            contactsListAdapter.addContacts(tempContactHolder);

            this.tempContactHolder.clear();

            if(txtProgress!=null){
                txtProgress.setVisibility(View.VISIBLE);
                String progressMessage = "Loading...("+loadedContactsCount+"/"+totalContactsCount+")";
                txtProgress.setText(progressMessage);
            }

        }

    }

    @Override
    protected void onPostExecute(Void v){

        contactsListAdapter.addContacts(tempContactHolder);
        tempContactHolder.clear();

        if(txtProgress!=null) {
            txtProgress.setText("");
            txtProgress.setVisibility(View.GONE);
        }
    }
}
A cursor is used to get the contacts with phone number and each contact is exploded, if it has multiple phone numbers. A buffer tempContactHolder is used to get a set of contacts at a time and then populate the adapter's contactsList using the adapter's addContacts() method. The addContacts() will update the contactsList, apply any existing filters and then update the ListView.

Step 7: Initialize the Listview, Search textbox, 'Done' Button and load contacts in the ContactPickerActivity


package sachinmuralig.me.simplemulticontactpicker;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ContactsPickerActivity extends AppCompatActivity {

    ListView contactsChooser;
    Button btnDone;
    EditText txtFilter;
    TextView txtLoadInfo;
    ContactsListAdapter contactsListAdapter;
    ContactsLoader contactsLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts_picker);

        contactsChooser = (ListView) findViewById(R.id.lst_contacts_chooser);
        btnDone = (Button) findViewById(R.id.btn_done);
        txtFilter = (EditText) findViewById(R.id.txt_filter);
        txtLoadInfo = (TextView) findViewById(R.id.txt_load_progress);


        contactsListAdapter = new ContactsListAdapter(this,new ContactsList());

        contactsChooser.setAdapter(contactsListAdapter);


        loadContacts("");



        txtFilter.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                contactsListAdapter.filter(s.toString());

            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });

        btnDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(contactsListAdapter.selectedContactsList.contactArrayList.isEmpty()){
                    setResult(RESULT_CANCELED);
                }
                else{

                    Intent resultIntent = new Intent();

                    resultIntent.putParcelableArrayListExtra("SelectedContacts", contactsListAdapter.selectedContactsList.contactArrayList);
                    setResult(RESULT_OK,resultIntent);

                }
                finish();

            }
        });
    }



    private void loadContacts(String filter){

        if(contactsLoader!=null && contactsLoader.getStatus()!= AsyncTask.Status.FINISHED){
            try{
                contactsLoader.cancel(true);
            }catch (Exception e){

            }
        }
        if(filter==null) filter="";

        try{
            //Running AsyncLoader with adapter and  filter
            contactsLoader = new ContactsLoader(this,contactsListAdapter);
            contactsLoader.txtProgress = txtLoadInfo;
            contactsLoader.execute(filter);
        }catch(Exception e){
            e.printStackTrace();
        }
    }




}
Note that the search textbox has a TextWatcher attached to it, that will call the filter method of the adapter on text change. The loadContacts() method will load all contacts from device and populate the adapter data members. The 'Done' button, on click will set the intent data as the selected contact list and will return the contacts to the activity which invoked startActivityForResult.

Step 8: Read the contacts on Activity result

From the Activity which invoked the ContactPickerActivity, you can read the selected contacts from onActivityResult. A sample implementation is as follows. (See MainActivity in the github project)
@Override
    public void onActivityResult(int requestCode,int resultCode,Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == CONTACT_PICK_REQUEST && resultCode == RESULT_OK){

            ArrayList<Contact> selectedContacts = data.getParcelableArrayListExtra("SelectedContacts");

            String display="";
            for(int i=0;i<selectedContacts.size();i++){

                display += (i+1)+". "+selectedContacts.get(i).toString()+"\n";

            }
            contactsDisplay.setText("Selected Contacts : \n\n"+display);

        }

    }

Setting Up Tomcat Server on Ubuntu

Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies. This post explains the installation and configuration of Tomcat on Ubuntu. I assume the reader to have basic knowledge in Ubuntu.
From Terminal/SSH :
  1. Run update
    sudo apt-get update
  2. You can see the list of tomcat packages by issuing a search command
    apt-cache search tomcat
  3. Install Apache Tomcat using the following command
    sudo apt-get install tomcat7
  4. Install Java
    sudo apt-get install default-jdk
  5. Now you have to set environment variables in bashrc
    sudo nano ~/.bashrc
    Append the following to bashrc (Omit contents after //)
    export JAVA_HOME=/usr/lib/jvm/default-java
    export CATALINA_HOME=/usr/share/tomcat7 //Or tomcat's directory
  6. Reload bashrc by
    . ~/.bashrc
  7. Now start tomcat by
    sudo /etc/init.d/tomcat7 start
  8. If everything was successful
    • sudo /etc/init.d/tomcat7 status
      will show a message, "Tomcat Servlet engine is running with pid [some pid]"
    • Typing server ip address:8080 in your browser will show default response (eg: http://123.456.78.90:8080)
    • Create a index.jsp at /var/lib/tomcat7/webapps/test and write in
      <%= "Hello" />
      Now typing in http://123.456.78.90:8080/test/index.jsp should show "Hello" (without quotes)
  9. If you want to change the default port (8080), you have to edit /etc/tomcat7/server.xml
    sudo nano /etc/tomcat7/server.xml
    Look for
    <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
    Refer Tomcat official site for more information
The /var/lib/tomcat7/webapps/ is where you will put your app files. In the list from apt-cache search tomcat you can find helpful stuffs like sample apps, docs etc. You may optionally install these using sudo apt-get install [package] command

Setup LAMP Server, phpMyAdmin, FTP (vsftpd) and .htaccess on Ubuntu

LAMP stands for Linux Apache MySQL and PHP. It is one of the most popular server configuration. This post explains how to set up a LAMP server on Ubuntu and then install commonly used development aids like phpMyAdmin for database, vsftpd for FTP access and then securing sensitive areas using .htaccess. The Steps below requires Root Privileges

  1. Install Ubuntu on the Intended System
  2. Access the terminal from GUI(Applications > Accessories > Terminal) or SSH 
  3. Install Apache by typing : 
    sudo apt-get update
    sudo apt-get install apache2
    Confirm the installation by typing in your server's IP address in your browser's address bar (eg: http://123.456.78.90), you should get a page saying "It Works!"
  4. Install MySQL with the following command
    sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
    sudo mysql_install_db
    sudo /usr/bin/mysql_secure_installation
    It may prompt you to set root password first and then prompt you to enter it again while setting up the configurations. Enter it as an when required. During the configuration, answer yes to all the yes/no prompts.
  5. Install PHP by typing in the following command
    sudo apt-get install php5
    After installing PHP5 you may want to install additional features like curl. You may see the available packages by typing in
    apt-cache search php5-
    This will give you a list of available packages. You may use sudo apt-get install [package-name] to install the required packages
  6. Voila! You have successfully set up a lamp server. Your php/html files may be put into /var/www/ folder. You may have to restart apache for the changs to take effect. You may do that by typing in
    sudo service apache2 restart
    To test your installation
    cd /var/www/
    sudo nano test.php
    Now type in
    <?php phpinfo(); ?>
    save,exit (CTRL+O to save CTRL+X to exit) and type in http://your server address/test.php (eg: http://123.456.78.9/test.php) and you will get a php info page.

Now you may optionally want to install phpMyAdmin, set up an FTP Server and Secure Sensitive areas(eg Admin panel and phpMyAdmin page) using .htaccess.

 phpMyAdmin installation may be done in two ways. Either you may use

 
sudo wget [url]
to download the zip file to your /var/www/ folder and unzip it using the unzip command, then use it by typing in http://server.address/[phpMyAdmin]( PS :[ ] should contain the folder name to which you unzipped the contents of the zip file downloaded, and you may have to install unzip using the sudo apt-get install command.), or you may install it as following
  1. sudo apt-get install phpmyadmin
    Select apache2 as server and answer YES when prompted on whether to Configure the database for phpmyadmin with dbconfig-common. You will also have to enter the MySQL root password and a login password.
  2. After the installation, add the following lines to /etc/apache2/apache2.conf (sudo nano /etc/apache2/apache2.conf)
    Include /etc/phpmyadmin/apache.conf
    and restart apache with sudo service apache2 restart .
  3. Access phpMyAdmin by typing in http://server.address/phpmyadmin

To Setup FTP server, you have to install and configure vsftpd.

  1. Install vsftpd with the following command
    sudo apt-get install vsftpd
  2. Configure vsftpd by editing /etc/vsftpd.conf
    sudo nano /etc/vsftpd.conf
    Now set the following values(Omit the ones after //)
    anonymous_enable=NO //IMPORTANT
    local_enable=YES
    write_enable=YES
    chroot_local_user=YES //This one restricts the local users to their chroot and denies access to other parts of server
    Save and Exit (CTRL+O CTRL+X). Sometimes(In case of errors) you may have to create a directory within the users home directory( mkdir /home/[username]/ftpFiles) and change the ownership to root(chown root:root /home/[username]) and do your changes in the ftpFiles directory.
  3. Now restart vsftpd
    sudo service vsftpd restart

Configuring .htaccess :

 htaccess file may be used to restrict access to sensitive folders/files in your web server

  1. To enable .htaccess, you need to edit /etc/apache2/sites-available/default.
    sudo nano /etc/apache2/sites-available/default
  2. Look for
    <Directory /var/www/>
      Options Indexes FollowSymLinks MultiViews
      AllowOverride None
      Order allow,deny
      allow from all
      # Uncomment this directive is you want to see apache2's
      # default start page (in /apache2-default) when you go to /
      #RedirectMatch ^/$ /apache2-default/
    </Directory>
    and Change AllowOverride None to AllowOverride All
  3. Restart apache
    sudo /etc/init.d/apache2 reload
  4. Now create a file named .htaccess in the directory that is to be secured
    sudo nano /path/to/directory/.htaccess
    and write
    AuthUserFile /your/path/to/.htpasswd
    AuthName "Authorization Required"
    AuthType Basic
    require valid-user
    To protect a single file, you may add the following to .htaccess file
    <Files "mypage.html"> Require valid-user </Files>
  5. The .htpasswd file will contain the authorized users list. It is advised to save it outside the www folder. To create a new .htpasswd file
    htpasswd -c /path/to/your/.htpasswd user1
    and enter the password. -c is used to create a new file, omit it to add new users to an existing .htpasswd file.
  6. Finally, add these to /etc/apache2/apache2.conf (sudo nano /etc/apache2/apache2.conf)
    <Directory /var/www> AllowOverride All </Directory>
    /var/www may be replaced with whatever path you wish to enable .htaccess, this will enable .htaccess for your whole website
  7. Restart apache server
    sudo /etc/init.d/apache2 restart
  8. Read More on .htaccess file