Saturday, 26 April 2014

working with crypto.js for hashing and encryption -javascript

Hashing is generally done for safe transferring of data from client to server and vice versa. In php there so many hashing algorithms are present as inbuilt functions.Similarly we have that hashing techniques as library in Javascript also.I had particularly searched for this library for developing hybrid apps using login functionality where REST API with PHP is used as backend to connect with a database to store username & hashed passwords.I was worried about passing the variables using REST API calls without hashing.since Hybrid Mobile Application mostly use javascripts for validations,making API calls and further appending i hashed my password for safety.i would like to show more about the function of crypto.js in which we could simply call the function and get our messages hashed in mean time.

javascipt Crypto.js for hashing variables

Installation:

Download the Zip file.Rollups folder contains all JS files.There is different JS file for Different crypting methods eg: MD5.SHA1 etc.

<script src="respective JS file for hashing" >
</script>

Live preview:

**if live preview is not loading results ! use demo option above.
var hash = CryptoJS.MD5("shivasurya");
document.getElementById('s').innerHTML=hash;
var hash = CryptoJS.SHA512("shivasurya");
document.getElementById('s3').innerHTML=hash;
var hash = CryptoJS.SHA1("shivasurya");
document.getElementById('s1').innerHTML=hash;
var hash = CryptoJS.SHA256("shivasurya");
document.getElementById('s2').innerHTML=hash;
var hash = CryptoJS.SHA3("shivasurya",{ outputLength: 224 });
document.getElementById('s4').innerHTML=hash;
var encrypted = CryptoJS.AES.encrypt('shivasurya is missing someone so badly', 'surya');
document.getElementById('s5').innerHTML=encrypted;
var decrypted = CryptoJS.AES.decrypt(encrypted, 'surya');
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);
document.getElementById('d5').innerHTML=plaintext;
var encrypted = CryptoJS.RC4.encrypt("Shiva is being missed by someone...", "surya");
document.getElementById('s7').innerHTML=encrypted;
var decrypted = CryptoJS.RC4.decrypt(encrypted, "surya");
var simple=decrypted.toString(CryptoJS.enc.Utf8);
document.getElementById('s8').innerHTML=simple;
var encrypted = CryptoJS.RC4.encrypt("love yourself", "pinku");
document.getElementById('s9').innerHTML=encrypted;
var decrypted = CryptoJS.RC4.decrypt(encrypted, "pinku");
var simple=decrypted.toString(CryptoJS.enc.Utf8);
document.getElementById('s10').innerHTML=simple;
See the Pen crypto.js ~ i-visionblog tutorials by s.shivasurya (@shivasurya) on CodePen.


MD5:

MD5 is common encryption done during these days since it easy to hash and it is one way hashing method .we could see this in many languages like PHP,java etc.. , but i wont encourage you to use MD5.

CryptoJS.MD5("shivasurya");    //calling this function returns md5 hash 

calling this function by passing arguments as string will return MD hash and we could store it in a Javascript variable.

SHA1:

SHA1 is also another encryption and hashing algorithm used to hash the message with different type of options.preferably SHA encryption is used for many purposes for repository handling and other purpose also.SHA is also good type of hashing.

CryptoJS.SHA1("shivasurya");   // calling this function return SHA1 hash

actually SHA1 was invented by NSA (National Security Agency) :p and they told that this method gets weakening as new methods are invented.


SHA2:

sha2 comes with two different options with 512 and 256 hashing.But it's not widely used by starters but provides security.

CryptoJS.SHA256("shivasurya"); 
CryptoJS.SHA512("harish");   //thos two function returns hash accordingly

SHA3:

sha3 comes finally which is more secured as per analysis.we could get desired output from 512,284 etc. length of hashed message.

CryptoJS.SHA3("Shivasurya",{ outputLength: 512 });
CryptoJS.SHA3("Shivasurya",{ outputLength: 224 });

so with additional parameter we could pass output length of our hashed message string.

AES(Advanced Encryption Standards):

AES is also best system for encrypting your messages with a passphrase key.by passing a key it would use the key to encrypt the variable.

var encrypted = CryptoJS.AES.encrypt('shivasurya is missing someone so badly', 'passphrase');
var decrypted = CryptoJS.AES.decrypt(encrypted, 'surya');
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);

here we called function and passed Message and passphrase as arguments and returned is saved in encrypted variable.Then with Decrypt function we have passed same passphrase and decrypted.as we need to convert into string format in UTF-8 format we call the additional function.

