Wednesday, April 9, 2014

ENHANCING CAESAR CIPHER TECHNIQUE

A Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and widely known encryption techniques. In this type of substitution cipher each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.


As with all single alphabet substitution ciphers, the Caesar cipher is easily broken and in modern practice offers essentially no communication security.

Example

The transformation can be represented by aligning two alphabets; the cipher alphabet is the plain alphabet rotated left or right by some number of positions. For instance, here is a Caesar cipher using a left rotation of three places, equivalent to a right shift of 23 (the shift parameter is used as the key):
Plain:    ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher:   XYZABCDEFGHIJKLMNOPQRSTUVW

When encrypting, a person looks up each letter of the message in the "plain" line and writes down the corresponding letter in the "cipher" line. Deciphering is done in reverse, with a right shift of 3.
Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
Plaintext:  the quick brown fox jumps over the lazy dog

Breaking the Cipher

The Caesar cipher can be easily broken even in a cipher text-only scenario. Two situations can be considered:

  1. An attacker knows (or guesses) that some sort of simple substitution cipher has been used, but not specifically that it is a Caesar scheme;
  2. An attacker knows that a Caesar cipher is in use, but does not know the shift value.
In the first case, the cipher can be broken using the same techniques as for a general simple substitution cipher, such as frequency analysis or pattern words. While solving, it is likely that an attacker will quickly notice the regularity in the solution and deduce that a Caesar cipher is the specific algorithm employed.

In the second instance, breaking the scheme is even more straightforward. Since there are only a limited number of possible shifts (26 in English), they can each be tested in turn in a brute force attack. One way to do this is to write out a snippet of the cipher text in a table of all possible shifts — a technique sometimes known as "completing the plain component".

Decryption
shift
Candidate plaintext
0
exxegoexsrgi
1
dwwdfndwrqfh
2
cvvcemcvqpeg
3
buubdlbupodf
4
attackatonce
5
zsszbjzsnmbd
6
yrryaiyrmlac
...
23
haahjrhavujl
24
gzzgiqgzutik
25
fyyfhpfytshj



















The example given is for the cipher text "EXXEGOEXSRGI"; the plaintext is instantly recognizable by eye at a shift of four. Another way of viewing this method is that, under each letter of the cipher text, the entire alphabet is written out in reverse starting at that letter. This attack can be accelerated using a set of strips prepared with the alphabet written down them in reverse order. The strips are then aligned to form the cipher text along one row, and the plaintext should appear in one of the other rows.
Another brute force approach is to match up the frequency distribution of the letters. By graphing the frequencies of letters in the cipher text, and by knowing the expected distribution of those letters in the original language of the plaintext, a human can easily spot the value of the shift by looking at the displacement of particular features of the graph. This is known as frequency analysis.

Enhancing the Cipher

Based on the explanation provided we see that main problem with Caesar cipher is predictability. Two main issues that cause this predictability are:

  1.  Fixed index for shifting characters
  2.  Knowledge about character at a given index.
We can enhance the strength of the cipher by overcoming these 2 issues. Let us look into these 2 issues and how we can overcome them:

Fixed index for shifting characters

As you read earlier in Caesar cipher each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. Thus if attacker manages to figure out shift index he can easily break the cipher text. We can overcome this making the shift index variable. Consider the example shown in the table above. Instead of using a fixed index of 4, the index could be length of the string I.e 12. Using such variable index will make the cipher text difficult to predict. In addition to this advantage, two similar word/phrase with different lengths would have different cipher texts. For example attackatonce and attackonce will have no pattern in common even though the word “attack” and “once” are being repeated. This happens because the string length is different thus the shift index will be different.

Knowledge about character at a given index

In our previous example we also observed while shifting the alphabets, the alphabet at new position occurs as per alphabetical order of A-Z. Thus if attacker manages to figure out the shift index he can easily find out all the characters in the given cipher text. Besides making the shift index dynamic we can also shuffle the alphabetical order by which the alphabets won’t be substituted as per the default alphabetic order. For example on a shift index of 4 if we were suppose to substitute character “a”, by alphabetical order the new character would be “d”. However if we do not follow alphabetical order and replace the characters basis of shuffled set of characters it will make it difficult for attacker to derive the plain text. For this we need to have a shuffled set of alphabets.

Implementation


