General, .Net, services, windows services, MVC

Generating Unique Key in .Net using RNGCryptoServiceProvider

I need to create some unique keys. GUID is one option as they give Globally Unique identifier but they are big. If you want to issue unique number in your application which you want to give as AppKey or any reference number then GUIDs is obviously not a solution.

RNG means Random Number Generator

The .net Framework provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers.

Although we can use this class to generate unique number in some sense. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only.

So, we used this function along with some character masking to generate unique key of any length (here I take 32 character long key).

Below is code sample:

private string RNGCharacterMask()

{

int maxSize = 32;

int minSize = 32;

char[] chars = new char[62];

string a;

a = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890″;

chars = a.ToCharArray();

int size = maxSize;

byte[] data = new byte[1];

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

crypto.GetNonZeroBytes(data);

size = maxSize;

data = new byte[size];

crypto.GetNonZeroBytes(data);

StringBuilder result = new StringBuilder(size);

foreach (byte b in data)

{

result.Append(chars[b % (chars.Length – 1)]);

}

return result.ToString();

}

Happy Coding… :)

.Net, General, MVC, services, windows, windows services

Prevent Cross-Site Request Forgery (CSRF) using ASP.NET anti-forgery token

The anti-forgery token used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the ValidateAntiForgeryTokenAttribute attribute to the action method that you want to protect. It generates a hidden  field (anti-forgery token) that is validated when the form is submitted.

To generate the AntiForgeryToken and the Cookie on the client side, we declare it as follows in the HTML form in the user.cshtml

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<fieldset>
<legend>UserDetails</legend>

This ensures that a form being posted to the server was actually generated by the same server. Thus fake forms that do not have the AntiForgeryToken from the correct server, gets rejected.

To validate an incoming post request, add the [ValidateAntiForgeryToken] filter to your target action method.

[ValidateAntiForgeryToken]
public ViewResult SubmitUpdate()
{
// Your code goes here…
}

Assuming that everything is going well, the request goes through as normal. But if not, there’s an authorization failure with message  “A required anti-forgery token was not supplied or was invalid”.

In case you want to protect multiple forms in your application independently of each other, you can use a “salt” value when you call Html.AntiForgeryToken()…

HTML Code:

<%= Html.AntiForgeryToken(“someString”) %>

Controller Code:

[ValidateAntiForgeryToken(Salt=”someString”)]
public ViewResult SubmitUpdate()
{
// Your code goes here…
}

Salt can be any non empty string.

A different salt value means a different anti-forgery token will be generated.

In conclusion, ASP.NET MVC’s AntiForgeryToken helpers are easy to use, and work very nicely!

Thank you!

Happy Coding :)

asp.net mvc
asp.net mvc
General

The efficient way to generate 4 or 8 characters long random alphanumeric string in SQL

SELECT LEFT(CONVERT(VARCHAR(36),NEWID()),4)+RIGHT(CONVERT(VARCHAR(36),NEWID()),4)

SELECT RIGHT(REPLACE(CONVERT(VARCHAR(36),NEWID()),’-‘,”),8)

DECLARE @chars NCHAR(36)
SET @chars = N’0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ’
DECLARE @result NCHAR(5)
SET @result = SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
SELECT @result

 

In order to ensure uniqueness for each varchar you can store the results in a table and compare with result in that table. You can also make the varchar longer and just hope for the best.

Happy Coding :)

.Net, General

Retrieve First Name and Last Name from string in asp.net

Retrieve First Name and Last Name from string in asp.net

VB.Net:

Dim name As String = “Joseph Van Andrews”

‘ Split string based on spaces
Dim names As String() = name.Split(New Char() {” “c})

‘ Seperate the first name from the rest of the string
Dim lastName as string = name.substring(names(0).length())

Dim nameString as string = “the First Name is: ” + names(0) + ” and the Last Name is: ” + lastName

response.write(nameString)

C#.Net:

string name = “ABC DEF XYZ”;

// Split string based on spaces
string[] names = name.Split(new char[] { ‘ ‘ });

// Seperate the first name from the rest of the string
string lastName = name.Substring(names[0].Length());

string nameString = “the First Name is: ” + names[0] + ” and the Last Name is: ” + lastName;

response.write(nameString);

Happy Coding :)