Figer's Technology Consulting | December 2014

Symetrical Triple DES encryption in Java and decryption in VB.NET

Java Code
---------------



package JavaTripleDES;



import java.security.spec.KeySpec;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESedeKeySpec;



import org.apache.commons.codec.binary.Base64; <strong>//This needs to be downloaded and added to eclipse as an external library</strong>





public class DESEncryption {



private static final String UNICODE_FORMAT = "UTF8";

public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";

private final KeySpec myKeySpec;

private final SecretKeyFactory mySecretKeyFactory;

private final Cipher cipher;

private final byte[] keyAsBytes;

private final String myEncryptionKey;

private final String myEncryptionScheme;

private final SecretKey key;



public DESEncryption() throws Exception {

myEncryptionKey = "hisIsSecretEncryptionKey";

myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;

keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);

myKeySpec = new DESedeKeySpec(keyAsBytes);

mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);

cipher = Cipher.getInstance(myEncryptionScheme);

key = mySecretKeyFactory.generateSecret(myKeySpec);

}



/**

* Method To Encrypt The String

*/

public String encrypt(String unencryptedString) {

String encryptedString = null;

try {

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);

byte[] encryptedText = cipher.doFinal(plainText);

encryptedString = new String(Base64.encodeBase64(encryptedText));

} catch (Exception e) {

e.printStackTrace();

}

return encryptedString;

}



/**

* Method To Decrypt An Encrypted String

*/

public String decrypt(String encryptedString) {

String decryptedText = null;

try {

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] encryptedText = Base64.decodeBase64(encryptedString);

byte[] plainText = cipher.doFinal(encryptedText);

decryptedText = bytes2String(plainText);

} catch (Exception e) {

e.printStackTrace();

}

return decryptedText;

}



/**

* Returns String From An Array Of Bytes

*/

private static String bytes2String(byte[] bytes) {

StringBuilder stringBuffer = new StringBuilder();

for (int i = 0; i &lt; bytes.length; i++) {

stringBuffer.append((char) bytes[i]);

}

return stringBuffer.toString();

}



/**

* Testing the DES Encryption And Decryption Technique

*/

public static void main(String args[]) throws Exception {

DESEncryption myEncryptor = new DESEncryption();



String stringToEncrypt = "12345678&amp;First&amp;Last&amp;M&amp;Lake%20Park";

String encrypted = myEncryptor.encrypt(stringToEncrypt);

String decrypted = myEncryptor.decrypt(encrypted);



System.out.println("String To Encrypt: " + stringToEncrypt);

System.out.println("Encrypted Value  : " + encrypted);

System.out.println("Decrypted Value  : " + decrypted);

}

}

-------------------

VB.NET Code
--------------------

Imports System.IO

Imports System.Text

Imports System.Security.Cryptography



Public Class Form1



Private Shared ReadOnly encryptionKey As String = "ThisIsSecretEncryptionKe" <strong>//Key Length matters which is why the trailing 'y' is missing</strong>

Public Sub New()

InitializeComponent() //This is added automatically

Dim strTestValueFromJava As String = "6JtWysSeMxc1L6I0wRJi9EOakFWfOo/+uM8K0PnwhEAYenfxZ1Yw9w=="

Dim dencryptedData As String = Decrypt(strShouldBe, False)

End Sub



Public Shared Function Decrypt(cipherString As String, useHashing As Boolean) As String

Dim keyArray As Byte()

Dim toEncryptArray As Byte() = Convert.FromBase64String(cipherString.Replace(" "c, "+"c))



If useHashing Then

' If hashing was used get the hash code with regards to your key

Dim hashmd5 As New MD5CryptoServiceProvider()

keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey))

hashmd5.Clear()

Else

' If hashing was not implemented get the byte code of the key

keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey)

End If



' Set the secret key for the tripleDES algorithm

Dim tdes As New TripleDESCryptoServiceProvider()

tdes.Key = keyArray

tdes.Mode = CipherMode.ECB