Similarly RABIT and RC4 works in the sameway by calling th function.

NOTE: each algorithm has different features as strength and weakness only developer must understand it and try to implement them with caution.Read more about more encryption weakness in stackoverflow website forum,many experts share their views on encryption.

report bug as comments/contact me s.shivasurya@gmail.com . share is care.

Wednesday, 23 April 2014

Mobile Detect in PHP and categorize different OS and Devices

According to +Mashable,Most of the Users nowadays use mobile phones,gadgets etc to access internet,apps and other services from them.so,it becomes handy for users and inorder to bring websites,standalone web application running in web browsers can be designed for the gadgets size and respective width and display the content appropriately for Easy access and better usage.You would have seen many site such as Google,Facebook release apps to load data for small gadgets efficiently instead of huge website with plugins.I would discuss about building apps from basic in future.in php we could detect the browser from headers and respond them accordingly!

php Mobile detection



Download the Above Mobile_detect.php and just call it by require or include function.

Installation:

<?php
include("Mobile_detect.php");
$found= new Mobile_detect;
?>

Sample code:

this code is just for sample there are lot of phones,OS,Browsers defined in Mobile_Detect.php just go through the class and call from creating object outside with appropriate spellings.


Screenshot from I-OS:

1)i have personally tested on Android,I-OS,Nokia ASHA and other web browsers.

2)generally this tutorials is very easy and there are lot of classes to check the mobile detection.

3)As far this class detect with the help of headers which carry browser information and OS.The authors of this class has took effort in finding Model Number|OS|Browser|Nature of Request and other parameters and made a simple class file for php.

As developer you must be known Browser header carry info about OS,Browser info and other variables within them to serve pages from web server.


a small snap of Request Headers.

report for doubts and bugs in comments.share is care.and you must not ask if user hide ip address and Browser information to me :p

Wednesday, 9 April 2014

how does facebook check-in works with Bing maps API with facebook pages (PART 1/3)

This is another post after Facebook custom stories for facebook application which made me more crazy to learn about the Bing Maps API to retrieve maps using AJAX 7 technique or REST API service provided by MICROSOFT.

you guys would be fascinated in updating status and photos ,events and others with check-in places and tag with your friends.Generally facebook always displays the Bing Maps for those check-in.These check-ins are actually born at Pages/place you create and give access via GPS to locate your device and get Latitude and longitude details to query Bing maps API and obtain maps to display to users and friends.



There are lot of parameters in getting map for exact location and corresponding maps for various platforms with various methods.i am here discussing about web(desktop) Rest API request and AJAX 7.

first of all let us see how to make location based request with BING API in this post:

1)
Go to Bing Maps API and register a new Application with Microsoft Live Account.


2) Create a Bing Map KEY for retrieval and authentication purpose(generally making API calls secure from anonymous calls)

3) Create with BASIC keys and provide as NON PROFIT as category for safer side usage.

4) Copy your KEY which is registered with correct Domain name URL.

Lets have a look at the simplest BING MAPS API CODE to retrieve location based on QUERY.
     <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()
{
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Aoyuj93YnzHbS8ZBLA6sdcvsdvzcxvcsyv2ASBjCJlICSIVobIZt3bZhwTzr-egVhMmlf-f8IKpM", mapTypeId:Microsoft.Maps.MapTypeId.road});

}

function ClickGeocode(credentials)
{
map.getCredentials(MakeGeocodeRequest);
}

function MakeGeocodeRequest(credentials)
{

var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" + encodeURI(document.getElementById('txtQuery').value) + "&output=json&jsonp=GeocodeCallback&key=" + credentials;

CallRestService(geocodeRequest);
}

function GeocodeCallback(result)
{
alert("Found location: " + result.resourceSets[0].resources[0].name);

if (result &&
result.resourceSets &&
result.resourceSets.length > 0 &&
result.resourceSets[0].resources &&
result.resourceSets[0].resources.length > 0)
{
// Set the map view using the returned bounding box
var bbox = result.resourceSets[0].resources[0].bbox;
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
map.setView({ bounds: viewBoundaries});

// Add a pushpin at the found location
var location = new Microsoft.Maps.Location(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1]);
var pushpin = new Microsoft.Maps.Pushpin(location);
map.entities.push(pushpin);
}
}

function CallRestService(request)
{
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}

</script>
See the Pen facebook like check-in [part 1/2] basic usage of bing API by s.shivasurya (@shivasurya) on CodePen.


Demo here - LINK 

so what happens in above code as simple and short and sweet:

