Wednesday, April 22, 2009

Encrypt and Decrypt an image with Coldfusion

<!---
Test settings / Change these
--->

<cfset inputImagePath = ExpandPath("./logo.gif")>
<!--- should be GIF, JPG, etc... --->
<cfset imageType = listLast(inputImagePath, ".")>
<cfset encryptedImagePath = ExpandPath("./encryptedLogo.gif")>
<cfset decryptedImagePath = ExpandPath("./decryptedLogo.gif")>


<!--- note, "salt" should be varied for better security --->
<cfset salt = BinaryDecode("28e9ac7b748194b0", "hex")>
<cfset iterations = 20>
<cfset password = "my password">

<!---
ENCRYPT
--->


<
<!--- read in the unencrypted image --->
<cfset unencryptedImage = ImageGetBufferedImage( ImageRead( inputImagePath ) )>


<!--- get SecretKeyFactory for key generation --->
<cfset passwordAlgorithm = "PBEWithMD5AndDES">
<cfset keyFactory = createObject("java", "javax.crypto.SecretKeyFactory").getInstance(passwordAlgorithm)>


<!--- use SecretKeyFactory to create secret key using given password --->
<cfset keySpec = createObject("java", "javax.crypto.spec.PBEKeySpec").init( password.toCharArray() )>
<cfset secretKey = keyFactory.generateSecret( keySpec )>
<!--- set up other parameters for password-based encryption ---->
<cfset keyParams = createObject("java", "javax.crypto.spec.PBEParameterSpec").init(salt, iterations)>


<!--- Create cipher and initialize it to ENCRYPT using the given password --->
<cfset encyrptAlgorithm = "PBEWithMD5AndDES" >
<cfset cipher = createObject("java", "javax.crypto.Cipher").getInstance(encyrptAlgorithm)>
<cfset cipher.init(Cipher.ENCRYPT_MODE, secretKey, keyParams)>


<!--- Create a regular output stream to store the encrypted image on disk --->
<cfset outStream = createObject("java", "java.io.FileOutputStream").init( encryptedImagePath )>
<!--- Create a cipher output stream to encrypt the output --->
<cfset cipherOutStream = createObject("java", "javax.crypto.CipherOutputStream").init( outStream, cipher )>
<!--- Write the encrypted image to disk --->
<cfset ImageIO = createObject("java", "javax.imageio.ImageIO")>
<cfset ImageIO.write( unencryptedImage, imageType, cipherOutStream )>


<!--- Finish. Close both streams --->
<cfset cipherOutStream.close()>
<cfset outStream.close()>

<!---
DECRYPT (must use same settings used to ENCRYPT)
--->


<!--- use SecretKeyFactory to get secret key --->
<cfset passwordAlgorithm = "PBEWithMD5AndDES">
<cfset keyFactory = createObject("java", "javax.crypto.SecretKeyFactory").getInstance(passwordAlgorithm)>
<cfset keySpec = createObject("java", "javax.crypto.spec.PBEKeySpec").init( password.toCharArray() )>
<cfset secretKey = keyFactory.generateSecret( keySpec )>


<!--- set up other parameters for password-based encryption ---->
<!--- "salt" should be varied for better security --->
<cfset PBEParameterSpec = createObject("java", "javax.crypto.spec.PBEParameterSpec")>
<cfset keyParams = createObject("java", "javax.crypto.spec.PBEParameterSpec").init(salt, iterations)>


<!--- Initialize cipher for DECRYPT operation --->
<cfset encyrptAlgorithm = "PBEWithMD5AndDES" >
<cfset cipher = createObject("java", "javax.crypto.Cipher").getInstance(encyrptAlgorithm)>
<cfset cipher.init( cipher.DECRYPT_MODE, secretKey, keyParams)>


<!--- read the encrypted image from disk into a cipher stream for decrypting --->
<cfset inStream = createObject("java", "java.io.FileInputStream").init( encryptedImagePath )>
<cfset CipherInputStream = createObject("java", "javax.crypto.CipherInputStream")>
<cfset cipherInStream = CipherInputStream.init(inStream, cipher)>


<!--- extract the decrypted image --->
<cfset ImageIO = createObject("java", "javax.imageio.ImageIO")>
<cfset imageBuffered = ImageIO.read( cipherInStream )>
<cfset cipherInStream.close()>


<!--- Convert the decrypted image to a CF compatible image --->
<cfset CFCompatibleImage = ImageNew(imageBuffered)>


<!--- **AND/OR** save the unecrypted image back to disk --->
<cfset outputStream = createObject("java", "java.io.FileOutputStream").init( decryptedImagePath )>
<cfset ImageIO.write(imageBuffered, imageType, outputStream)>
<cfset outputStream.close()>