tdes.Padding = PaddingMode.PKCS7



Dim cTransform As ICryptoTransform = tdes.CreateDecryptor()

Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)

tdes.Clear()



' Return the Clear decrypted TEXT

Return UTF8Encoding.UTF8.GetString(resultArray)

End Function

End Class

C# Web API Forms Authentication using JQuery Ajax calls from HTML5 app

------------------

Enable Forms Authentication

-------------------

add to web.config

<system.web>

<authentication mode="Forms" />


LogonModel.cs

--------------

namespace DeliveryApp.Models

{

using System;

using System.Collections.Generic;


public class LogOnModel

{

public string Username { get; set; }

public string Password { get; set; }

}

}


AccountController.cs

--------------------

using System.Web.Http;

using System.Web.Security;

using DeliveryApp.Models;

using System.Web;

using System.Security.Principal;

using System.Web.Helpers;


namespace DeliveryApp.Controllers

{

public class AccountController : ApiController

{

public bool Post(LogOnModel UserAccount)

{

if (UserAccount != null)

{

//Change this to hit the SQL server to get the accounts and validate

if (UserAccount.Username == "test" && UserAccount.Password == "test12")

{

FormsAuthentication.SetAuthCookie(UserAccount.Username, false);

return true;

}

}


return false;

}

}

}


Javascript ajax function to login - once logged in, it creates cookie that all other ajax calls auto send with the request.

<strong>Must be over SSL to be secure</strong>

---------------------------------


function login() {


var user = $('#user').val();

var pass = $('#pass').val();


$.ajax({

type: 'Post',

url: webapiURL + '/Api/Account',

data: { Username: user, Password: pass },

dataType: 'json',

success: function(data) {


//Login Success

window.location = "index.html";

},

error: function(msg) {

alert("Error Logging in - " + msg.responsetext);

}

});

}


Finally place  [Authorize] directly above every web api controller function except for the Login one. This will restrict access unless the user has authenticated.

CSS rounded image corners

Simple CSS styling to add to any image to add rounded corners


style="border: 2px solid black;border-radius: 30px;-moz-border-radius: 30px;-khtml-border-radius: 30px;-webkit-border-radius: 30px;"

C# eventhandler passing variables from Usercontrol to parent page

In this example I'm passing a telerik radgrid collection to the parent page from the child usercontrol when the user selects a row.


-----------------------------

User Controls (.ascx)

-----------------------------


public partial class NPISearch : System.Web.UI.UserControl 

//This is just the standard class section when a user control is created</em>