Enhanced Caesar cipher can be implemented in following manner:

  1. Determine the shift index on the basis of string length.
  2. Determine the position of character to be replaced in the shuffled string.
  3. Add the shift index to the position to determine the position of new character.
  4. Determine the character at new position. If the new position is more than the length of the shuffled set then loop again after the loop index reaches the length of shuffled set.
For example
The plain text to be ciphered is “america”. The shuffled subset is “adwxyzefijklmnoghpqrstbcuv”. The cipher for this will be “frnagyf”. In this example “a” is substituted with “e”. For this substitution we 1st determine the position of “a” in shuffled subset. This is 1. Now we need to determine the shift index, which is length of string i.e. 7. Thus with a right shift of 7,”a” gives “f” as per the shuffled set. Similar substitution process will be applied to each character in the given word.

The Outcome

An enhanced cipher technique derived from a simple substitution cipher is much effective compared to its original version.

Wednesday, November 27, 2013

Using jshybugger to debug HTML, CSS and javascript on native Android browser


Debugging web applications on android device as been a challenging issue. This becomes further challenging when the debugging is to be done on native browser of Android.
The debugging tools provided by native android browser are insufficient to perform detailed analysis of the problem. (In case you're not aware about these tools and wish to check em out type "about:debug" in your native browser's address bar and then check your settings menu for debug options).
While looking for solution of one of my problems on native android browser i came across this tool which does the job brilliantly! Its name is jsHybugger (https://www.jshybugger.com/#!/).

When you use jsHybugger App, jsHybugger runs on your device and provides two things:
  • a proxy between the native Android browser and the web server where your mobile web pages are hosted
  • a communication endpoint for the debugging frontend on your development machine
Using this very simple and straight forward. Steps for it are as follow:

  1. Download and install the APK file for jsHybugger App, either through a direct download on your device or from your development machine using ADB.
  2. Start jsHybugger App on your device and adjust the configuration (see parameters below).
  3. Open the native Android browser via Open browser. The browser automatically navigates to the specified URL.
  4. Connect to jsHybugger.
  5. Set port forwarding to enabled in ADB interface. For more information on how to use ADB extension please refer to my earlier blog post (http://anirudhprabhu.blogspot.in/2013/08/debugging-website-or-web-application.html)

Parameters
  • Remote host: IP address or hostname of the remote web server
  • Remote port: HTTP port of the remote web server (usually 80)
  • URI: URI of the start page, e.g. /index.html
Control
  • Stop service: Stop service on device
  • Start service: Start service on device
  • Open browser: Start the Android browser with the configured URL
  • Clear cache: Clear jsHybugger cache
  • Log viewer: Display HTTP access log

Happy Debugging!!!

Sunday, October 6, 2013

Basics of Jasmine Framework

Hey folks today we will look into some basics of jasmine. Jasmine is a behavior-driven testing framework for JavaScript programming language. It’s a bunch of tools that you can use to test JavaScript code. you can test your code against specifications that you write. If your code should work in a certain way, Jasmine helps you express
that intention in code.




Getting Started
1. Start by downloading the latest standalone release of Jasmine (https://github.com/pivotal/jasmine/downloads). Unzip it.

2. In your html include scripts in following order:

<script type="text/javascript" src="jasmine/lib/jasmine-core/jasmine.js"></script>
<script type="text/javascript" src="jasmine/lib/jasmine-core/jasmine-html.js"></script>
<script type="text/javascript" src="jasmine/lib/jasmine-core/boot.js"></script>

3. Now include you spec file. This is a normal js file in which your test cases are written. So in our case it will be

<!-- Spec files-->
<script type="text/javascript" src="spec/calculatorSpec.js"></script>

Please not that always include spec file before actual code file.

4. Now we include the code file

<!-- Src files-->
<script type="text/javascript" src="src/calculator.js"></script>

Which will contain our logic

Now here are few things you need to know before we look into the code of spec file

* A describe("some name"...) is called a suite. This name of suite would usually be a component of your application.
* Inside of suite is the it() block. This is called specification. Its is a Js function that says what a small  peice of your component must do.

* Matchers: This basically takes the arguement to the expect function and checks to see if it satisfies some criterion in the matcher. for example: toEqual()

Now lets take a look at the spec

You can view the example here: http://designmantra.x10.mx/jasmine/

We are carrying out five tests here:
1. Storing current value
2. Addition yields correct results. 
3. Substraction yields correct results.
4. Multiplication yields correct results.
5. Division yields correct results.

Here is the code for spec file:

describe("Calculator",function(){
it("Should have current value stored",function(){
expect(calculator.currentValue).toBeDefined();
});
beforeEach(function(){
calculator.currentValue = 0
});
describe("Addition module",function(){
it("Should add two numbers",function(){
expect(calculator.add(5)).toEqual(5);
expect(calculator.add(5)).toEqual(10);
})
});
describe("Substraction module",function(){
it("Should substract two numbers",function(){
expect(calculator.substract(5)).toEqual(-5);
})
})
describe("Multiplication module",function(){
it("Should multiply two numbers",function(){
calculator.currentValue = 5;
expect(calculator.multiply(5)).toEqual(25);
})
})
describe("Division module",function(){
it("Should divide two numbers",function(){
expect(calculator.divide(5)).toEqual(5);
})
})
})

Here is the corresponding code for calculator.js code

var calculator = {
currentValue : 0,
add: function(num){
return this.currentValue += num;
},
substract:function(num){
return this.currentValue -= num;
},
multiply:function(num){
return this.currentValue *= num;
},
divide:function(num){
return 25/num;
}
}

Hope this article was useful. For any queries write me at prabhu.anirudh@live.in.

Saturday, August 24, 2013

Debugging a website or web application using Chrome and Android device made easy

In this post we will look into simple steps of how to debug your website or you web application on chrome desktop while you are viewing it on chrome on android. Here is what you need:

1. An android device with chrome installed on it.
2. Device drivers for that android device (must have as this will enable USB Debugging)
3. ADB extension (https://chrome.google.com/webstore/detail/adb/dpngiggdglpdnjdoaefidgiigpemgage)

Here is how you perform debugging:

Step 1. Install ADB extension in your chrome on desktop
Step 2. Install device drivers for your android device
Step 3. Enable USB debugging:
Step 4: Enable USB debugging within chrome for android as shown below:

Step 5. In chrome on desktop click on Start ADB
Step 6: Click on view inspection target to start debugging






Saturday, April 27, 2013

Introduction to SASS

In this blog post i will be giving you a short tutorial on SASS that will clear most of the fundamental syntax and how the language work.
Sass is an extension of CSS3, adding nested rulesvariablesmixins,selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
You can see how to install SASS here: http://sass-lang.com/

FUNDAMENTALS:

1.
 Declaring variables in SASS: You declare variables in SASS using following notation :: 


$blue: #00F;

This can be used in you scss file as follows:

color: $blue;

2. Declaring list in SASS: You declare list in SASS using following notations ::

$icons: twitter facebook youtube.

List comes handy when you want generate a set of element in some common fashion. For example you might wish to generate a series of divs with different background images and having same dimensions. You can do that in following manner:

@each $social in $icon{
##{$social}{background: image-url("avatars/#{$social}.png") no-repeat}
}

MIXINS:

Mixin is a way by which you can declare a reusable chunk of code. This can also be called as advanced version of variable.
Example:


@mixin border-radius($radius:10px){
border-radius: $radius;
-moz-border-radius: $radius;
-webkit-border-radius: $radius;
-o-border-radius: $radius;
}

These mixins can be used in your code in following manner:

@include border-radius(5px)

SELECTOR INHERITANCE:

In SASS, you can inherit styles from one class into another class. This can be done in following manner:

.primaryClass{
/*Style declaration*/
}

.secondary{
@extend .primaryClass;
}

This feature can come handy when you want to reuse certain style attributes across multiple classes like fonts, color.

@IMPORT

Sass extends the CSS @import rule to allow it to import SCSS and Sass files. All imported SCSS and Sass files will be merged together into a single CSS output file. In addition, any variables or mixins defined in imported files can be used in the main file.

Example:

@import "reset";

NESTING SELECTORS

Sass avoids repetition by nesting selectors within one another. The same thing works with properties.

Example for this:


.nav{
background-color: $brandcolor;
width:100%;
height: 64px;
@include setMargin("10px","20px","30px","40px");
.container{
.items{
position: relative;
.submenu{
width:96px;
@include border-radius(5px)
}
}
}
}

When compiled this will output:

.nav {
  background-color: #ac2428;
  width: 100%;
  height: 64px;
  margin: 10px 20px 30px 40px;
 }
.nav .container .items {
  position: relative;
}
    
.nav .container .items .submenu {
      width: 96px;
      border-radius: 5px;
      -moz-border-radius: 5px;
      -webkit-border-radius: 5px;
      -o-border-radius: 5px; 
}

USING LISTS AND @each

We can process a list to get some meaningful styles. Here is an example where i m creating social classes based on the list of social names that have been provided in the list.

$icon:twitter facebook youtube;
@each $social in $icon{
##{$social}{background: image-url("avatars/#{$social}.png") no-repeat}
}

BUILD YOUR OWN FUNCTION

It is possible to define your own functions in sass and use them in any value or script context.


@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}

#sidebar { width: grid-width(5); }

LOOPING IN SASS USING FOR LOOP

We have provision in SASS where we can loop using for loop. Example of this:

$class-slug: for;
@for $i from 1 through 4{
.#{$class-slug}-#{$i}{
@if $i > 2{
width:60px;
}
@else{
width:40px;
}
}
}

As you can see in this example we are generating four classes using for loop. Within this loop we see the number of iteration and assign the width accordingly. This also shows implementation of if.

GENERATING CSS SHORTHANDS USING SASS

While working on SASS when writing this tutorials i cam across a scenario where i wanted to write a mixin that would throw me shorthand declaration instead of providing me separate declarations.
For example how would you generate a something like

margin: 10px 20px 30px 40px;

using SASS? Here's how you do it:


@mixin setMargin($top,$right,$bottom,$left){
margin: #{$top} #{$right} #{$bottom} #{$left};
}

You can use this mixin in following manner

@include setMargin("10px","20px","30px","40px");

Well this is it for fundamentals of SASS. You can also refer to this manual for trying out more stuff in SASS:
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html

Yet another good site for reference is:
http://thesassway.com/

For any queries feel free to write to : prabhu.anirudh@live.in


Saturday, December 22, 2012

Getting started with knockout js

Today we will be seeing how to work with knockout js. Objective of this article is to quickly get you up and running with this MVVM framework.

So what is Knockout JS

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

Some key things to understand:
1. observables:  model properties as observables, because these are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies.

2. observable array: If you want to detect and respond to changes on one object, you’d use observables. If you want to detect and respond to changes of a collection of things, use an observableArray

3. computed : these are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change.

For this article we will be creating a view model for simple ma thematic operations like addition, subtraction, multiplication etc...


The code for our view model looks as follows:


function mathematica(){

var self = this;
this.firstNumber = ko.observable(2);
this.secondNumber = ko.observable(3);
//Start off with computed values
this.addition = ko.computed(function(){
var add = this.firstNumber() + this.secondNumber()
return add;
},this);
this.substraction = ko.computed(function(){
return this.firstNumber() - this.secondNumber()
},this)
this.multiplication = ko.computed(function(){
return this.firstNumber() * this.secondNumber()
},this)
this.division = ko.computed(function(){
return this.firstNumber() / this.secondNumber()
},this)
this.squareRootFirst = ko.computed(function(){
return Math.sqrt(this.firstNumber())
},this);
//Compute the value multiplication table and assign it to the observable array
this.MultiplicationTableGenerate = ko.computed(function(){
var testArray = new Array();
for (var i = 0; i <= 10; i++) {
testArray[i] = i*this.firstNumber();
};
return testArray;
},this);
this.TableValue = ko.observableArray(this.MultiplicationTableGenerate());
this.recalculateTable = function(){
var inputtedNumber = document.getElementById("firstNumber").value;
this.firstNumber(parseInt(inputtedNumber));
var newArray = new Array();
for (var i = 0; i <= 10; i++) {
newArray[i] = i*inputtedNumber;
};
this.TableValue(newArray)
}
this.setFirstNumber = function() {
var inputtedNumber = document.getElementById("firstNumber").value;
this.firstNumber(parseInt(inputtedNumber));
}
this.setSecondNumber = function() {
var inputtedNumber = document.getElementById("secondNumber").value;
console.log(inputtedNumber);
this.secondNumber(parseInt(inputtedNumber));
}
}

in this code, we first create observables "firstNumber" and "secondNumber". Rest of the variables like addition, subtraction, etc are computed.
In case you’re wondering what the second parameter to ko.computed is (the bit where we passed this in the preceding code), that defines the value of this when evaluating the computed observable. Without passing it in, it would not have been possible to refer to this.firstNumber() or this.secondNumber().

To activate Knockout, add the following line to a 

var instant = new mathematica();
ko.applyBindings(instant)