<b>Original Image</b><br>
<cfimage action="writeToBrowser" source="#inputImagePath#">  <br><b>Encrypted Image</b><br>  <cftry>  <cfimage action="writeToBrowser" source="#encryptedImagePath#">  You should NOT see an image above  <cfcatch>  Success! Cannot render encrypted images  </cfcatch>  </cftry>  <br><b>Decrypted Image:</b><br>  <cfimage action="writeToBrowser" source="#decryptedImagePath#">  

Coldfusion server side email validation

<cfoutput>
<cfset errors = "">
<cfif isDefined("Form.FIELDNAMES") >
<!--- validate formfields --->
<!--- First validate if form.lemail is empty --->
<cfif NOT Len(Trim(Form.lEmail))>
<cfset errors = ListAppend(errors,"Please write your email!","|")>
<cfset lEmailError = 1>
<cfelseif NOT IsValid("email", Form.lEmail)>
<cfset errors = ListAppend(errors,"Please write correct email format!","|")>
<cfset lEmailError = 1>
</cfif>
<!--- the rest of the logincode --->
.......
<!--- output errors --->
<CFIF errors NEQ "">
<CFLOOP list="#errors#" index="the_error" delimiters="|">
<li>#the_error#</li>
</CFLOOP>
<br/>
</CFIF>
</CFIF>


<form method="post" action="#CGI.SCRIPT_NAME#" name="loginform">
Email: <input type = "text" name="lemail" value="" class="textfieldLogin" /><br/>
Password: <input name="luserpassword" type="password" class="textfieldLogin" value=""/><br/>
<input type="submit" name="Logon" value="Logon" />
</form>
</cfoutput>

How to output XML file to HTML In Coldfusion

<!--- Answers to be stored in an array --->
<cfset hotspots=ArrayNew(1)>
<cfif(isXML(xml_string))>
<!--- XML string is a Valid XML --->
<!--- Parse XML into a Struct --->
<cfset xml_struct=XMLParse(xml_string)>
<!--- use cfdump to understand the xml_struct and modify the loop below to suit --->
<cfloop from="1" to="#ArrayLen(XMLRoot.Hotspot)#" index="i">
<cfset hotspot=StructNew()>
<cfloop list="Name,X,Y" index="attrib">
<cfif IStructKeyExists(XMLRoot.Hotspot[i].XMLAttributes,attrib)>
<cfset StructInsert(hotspot,attrib,XMLRoot.Hotspot[i].XMLAttributes[attrib],true)>
<cfelse>
<cfset StructInsert(hotspot,attrib,iif(attrib eq "Name",'""','"0"'),true)>
</cfif>
</cfloop>
<cfset ArrayAppend(hotspots,hotspot)>
</cfloop>
<cfelse>
<!--- find the 1st case of <hotspot[^>]*> --->
<cfset hotspot_find=ReFindNoCase(xml_string,"<hotspot[^>]*>",1,true)>
<!--- Loop while hotspot_find is successful --->
<cfloop condition="#hotspot_find.len[1]#">
<!--- create a structure to hold the answers --->
<cfset hotspot=StructNew()>
<--- extract the individual <hotspot> element --->
<cfset hotspot_data=mid(xml_string,hotspot_find.pos[1],hotspot_find.len[1])>
<!--- loop for the required attributes --->
<cfloop list="name,x,y" index="attrib">
<!--- search for the attributes --->
<cfset attrib_find=ReFindNoCase(hotspot_data,'#Attrib#="[^"]*"',1,true)>
<cfif ArrayLen(attrib_find.len) eq 2 and attrib_find.len[1]>
<!--- Attribute exists and has value --->
<cfset structInsert(hotspot,attrib,mid(hotspot_data,attrib_find.pos[1],attrib_find.len[1]),true)>
<cfelse>
<!--- Attribute doesn't exist or has no value --->
<cfset structInsert(hotspot,attrib,iif(attrib eq "name",'""','"0"'),true>
</cfif>
</cfloop>
<!--- Append the struct hotspot to the array hotspots --->
<cfset ArrayAppend(hotspots,hotspot)>
<!--- Locate the next <hotspot> element --->
<cfset hotspot_find=ReFindNoCase(xml_string,"<hotspot[^>]*>",hotspot_find.pos[1]+hotspot_find.len[1],true)>
</cfloop>
</cfif>
<cfdump var="#hotspots#">

Tuesday, April 7, 2009

JQuery tips and tricks

Who doesn’t like JQuery? This fast and easy to use Javascript framework became very popular in 2008. In the following article, I have compiled a list of 8 absolutely useful JQuery hacks, tips and tricks.
Target blank links

Do you use the target=blank attribute on links? If yes, you might know that XHTML 1.0 Strict don't allow it. A good solution to this problem should be using JQuery to make links opening in new windows:

$('a[@rel$='external']').click(function(){
this.target = "_blank";
});

/*
Usage:
<a href="http://www.lepinskidesign.com.br/" rel="external">lepinskidesign.com.br</a>
*/

Get the total number of matched elements

That what I call a very simple, but very useful tip: This will return the number of matched elements:

$('element').size();

Preloading images

When you're using images in Javascript, a good thing is to preload it before you have to use it. This code will do the job:

jQuery.preloadImages = function()
{
for(var i = 0; i").attr("src", arguments[i]);
}
};

// Usage
$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");

Detect browser

Although it is better to use CSS conditionnal comments to detect a specific browser and apply some css style, it is a very easy thing to do with JQuery, which can be useful at times.

//A. Target Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );

//B. Target anything above IE6
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//C. Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//D. Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );

Remove a word in a text

Do you ever wanted to be able to remove words in a text? Note that the following code can be easily modified to replace a word by another.

var el = $('#id');
el.html(el.html().replace(/word/ig, ""));

Columns of equal height

This seems to be a highly-requested hack: How to use two CSS columns, and make them having exactly the same height? Happilly Rob from cssnewbie have the solution.

function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}