1) we got the key from Bing API official used them rite at the place (credential mentioned in code)

2) using the key we made a user query place(eg:coimbatore) and which is sent via URL as REST API CALL with javascript help.

3) after STATUS 200 we get the result in JSON/XML (as we mention in URL PART)

4) by appending the result in browser we could get the place with Pushpin and we could get LATITUDE/LONGITUDE info also here which can be stored in database.

5) note that the resultant map is in form of Image as tiles (parts) can be saved and used personally.and the link can be useful later part.

thus we have successfully queried a place with longitud/latitude and an image.with this in next tutorial i would explain how pages/events/status check-in's works and btw we could create simple Check-in applications also.

i have tested this above code worled well and came across many errors! you can discuss errors with me hope i can provide solutions as comments/Email,Share is Care.

Saturday, 5 April 2014

working with chart.js to create graphs,charts using javascript

I was monitoring my traffic last few days and was viewing graph of visitors for my site and was curious to know the way of generation of chart in Blogger to display the traffic.& finally found an excellent solution for my own Admin site also.solution was - Chart.js. Humans are always attracted to the visually drawn graphs and charts rather than raw data in plain sheets.Thus,Chart.js enhances to create charts and load the graph easily in to web pages since it is javascript plugin.as we come across the comparison of data charts could make easy to differ one from the other and makes user to understand soon about it,Any way those carts will be very useful for the ADMIN panel for many back end website to analyse data and compare them.There are lot of Bootstrap themes to create admin with charts but this tutorial may enhance you to create your own charts for your website with data given.


Installation of Chart.js : Download

Just like how we use javascript in our sites,attach them as in <head></head> tags using script src.

<script src="chart.js"></script>

Generating chart :

since this chart.js uses HTML5 we use <canvas> tag to load our charts in web pages with referencing respecttive id's

<canvas id="preferred_name" height="preferred height" 
width="preferred width"></canvas>

Javascript to create a chart :

generally Chart.js gives many flavours such as LINE,BAR,RADAR,POLAR,PIE,DOUGH NUT chart types.
Essential part of the chart is Data that to in number formats and Labels and Data Range to prepare a chart.By using the below statement we could call the function with possible arguments through them.generally we pass DATA and OPTIONS as arguments to generate a graph in canvas area.

var ctx = document.getElementById("canvas_id_here").getContext("2d");
new Chart(ctx).Line(data,options);

the above code calls the function with specific arguments i.e DATA and OPTIONS.

data (argument of above function) :

data is generally declared as VAR in javascript and by further we could break it up with three different options such as LABELS as array ,DATASETS that contains some CSS property and RAW-DATA.
lets have a look at the LABEL which is declared as array i.e

label:['India','south africa','Australia','USA']

now about some CSS property for our graph look i.e they have been determined by DATASETS with that RAW-DATA is combined as array which is essentials to generate graph, i.e

datasets:
[{
fillColor:"rgba(your specified value for fill color in r,g,b,a format)",
strokeColor:"rgba(your specified value for strokes colour in r,g,b,a format)",
pointColor:"rgba(your specified color option in rgba format)",
pointStrokeColor:"hexa decimal value for colour",
data:[45,42,15,14,17,62,14]
}
]

Options(argument to function mentioned above):

there are so many options which defines our graph look add some css,Those Options are simple for readers to interpret so i don't want to explain those,just go through the options code.

Line.defaults = {
scaleOverlay : false,
scaleOverride : false,
scaleSteps : null,
scaleStepWidth : null,
scaleStartValue : null,
scaleLineColor : "rgba(0,0,0,.1)",
scaleLineWidth : 1,
scaleShowLabels : true,
scaleLabel : "<%=value%>",
scaleFontFamily : "'Arial'",
scaleFontSize : 12,
scaleFontStyle : "normal",
scaleFontColor : "#666",
scaleShowGridLines : true,
scaleGridLineColor : "rgba(0,0,0,.05)",
scaleGridLineWidth : 1,
bezierCurve : true,
pointDot : true,
pointDotRadius : 3,
pointDotStrokeWidth : 1,
datasetStroke : true,
datasetStrokeWidth : 2,
datasetFill : true,
animation : true,
animationSteps : 60,
animationEasing : "easeOutQuart",
onAnimationComplete : null

}

Final word:

Thus combining the above resource we could generate charts graphs in efficient manner.I have given only a start up use the resource from Chart.js official website for download and verfication & documentations to get more stuffs loaded.share is care.I will provide the demo soon as possible.