.NET | Suhail Kaleem - Part 2

.NET

Encrypt in VB.NET and Decrypt in PHP and Vice Versa

22
########################################
# BEGIN PHP CODE
########################################

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

$ky = 'lkirwf897+22#bbtrm8814z5qq=498j5'; // 32 * 8 = 256 bit key
$iv = '741952hheeyy66#cs!9hjv887mxx7@8y'; // 32 * 8 = 256 bit iv

$text = "Here is my data to encrypt!!!";

$from_vb = "QBlgcQ2+v3wd8RLjhtu07ZBd8aQWjPMfTc/73TPzlyA=";   // enter value from vb.net app here to test

$etext = encryptRJ256($ky, $iv, $text);
$dtext = decryptRJ256($ky, $iv, $etext);
$vtext = decryptRJ256($ky, $iv, $from_vb);

echo "orignal string: $text";
echo "encrypted in php: $etext";
echo "decrypted in php: $dtext";
echo "encrypted in vb: $from_vb";
echo "from vb decrypted in php: $vtext";
echo "If you like it say thanks! ";

exit;

function decryptRJ256($key,$iv,$string_to_decrypt)
{

$string_to_decrypt = base64_decode($string_to_decrypt);

$rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);

$rtn = rtrim($rtn, "\4");

return($rtn);

}

function encryptRJ256($key,$iv,$string_to_encrypt)
{

$rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);

$rtn = base64_encode($rtn);

return($rtn);

}

?>

########################################
# END PHP CODE
########################################
########################################
# BEGIN VB.NET CODE (console app)
########################################

Imports System
Imports System.Text
Imports System.Security.Cryptography
Imports System.IO

Module Module1

Sub Main()

'Shared 256 bit Key and IV here
Dim sKy As String = "lkirwf897+22#bbtrm8814z5qq=498j5"  '32 chr shared ascii string (32 * 8 = 256 bit)
Dim sIV As String = "741952hheeyy66#cs!9hjv887mxx7@8y"  '32 chr shared ascii string (32 * 8 = 256 bit)

Dim sTextVal As String = "Here is my data to encrypt!!!"

Dim eText As String
Dim dText As String

eText = EncryptRJ256(sKy, sIV, sTextVal)
dText = DecryptRJ256(sKy, sIV, eText)

Console.WriteLine("key: " &amp; sKy)
Console.WriteLine()
Console.WriteLine(" iv: " &amp; sIV)
Console.WriteLine("txt: " &amp; sTextVal)
Console.WriteLine("encrypted: " &amp; eText)
Console.WriteLine("decrypted: " &amp; dText)
Console.WriteLine("If you like it say thanks! ")
Console.WriteLine("press any key to exit")
Console.ReadKey(True)

End Sub

Public Function DecryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_decrypt As String)

Dim sEncryptedString As String = prm_text_to_decrypt

Dim myRijndael As New RijndaelManaged
myRijndael.Padding = PaddingMode.Zeros
myRijndael.Mode = CipherMode.CBC
myRijndael.KeySize = 256
myRijndael.BlockSize = 256

Dim key() As Byte
Dim IV() As Byte

key = System.Text.Encoding.ASCII.GetBytes(prm_key)
IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)

Dim decryptor As ICryptoTransform = myRijndael.CreateDecryptor(key, IV)

Dim sEncrypted As Byte() = Convert.FromBase64String(sEncryptedString)

Dim fromEncrypt() As Byte = New Byte(sEncrypted.Length) {}

Dim msDecrypt As New MemoryStream(sEncrypted)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)

Return (System.Text.Encoding.ASCII.GetString(fromEncrypt))

End Function

Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String)

Dim sToEncrypt As String = prm_text_to_encrypt

Dim myRijndael As New RijndaelManaged
myRijndael.Padding = PaddingMode.Zeros
myRijndael.Mode = CipherMode.CBC
myRijndael.KeySize = 256
myRijndael.BlockSize = 256

Dim encrypted() As Byte
Dim toEncrypt() As Byte
Dim key() As Byte
Dim IV() As Byte

key = System.Text.Encoding.ASCII.GetBytes(prm_key)
IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)

Dim encryptor As ICryptoTransform = myRijndael.CreateEncryptor(key, IV)

Dim msEncrypt As New MemoryStream()
Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)

toEncrypt = System.Text.Encoding.ASCII.GetBytes(sToEncrypt)

csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
csEncrypt.FlushFinalBlock()

encrypted = msEncrypt.ToArray()

Return (Convert.ToBase64String(encrypted))

End Function

End Module

########################################
# END VB.NET CODE
########################################

Disabling a Trigger Control During Asynchronous PostBack

0

Often, we want to disable the control that triggered an asynchronous postback until the postback has completed. This prohibites the user from triggering another postback until the current one is complete.

The Code

First add a ScriptManager to the page, immediately following the <form> tag.

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />

Then add a Label wrapped in an UpdatePanel. This label will be populated with the date and time on each postback. We’ll also add a Button inside of the UpdatePanel to cause the postback.

<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<ContentTemplate>
<asp:Label ID=”Label1″ runat=”server” Text=”Label” /><br />
<asp:Button ID=”Button1″ runat=”server” Text=”Update Time” OnClick=”Button1_Click” />
</ContentTemplate>
</asp:UpdatePanel>

We’ll also add an UpdateProgress control and associate it with our UpdatePanel just to let the user know that something’s happening.

<asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″>
<ProgressTemplate>
Loading…
</ProgressTemplate>
</asp:UpdateProgress>

Next, we’ll add a events in the code-behind to populate the Label and to introduce some latency, simulating a lengthy update to the page.

VB.NET:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = Now.ToString
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
System.Threading.Thread.Sleep(4000)  ‘Pause for 4 seconds.
End Sub

And finally we’ll add the client-side code to disable our button during the postback. The Javascript disables the button during the beginRequest event of the PageRequestManager and enables it when control has been returned to the browser in the endRequest event. The control causing the postback is returned from the get_postBackElement() method of the BeginRequestEventArgs object which is passed to the function handling the beginRequest event.

Add the follow script after the ScriptManager on the page:

<script type=”text/javascript”>
var pbControl = null;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
pbControl = args.get_postBackElement();  //the control causing the postback
pbControl.disabled = true;
}
function EndRequestHandler(sender, args) {
pbControl.disabled = false;
pbControl = null;
}
</script>

And that’s it!

The Complete Source Code:

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>
<%@ Register Assembly=”System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″
Namespace=”System.Web.UI” TagPrefix=”asp” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
<script type=”text/javascript”>
var pbControl = null;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
pbControl = args.get_postBackElement();  //the control causing the postback
pbControl.disabled = true;
}
function EndRequestHandler(sender, args) {
pbControl.disabled = false;
pbControl = null;
}
</script>
<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<ContentTemplate>
<asp:Label ID=”Label1″ runat=”server” Text=”Label” /><br />
<asp:Button ID=”Button1″ runat=”server” Text=”Update Time” OnClick=”Button1_Click” />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″>
<ProgressTemplate>
Loading…
</ProgressTemplate>
</asp:UpdateProgress>
</form>
</body>
</html>


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <script type="text/javascript">
                var pbControl = null;
                var prm = Sys.WebForms.PageRequestManager.getInstance();
                prm.add_beginRequest(BeginRequestHandler);
                prm.add_endRequest(EndRequestHandler);
                function BeginRequestHandler(sender, args) {
                    pbControl = args.get_postBackElement();  //the control causing the postback
                    pbControl.disabled = true;
                }
                function EndRequestHandler(sender, args) {
                    pbControl.disabled = false;
                    pbControl = null;
                }
            </script>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server" Text="Label" /><br />
                    <asp:Button ID="Button1" runat="server" Text="Update Time" OnClick="Button1_Click" />
                </ContentTemplate>
            </asp:UpdatePanel>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
                <ProgressTemplate>
                    Loading...
                </ProgressTemplate>
            </asp:UpdateProgress>
        </form>
    </body>
</html>

Check String for Unicode Characters ( IsUnicode() )

1

in .Net All Strings are Unicode

we also know that  ASCII Characters range is up-to 255 any thing above 255 will be Unicode so what we will do is we will just check each character value if it is above 255 then there is Unicode Characters

here is function which does that

Public Shared Function IsUnicode(ByVal s As String) As Boolean

Dim items As Char() = s.ToCharArray()
For i As Integer = 0 To items.Length – 1

If CUShort(AscW(items(i))) > 255 Then
Return True
End If

Next

Return False

End Function

use it like

if IsUnicode(“لعربي“) then

‘ is unicode

else

‘not unicode

end if

Go to Top