{

<strong>public delegate void ReturnNPISearchEvent (Telerik.Web.UI.GridDataItemCollection e); //You need to add this line</strong>


Page_Load() { 

//Standard Page_load event

protected void grdNPI_SelectedIndexChanged(object sender, EventArgs e) 

//Here is the function that raises the event to the parent page

{

//Null check makes sure the main page is attached to the event

if (this.ReturnNPISearch != null)

this.ReturnNPISearch(grdNPI.MasterTableView.Items);

}


}


-----------------------------------

Parent page (.aspx)

---------------------------------


protected void Page_Load(object sender, EventArgs e) //Add the line below in Page_Load()

{

NPISearch1.ReturnNPISearch += new      MCRASunshine.Account.NPISearch.ReturnNPISearchEvent(MyEventHandlerFunction_ReturnNPISearch);

}


//This is the function that is called when the usercontrol event is fired

public void MyEventHandlerFunction_ReturnNPISearch(Telerik.Web.UI.GridDataItemCollection e)


{

this.divSearch.Visible = false;

this.divAddInfo.Visible = true;

txtInfoNPI.Enabled = false;


//set values in textboxes

foreach (Telerik.Web.UI.GridDataItem dataItem in e)

{

if (dataItem.Selected == true)

{

this.txtInfoFirstName.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dataItem.Cells[4].Text.ToLower().Trim('"'));

this.txtInfoLastName.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dataItem.Cells[3].Text.ToLower().Trim('"'));

this.txtInfoNPI.Text = dataItem.Cells[5].Text.Trim('"');

jQuery dynamically set html select dropdownlist item

This was not obvious at all to me, but you have to invoke the select elements .Change() event to see the selected item actually reflected on the page, seems foolish, but the code is simple:


$("#SelectItem").val("SetThisValue");

$('#SelectItem').change();

Enable Access-Control-Allow-Origin in IIS6 &amp; IIS7 for webapi calls

To allow your newly created webapi web service calls to be accessed from ajax post calls from another website you need to enable this setting in either IIS6 or IIS7 IIS6
  1. Open Internet Information Service (IIS) Manager
  2. Right click the site you want to enable CORS for and go to Properties
  3. Change to the HTTP Headers tab
  4. In the Custom HTTP headers section, click Add
  5. Enter Access-Control-Allow-Origin as the header name
  6. Enter * as the header value
  7. Click Ok twice


IIS7 - Add this to your web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

Resolve VS 2010 script debugging and IE 10

If you are getting an error Attached the Script debugger to process failed after installing IE 10  you need to run this script using CMD in administrator mode.


regsvr32.exe "%ProgramFiles(x86)%\Common Files\Microsoft Shared\VS7Debug\msdbg2.dll

.NET - Calling Web API functions directly

To get around the default .NET Web API GET calls (http://localhost:10305/api/ISS/?strUser=myusername&strPass=mypassword) where you only specify parameters and not the function name, add this code snippet to  your Global.asax.vb file: 

Public Shared Sub RegisterRoutes(routes As RouteCollection)
routes.MapHttpRoute(name:="DefaultApi", routeTemplate:="api/{controller}/{action}", defaults:=New With {Key .action = "get"})
routes.MapHttpRoute(name:="DefaultApi", routeTemplate:="api/{controller}/{action}", defaults:=New With {Key .action = "post"})
End Sub

Then you can make a call that looks like this: http://localhost:10305/api/ISS/LoginFunction?strUser=myusername&strPass=mypassword This is just an example, don't ever send a username and password like this!

Update Wordpress base URLs in MySQL

UPDATE wp_options SET option_value = replace(option_value, 'http://oldurl.com', 'http://newurl.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://oldurl.com','http://newurl.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://oldurl.com', 'http://newurl.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://oldurl.com','http://newurl.com');

Using Google Docs Forms to validate email addreses, capture them and redirect to your site

I wanted to allow the user to hit index.html and if it was the first time visiting the site, they'd have to type in their email address (which I was validating with Javascript), then redirecting to an agreement page, otherwise if they had been there before based on a cookie I had created redirect them immediately to inner_index.html. The Problem: Google Docs don't want you to redirect after the form is submitted, Google docs don't play very nicely with IE when you try to implement work arounds.

The Solution:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><link rel="shortcut icon" href="//ssl.gstatic.com/docs/spreadsheets/forms/favicon_jfk.png" type="image/x-icon">
<title>Title</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="style.css" type="text/css" media="all" />
</head>
<body onload="checkCookie()" dir="ltr" itemscope itemtype="http://schema.org/CreativeWork/FormObject"><meta itemprop="name" content="Email Capture Form">
<meta itemprop="thumbnailUrl" content="https://docs.google.com/spreadsheet/formthumb?formkey=dElxTGNKYTFoWkxSOVVwb3RiR210Wnc6MQ">
<meta itemprop="embedUrl" content="https://docs.google.com/spreadsheet/embeddedform?formkey=dElxTGNKYTFoWkxSOVVwb3RiR210Wnc6MQ">
<meta itemprop="faviconUrl" content="//ssl.gstatic.com/docs/spreadsheets/forms/favicon_jfk.png">
<div>
<div><script type="text/javascript">var submitted_jljnpsrw=false;function
checkRequiredFields_jljnpsrw(requiredFields)
{
var errorMessage='Required field left blank.';
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.getElementById('entry_0').value;
if (reg.test(address) == false)
{
alert("Not a valid e-mail address");
return false;
}
for(var x in requiredFields)
{
var fieldNum=requiredFields[x];
if(document.getElementById('entry_'+fieldNum))
{
if(!document.getElementById('entry_'+fieldNum).value.length)
{
alert(errorMessage);
document.getElementById('entry_'+fieldNum).focus();
return false;
}
}
else if(document.getElementById('group_'+fieldNum+'_1'))
{
var counter=1;
var selected=false;
while(document.getElementById('group_'+fieldNum+'_'+counter))
{
if(document.getElementById('group_'+fieldNum+'_'+counter).checked)
{
selected=true;
}
counter++;
}
if(document.getElementById('other_option:'+fieldNum))
{
if(document.getElementById('other_option:'+fieldNum).checked)
{
selected=true;
if(!document.getElementsByName('entry.'+fieldNum+'.group.other_option_').item(0).value.length)
{
alert(errorMessage);
document.getElementsByName('entry.'+fieldNum+'.group.other_option_').item(0).focus();
return false;
}
}
}
if(!selected)
{
alert(errorMessage);
document.getElementById('group_'+fieldNum+'_1').focus();
return false;
}
}
}
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*365);
document.cookie = "33poemsEmail=BeenHere;expires="+expire.toGMTString();
return true;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function checkCookie()
{
var email=getCookie("33poemsEmail");
if (email!=null && email!="")
{
window.location = "inner_index.html";
}
}
</script>
<p>Title</p>
<p>Sub-Title</p>
<div id="description">
<div>
<p><span>T</span>his is where you put the description</p>
<iframe name="hidden_iframe_jljnpsrw" id="hidden_iframe_jljnpsrw" style="display:none;" onload="if(submitted_jljnpsrw){window.location='foc.html';}"></iframe><form action="https://docs.google.com/spreadsheet/formResponse?formkey=dElxTGNKYTFoWkxSOVVwb3RiR210Wnc6MQ&amp;ifq" method="post" target="hidden_iframe_jljnpsrw" onsubmit="if(checkRequiredFields_jljnpsrw([0])){submitted_jljnpsrw=true;}else{return false;}" id="ss-form">
<br>
<div>
<div><div>
<label for="entry_0"></label>
<div>Please enter your email address to enter the site<br></div>
<div><input type="text" name="entry.0.single" value="" id="entry_0"><input type="submit" name="submit" value="Submit"></div>
</div></div></div>
<br>
<input type="hidden" name="pageNumber" value="0">
<input type="hidden" name="backupCache" value="">
<div><div>
</div></div></form>
<script type="text/javascript">
(function() {
var divs = document.getElementById('ss-form').
getElementsByTagName('div');
var numDivs = divs.length;
for (var j = 0; j < numDivs; j++) {
if (divs[j].className == 'errorbox-bad') {
divs[j].lastChild.firstChild.lastChild.focus();
return;
}
}
for (var i = 0; i < numDivs; i++) {
var div = divs[i];
if (div.className == 'ss-form-entry' &&
div.firstChild &&
div.firstChild.className == 'ss-q-title') {
div.lastChild.focus();
return;
}
}
})();
</script></div>
</div></body></html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><link rel="shortcut icon" href="//ssl.gstatic.com/docs/spreadsheets/forms/favicon_jfk.png" type="image/x-icon"><title>Title</title>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <meta name="description" content="">    <meta name="keywords" content="">    <link rel="shortcut icon" href="images/favicon.ico" />    <link rel="stylesheet" href="style.css" type="text/css" media="all" /></head><body onload="checkCookie()" dir="ltr" itemscope itemtype="http://schema.org/CreativeWork/FormObject"><meta itemprop="name" content="Email Capture Form"> <meta itemprop="thumbnailUrl" content="https://docs.google.com/spreadsheet/formthumb?formkey=dElxTGNKYTFoWkxSOVVwb3RiR210Wnc6MQ"> <meta itemprop="embedUrl" content="https://docs.google.com/spreadsheet/embeddedform?formkey=dElxTGNKYTFoWkxSOVVwb3RiR210Wnc6MQ"><meta itemprop="faviconUrl" content="//ssl.gstatic.com/docs/spreadsheets/forms/favicon_jfk.png"> <div><div><script type="text/javascript">var submitted_jljnpsrw=false;function checkRequiredFields_jljnpsrw(requiredFields){ var errorMessage='Required field left blank.'; var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var address = document.getElementById('entry_0').value; if (reg.test(address) == false)  {  alert("Not a valid e-mail address"); return false;  } for(var x in requiredFields) { var fieldNum=requiredFields[x]; if(document.getElementById('entry_'+fieldNum)) { if(!document.getElementById('entry_'+fieldNum).value.length) { alert(errorMessage); document.getElementById('entry_'+fieldNum).focus(); return false; } } else if(document.getElementById('group_'+fieldNum+'_1')) { var counter=1; var selected=false; while(document.getElementById('group_'+fieldNum+'_'+counter)) { if(document.getElementById('group_'+fieldNum+'_'+counter).checked) { selected=true; } counter++; } if(document.getElementById('other_option:'+fieldNum)) { if(document.getElementById('other_option:'+fieldNum).checked) { selected=true; if(!document.getElementsByName('entry.'+fieldNum+'.group.other_option_').item(0).value.length) { alert(errorMessage); document.getElementsByName('entry.'+fieldNum+'.group.other_option_').item(0).focus(); return false; } } } if(!selected) { alert(errorMessage); document.getElementById('group_'+fieldNum+'_1').focus(); return false; } } } var today = new Date();  var expire = new Date();  expire.setTime(today.getTime() + 3600000*24*365);  document.cookie = "33poemsEmail=BeenHere;expires="+expire.toGMTString(); return true;} function getCookie(c_name){var i,x,y,ARRcookies=document.cookie.split(";");for (i=0;i<ARRcookies.length;i++)  {  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);  x=x.replace(/^\s+|\s+$/g,"");  if (x==c_name)    {    return unescape(y);    }  }} function checkCookie(){ var email=getCookie("33poemsEmail");if (email!=null && email!="")  {  window.location = "inner_index.html";  }}</script>      <p>Title</p>      <p>Sub-Title</p>      <div id="description">        <div>          <p><span>T</span>his is where you put the description</p> <iframe name="hidden_iframe_jljnpsrw" id="hidden_iframe_jljnpsrw" style="display:none;" onload="if(submitted_jljnpsrw){window.location='foc.html';}"></iframe><form action="https://docs.google.com/spreadsheet/formResponse?formkey=dElxTGNKYTFoWkxSOVVwb3RiR210Wnc6MQ&amp;ifq" method="post" target="hidden_iframe_jljnpsrw" onsubmit="if(checkRequiredFields_jljnpsrw([0])){submitted_jljnpsrw=true;}else{return false;}" id="ss-form"> <br><div><div><div><label for="entry_0"></label> <div>Please enter your email address to enter the site<br></div> <div><input type="text" name="entry.0.single" value="" id="entry_0"><input type="submit" name="submit" value="Submit"></div> </div></div></div><br><input type="hidden" name="pageNumber" value="0"><input type="hidden" name="backupCache" value=""> <div><div></div></div></form><script type="text/javascript">            (function() {var divs = document.getElementById('ss-form').getElementsByTagName('div');var numDivs = divs.length;for (var j = 0; j < numDivs; j++) {if (divs[j].className == 'errorbox-bad') {divs[j].lastChild.firstChild.lastChild.focus();return;}}for (var i = 0; i < numDivs; i++) {var div = divs[i];if (div.className == 'ss-form-entry' &&div.firstChild &&div.firstChild.className == 'ss-q-title') {div.lastChild.focus();return;}}})();      
</script>
</div>
</div>
</body>
</html>