/*
Usage:
$(document).ready(function() {
equalHeight($(".recent-article"));
equalHeight($(".footer-col"));
});
*/

Source: Equal Height Columns with jQuery
Font resizing

Font Resizing is a very common feature in many modern websites. Here's how to do it with JQuery.

$(document).ready(function(){
// Reset Font Size
var originalFontSize = $('html').css('font-size');
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
// Increase Font Size
$(".increaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*1.2;
$('html').css('font-size', newFontSize);
return false;
});
// Decrease Font Size
$(".decreaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*0.8;
$('html').css('font-size', newFontSize);
return false;
});
});

Source: Text Resizing With jQuery
Disable right-click contextual menu

There's many Javascript snippets available to disable right-click contextual menu, but JQuery makes things a lot easier:

$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});

html and javascript codes to crash IE6

Let's start with the longest of all:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>CRASH-IE</title>
<style type="text/css">
html, body {
overflow: hidden;
scrollbar-base-color: #330066;
}

.crash {
position:absolute;
left:200px;
top:200px;
width:200px;
}
</style>

<script type="text/javascript">
function galgenfrist() {
window.setTimeout('crashIE();',1000);
}

function crashIE() {
var moveNode = document.getElementById("move");
if(moveNode) {
moveNode.style.top = "100px";
moveNode.style.left = "200px";
}
}
</script>
</head>

<body onload="galgenfrist();">

<h1>CRASH-IE</h1>
<div id="move" class="crash">
<table>
<tbody>
<tr>
<td>
<textarea></textarea>
</td>
</tr>
</tbody>
</table>
</div>

</body>

</html>

Javascript and IE6, a true love story...

<script>for (x in document.write) { document.write(x);}</script>

This one was discover last year:

<style>*{position:relative}</style><table><input></table>

Anti-IE Javascript strikes back!

<body onLoad=”window()”>

Now my favorite: 11 symbols and...bang :D

<STYLE>@;/*

This one is the only one I know which make IE7 crash:

function getX( oElement ) {
var iReturnValue = 0;
while( oElement != null ) {
iReturnValue += oElement.offsetLeft;
oElement = oElement.offsetParent;
}
return iReturnValue;
}

Thursday, April 2, 2009

CFML Certification preparation Resources

The tools mentioned here are still only oriented toward CF 7, so if you're looking for CF8-specific information, the best bet is the

http://livedocs.adobe.com/coldfusion/8/htmldocs/

http://www.adobe.com/support/certification/index.html

http://www.adobe.com/support/training/certified_professional_program/cfmx7_developer.html

http://www.amazon.com/Macromedia-ColdFusion-Certified-Developer-Study/dp/0321330110

for further information log on to

http://www.cf411.com/#certprep

Sql Injection vulnerabilities in your Application

http://www.codersrevolution.com/index.cfm/2008/7/24/Parameterize-your-queries-without-lifting-a-finge


and download :


http://www.webapper.net/index.cfm/2008/7/22/ColdFusion-SQL-Injection

it will check all the
queries with sql injection weakness and add cfqueryparam for all the queries .....for this u have to keep the downloaded file in to the webroot and run the file...

Here's the highlights of Daryl's script:

* It's a single stand alone .cfm file
* It will (optionally) drill down recursively from its current location and scan all CFML for cfquery tags with missing cfqueryparam tags
* It automatically skips files starting with an underscore, and folders starting with a period
* The tool gives you the option to check a box next to the queries you want to automatically fix, and submit the form. It will then edit each of those files and wrap your parameters in a cfqueryparam tag!
* It backs up the old file for you in case to need to roll back (test.cfm.old)
* In general the only attribute it uses for the cfqueryparam tag is value, but it will add cfsqltype="CF_SQL_TIMESTAMP" if the column name contains the word "date", or the parameter contains "now()"


go through this link