Saturday, June 1, 2019

Count the Number of Bits Set to One using Java



In this article, we’ll be counting the number of bits set to one using Java. To make it clearer, let’s take number 6 as an example. Number 6 is written as 1102 in binary. From our example, we’ll get the output as 2, as there are 2 ones in the binary of the converted number. In this process, we use 2 concepts related to the binary numbers.   
  • Binary Comparison
  • Binary Shifting

What is Binary Comparison?

In our example, we are using and operation (&) for the binary comparison. It also called as bitwise and operation. Let’s take a look at the below example to understand how this binary comparison works with the & operator.

For Eg: Let’s take n as 4 and evaluate the (n&1) operation.

Logic Gate of AND operation
n = 00000000  00000100

A
B
Result
0
0
0
0
1
0
1
0
0
1
1
1

1 = 00000000  00000001 AND
------------------------------
0 = 00000000  00000000
==================


From the bitwise-and, result of (n&1); where n=4 is 0. This is frequently used to extract the Least Significant Bit (LSB) from a given number.

What is Binary Shifting?

Binary shifting refers to as shifting of all the bits in the operand used to a particular direction assigned by the user. There are 2 types of shifting.
  • ·         Arithmetic Left shifting(<<)
  • ·         Arithmetic Right shifting(>>)

In our example, arithmetic Right shifting is used to shift all the bits to the right side. To understand how arithmetic right shifting works, take a look at the below example.

When n = 12                                            Binary Representation = 1100

Let’s apply right shifting to the 12 => 1100>>1 which shifts one bit to right at a time.
1st Iteration – Last 0 is removed (110)
2nd Iteration – Next 0 is removed (11)

public static void main(String args[]){
      System.out.print("Please enter the number: ");
      //take the input from the user
      Scanner input = new Scanner(System.in);
      int number = input.nextInt();
             
      System.out.print("Total number of 1s
                            : "+countBitsSetToOne(number));
      //close the scanner instance
      input.close();
}
       
public static int countBitsSetToOne(int number) {
      int count = 0;
      while (number > 0){
        //binary comparison
        count = count + (number & 1);
        //binary shifting
        number = number >> 1;
      }
      return count;
}


In here, we have created a static method which takes one integer parameter. First, it checks whether the number is equal to zero or not. If the number is equal to zero, it will return the default value of the count variable; which is zero. When the number is greater than zero, it will increase the count while doing the bitwise-and operation. As I said earlier, bitwise-and returns the LSB of the number passed in. Finally, binary shifting is done to shift all the bits to right one by one until the whole iteration ends. When the number becomes zero, while loop terminates and returns the count.             

Basic Authentication in Web API



Authentication is the process of identifying the users based on their username and password. This restricts unauthorized people getting access to data or applications. There are 3 common ways of ensuring authentication. The basic method is to validate the username and password. Next method is to use smart cards and the final method is to use biometric details of the user.
From this post, we are going to talk about username and password authentication using a web API. In here we are using AuthorizationFilterAttribute class which is readily available from the System.Web.Http.Filters package to implement the authentication.

Why we use Authorization Filter class?

Authorization filters are the easiest way of handling the requests from the user and identifies whether the user has access to the application. Otherwise, UnauthorizedAccess exception will be thrown from the class. For the authorization, we will create our own class inheriting the features of the AuthorizationFilterAttribute class and overrides the OnAuthorization method by passing an action parameter. It is the method used to provide the request and response to the data we are passing.
namespace Authentication
class AuthenticationClass : AuthorizationFilterAttribute 
{ 
       public override void OnAuthorization(HttpActionContext httpActionContext) 
       { 
           base.OnAuthorization(httpActionContext); 
       } 
}

The main purpose of using an HTTPAction object is to check whether the header, we are passing is null or not. For any invalid header, OnAuthorization returns unauthorized access which is the 401 error code. Thereby no unauthorized third party can access the information. Hence, it is important to check the header before proceeding to the next section of the code. Now let’s override the OnAuthorization method with our customizations.


public override void OnAuthorization(HttpActionContext httpActionContext)  {      
           if (httpActionContext.Request.Headers.Authorization != null)  { 
                     // code
            }
            else { 
              httpActionContext.unauthorizedResponse =
           httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
            }
}

For more information regarding the OnAuthorization() method, check the below link: https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.authorizeattribute.onauthorization?view=aspnet-mvc-5.2

Next, we have to get the user credentials and check it against the values from the database. For this example, I’ll be using 2 dummy values to illustrate the concept. Hence, this method will return true as a result of authorized login and return false for any unauthorized credentials.
public static bool isAuthorized(string username, string password)  {
           if( username == "admin" && password == "admin123"){
                return true;
            }
           else{
               return false;
           } 
}

So far we have overridden the OnAuthorization() method and created a new method to check the validity of the credentials. Now it’s time to implement the OnAuthorization() method combining all the components we created thus far. First, we need to create a token to store the headers of the request. For that, we use the headers property available in the HttpActionContext.
var accessToken = httpActionContext.Request.Headers.Authorization.Parameter;

As a security measure, AuthorizationFilterAttribute class encodes our credentials into the base64 encoding scheme. To get the original values we need to decode those back using UTF8 encoding scheme. For this conversion, we need to use the default method available in the System.Text library called FromBase64String.
var decodedaccessToken = System.Text.Encoding.UTF8.GetString( 
                                 Convert.FromBase64String (accessToken)); 

After the decoding, we will obtain the username and password separated by a colon. To separate out them into 2 parts, we need to use the split function available for the strings.
 var credentials = decodedaccessToken.Split(':'); 
string user = credentials[0]; // assigning values to each variable
string passwrd = credentials[1];


To proceed further, we need to check the validity of the credentials. For that, we need to pass the variables “user” and “password” to the method that we created to check the authorization. On the return of “true” function will proceeds and for “false”, unauthorized access code is returned.
  if (isAuthorized (user, passwrd)){
        Thread.CurrentPrincipal =
                           new GenericPrincipal(new GenericIdentity(user), null); 
  } 
  else 
  { 
      httpActionContext. unauthorizedResponse =
                                             httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
  } 

If the isAuthorized() returns true, new instance of GenericPrincipal() is created and current state of user is assigned to it. Generic Principal takes two parameters, user identity and an array of roles names that the particular user belongs to. In here we will set that array to null and user identity as the username of the user. By now we have created the complete code to authorize the user.
For more information about the Generic Principle, take a look at the below link:

Now it’s the time to create a small API, to call the function we created. For that we need to create a controller class from the namespace we used earlier “Authentification” and this class will inherits features from the ApiController class.
namespace Authentication.Controllers 
{ 
    public class BasicController : ApiController 
    { 
         // GET api/value/id
         public string GetID(int id)
         {
            return id.ToString();
         }
    } 
} 


Finally, if you are using HTTP client like Postman to check this, it is important to set the Type as “Basic Auth”.