Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, June 6, 2010

Encrypting/Decryptng a stirng using C#.

You have a string you want to be able to encrypt and decrypt—perhaps a password or software key—which will be stored in some form accessible by users, such as in a file, the registry, or even a field, that may be open to attack from malicious code.


Solution

Encrypting the string will prevent users from being able to read and decipher the information. The following class, CryptoString, contains two static methods to encrypt and decrypt a string and two static properties to retrieve the generated key and inititialization vector (IV—a random number used as a starting point to encrypt data) after encryption has occurred:
using System;
using System.Security.Cryptography;

public sealed class CryptoString
{
    private CryptoString( ) {}

    private static byte[] savedKey = null;
    private static byte[] savedIV = null;

     public static byte[] Key
    {
        get { return savedKey; }
        set { savedKey = value; }
    }

     public static byte[] IV
    {
        get { return savedIV; }
        set { savedIV = value; }
    }

    private static void RdGenerateSecretKey(RijndaelManaged rdProvider)
    {
        if (savedKey == null)
        {
            rdProvider.KeySize = 256;
            rdProvider.GenerateKey( );
            savedKey = rdProvider.Key;
        }
    }

    private static void RdGenerateSecretInitVector(RijndaelManaged rdProvider)
    {
        if (savedIV == null)
        {
            rdProvider.GenerateIV( );
            savedIV = rdProvider.IV;
        }
    }

    public static string Encrypt(string originalStr)
    {
        // Encode data string to be stored in memory
        byte[] originalStrAsBytes = Encoding.ASCII.GetBytes(originalStr);
        byte[] originalBytes = {};

        // Create MemoryStream to contain output
        MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length);

        RijndaelManaged rijndael = new RijndaelManaged( );

        // Generate and save secret key and init vector
        RdGenerateSecretKey(rijndael);
        RdGenerateSecretInitVector(rijndael);

        if (savedKey == null || savedIV == null)
        {
            throw (new NullReferenceException(
                    "savedKey and savedIV must be non-null."));
        }

        // Create encryptor, and stream objects
        ICryptoTransform rdTransform = rijndael.CreateEncryptor((byte[])savedKey.
                            Clone( ),(byte[])savedIV.Clone( ));
        CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform, 
                            CryptoStreamMode.Write);

        // Write encrypted data to the MemoryStream
        cryptoStream.Write(originalStrAsBytes, 0, originalStrAsBytes.Length);
        cryptoStream.FlushFinalBlock( );
        originalBytes = memStream.ToArray( );

        // Release all resources
        memStream.Close( );
        cryptoStream.Close( );
        rdTransform.Dispose( );
        rijndael.Clear( );

        // Convert encrypted string
        string encryptedStr = Convert.ToBase64String(originalBytes);
        return (encryptedStr);
    }

    public static string Decrypt(string encryptedStr)
    {
        // Unconvert encrypted string
        byte[] encryptedStrAsBytes = Convert.FromBase64String(encryptedStr);
        byte[] initialText = new Byte[encryptedStrAsBytes.Length];

        RijndaelManaged rijndael = new RijndaelManaged( );
        MemoryStream memStream = new MemoryStream(encryptedStrAsBytes);

        if (savedKey == null || savedIV == null)
        {
            throw (new NullReferenceException(
                    "savedKey and savedIV must be non-null."));
        }

        // Create decryptor, and stream objects
        ICryptoTransform rdTransform = rijndael.CreateDecryptor((byte[])savedKey.
                            Clone( ),(byte[])savedIV.Clone( ));
        CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform, 
                            CryptoStreamMode.Read);

        // Read in decrypted string as a byte[]
        cryptoStream.Read(initialText, 0, initialText.Length);

        // Release all resources
        memStream.Close( );
        cryptoStream.Close( );
        rdTransform.Dispose( );
        rijndael.Clear( );

        // Convert byte[] to string
        string decryptedStr = Encoding.ASCII.GetString(initialText);
        return (decryptedStr);
    }
}

Discussion

The CryptoString class follows a singleton design pattern. This class contains only static members, except for the private instance constructor, which prevents anyone from directly creating an object from this class.
This class uses the Rijndael algorithm to encrypt and decrypt a string. This algorithm is found in the System.Security.Cryptography.RijndaelManaged class. This algorithm requires a secret key and an initialization vector; both are byte arrays. A random secret key can be generated for you by calling the GenerateKey method on the RijndaelManaged class. This method accepts no parameters and returns void. The generated key is placed in the Key property of the RijndaelManaged class. The GenerateIV method generates a random initialization vector and places this vector in the IV property of the RijndaelManaged class.
The byte array values in the Key and IV properties must be stored for later use and not modified. This is due to the nature of private-key encryption classes, such as RijndaelManaged. The Key and IV values must be used by both the encryption and decryption routines to successfully encrypt and decrypt data.
The SavedKey and SavedIV private static fields contain the secret key and initialization vector, respectively. The secret key is used by the encryption and decryption methods to encrypt and decrypt data. This key must be used by both the encryption and decryption methods in order to successfully encrypt and then decrypt the data. This is why there are public properties for these values, so they can be stored somewhere secure for later use. This means that any strings encrypted by this object must be decrypted by this object. The initialization vector is used to prevent anyone from attempting to decipher the secret key.
There are two methods in the CryptoString class, RdGenerateSecretKey and RdGenerateSecretInitVector, that are used to generate a secret key and initialization vector, when none exist. The RdGenerateSecretKey method generates the secret key, which is placed in the SavedKey field. Likewise, the RdGenerateSecretInitVector generates the initialization vector, which is placed in the SavedIV field. There is only one key and one IV generated for this class. This enables the encryption and decryption routines to have access to the same key and IV information at all times.
The Encrypt and Decrypt methods of the CryptoString class do the actual work of encrypting and decrypting a string, respectively. The Encrypt method accepts a string that you want to encrypt and returns an encrypted string. The following code calls this method and passes in a string to be encrypted:
string encryptedString = CryptoString.Encrypt("MyPassword");
Console.WriteLine("encryptedString: " + encryptedString);
// get the key and IV used so you can decrypt it later
byte [] key = CryptoString.Key;
byte [] IV = CryptoString.IV;
Once the string is encrypted, the key and IV are stored for later decryption. This method displays:
encryptedString: Ah4vkmVKpwMYRT97Q8cVgQ==
The following code sets the key and IV used to encrypt the string, then calls the Decrypt method to decrypt the previously encrypted string:
CryptoString.Key = key;
CryptoString.IV = IV;
string decryptedString = CryptoString.Decrypt(encryptedString);
Console.WriteLine("decryptedString: " + decryptedString);
This method displays:
decryptedString: MyPassword
There does not seem to be any problems with using escape sequences such as \r, \n, \r\n, or \t in the string to be encrypted. In addition, using a quoted string literal, with or without escaped characters, works without a problem:
@"MyPassword"

Friday, March 12, 2010

How to install Java 6 on ubuntu 9.10

To install proprietary Java, you must have the Multiverse repository enabled. Click on System > Administration > Software Source > Select Multisource > Close







Open a shell prompt (terminal) and type the following to install JDK and JRE:
$ sudo apt-get install sun-java6-bin sun-java6-jre sun-java6-jdk

Setup the default Java version

Ubuntu Linux comes with update-java-alternatives utility to updates all alternatives belonging to one runtime or development kit for the Java language. To select, Sun's JVM as provided in Ubuntu 9.10

$ sudo update-java-alternatives -s java-6-sun

You also need to edit a file called /etc/jvm. This file defines the default system JVM search order. Each JVM should list their JAVA_HOME compatible directory in this file. The default system JVM is the first one available from top to bottom. Open /etc/jvm


$ sudo vi /etc/jvm

Make sure /usr/lib/jvm/java-6-sun is added to the top of JVM list

/usr/lib/jvm/java-6-sun

At the end your file should read as follows:
/usr/lib/jvm/java-6-sun
/usr/lib/jvm/java-gcj
/usr/lib/jvm/ia32-java-1.5.0-sun
/usr/lib/jvm/java-1.5.0-sun
/usr

Save and close the file.

Setup the environment variable

You also need to setup JAVA_HOME and PATH variable. Open your $HOME/.bash_profile or /etc/profile (system wide) configuration. Open your .bash_profile file:

$ vi $HOME/.bash_profile

Append following line:

export JAVA_HOME=/usr/lib/jvm/java-6-sun
export PATH=$PATH:$JAVA_HOME/bin

Save and close the file.

Test your new JDK

Type the following command to display version:

$ java -version

Output:

java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Server VM (build 1.6.0_03-b05, mixed mode) 

Try HelloWorld.java - first java program

$ vi HelloWorld.java
Append code:
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Save and close the file. Compile HelloWorld.java and execute program by typing following two instructions:
$ javac HelloWorld.java
$ java HelloWorld

Output:
Hello, World!

Tuesday, March 9, 2010

Visual basic like programming tool in Linux

 Linux the said to be the best operating system for programmers just not because of its open source nature but also great tools supported by it.
As in windows visual basic is still one of the finest and easy technology to create applications in Linux too GAMBAS2 is one of the great tool offered by Linux developers it can be easily found in Linux Software package It is famous for its easy to write code nature and well supported by MySql Database server.It provides lot of flexibility like visual basic and its easy to learn.
You can create CGI web applications and network programming is also supported by this tool.

Sunday, March 7, 2010

How to save binary large objects in database using asp.net

Introduction:

You can define a BLOB as a large photo, document, audio etc. saved in binary formats that you want to save in a database.
Saving and retrieving BLOBs in a database is more complex than querying string or numeric data.

The BLOB may be very large and if you try to move it in one piece will consume a lot of system memory and that for sure will affect your application performance.

To reduce the amount of system memory you have to break up the BLOB into smaller pieces.

There are a lot of classes that are designed for moving large amount of binary data like BinaryRader, BinaryWriter which exists in System.IO namespace. In the next paragraphs you will see how to use all of this.

Saving a BLOB value to the database:
To save a BLOB value to database we use FileStream and BinaryReader classes.

The next example will show you the process of saving a BLOB to a database.

string
filePath = @"D:\\My Movie.wmv";
 
//A stream of bytes that represnts the binary file
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
 
//The reader reads the binary data from the file stream
BinaryReader reader = new BinaryReader(fs);
 
//Bytes from the binary reader stored in BlobValue array
byte[] BlobValue = reader.ReadBytes((int)fs.Length);
 
fs.Close();
reader.Close();
 
SqlConnection BlobsDatabaseConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");SqlCommand SaveBlobeCommand = new SqlCommand();
SaveBlobeCommand.Connection = BlobsDatabaseConn;
SaveBlobeCommand.CommandType = CommandType.Text;
SaveBlobeCommand.CommandText = "INSERT INTO BlobsTable(BlobFileName, BlobFile)" + "VALUES (@BlobFileName, @BlobFile)";

SqlParameter BlobFileNameParam = new SqlParameter("@BlobFileName", SqlDbType.NChar);
SqlParameter BlobFileParam = new SqlParameter("@BlobFile", SqlDbType.Binary);
SaveBlobeCommand.Parameters.Add(BlobFileNameParam);
SaveBlobeCommand.Parameters.Add(BlobFileParam);
BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("\\") + 1);
BlobFileParam.Value = BlobValue;
try
{
    SaveBlobeCommand.Connection.Open();
    SaveBlobeCommand.ExecuteNonQuery();
    MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.","BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

catch(Exception ex)
{
    MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

finally
{
    SaveBlobeCommand.Connection.Close(); }
Retrieving a BLOB from the database:
To retrieve a BLOB value from database we use FileStream and BinaryWriter classes.

The next example will show you the process of retrieving a BLOB to a database.

NOTE: you will see that we set the CommandBehavior to SquentialAccess when we call ExecuteReader() method, this allow us to use the GetBytes() method of the SqlDataRader, so we can read the BLOB from database in smaller, user-definable amounts.

string
SavePath = @"D:\\My BLOBs";
SqlConnection SaveConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");
SqlCommand SaveCommand = new SqlCommand();
SaveCommand.CommandText = "Select BlobFileName, BlobFile from BlobsTable where BlobFileName = @BlobFileName";
SaveCommand.Connection = SaveConn;
SaveCommand.Parameters.Add("@BlobFileName", SqlDbType.NVarChar).Value = "My Movie.wmv";

//the index number to write bytes to
long CurrentIndex = 0;

//the number of bytes to store in the array
int BufferSize = 100;

//The Number of bytes returned from GetBytes() method
long BytesReturned;

//A byte array to hold the buffer
byte[] Blob = new byte[BufferSize];

SaveCommand.Connection.Open();

//We set the CommandBehavior to SequentialAccess
//so we can use the SqlDataReader.GerBytes() method.

SqlDataReader
reader = SaveCommand.ExecuteReader(CommandBehavior.SequentialAccess);

while
(reader.Read())
{
    FileStream fs = new FileStream(SavePath + "\\" + reader["BlobFileName"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);

    BinaryWriter writer = new BinaryWriter(fs);

    //reset the index to the beginning of the file
    CurrentIndex = 0;

    BytesReturned = reader.GetBytes(1, //the BlobsTable column indexCurrentIndex, // the current index of the field from which to begin the read operationBlob, // Array name to write tha buffer to0, // the start index of the array to start the write operationBufferSize // the maximum length to copy into the buffer); 
    while (BytesReturned == BufferSize)
    {
        writer.Write(Blob);
        writer.Flush();        CurrentIndex += BufferSize;
        BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);
    } 
    writer.Write(Blob, 0, (int)BytesReturned);
    writer.Flush(); writer.Close(); 
    fs.Close();
} 
reader.Close(); SaveCommand.Connection.Close();
To fully understand the concept you need to try to write this code yourself.

Saturday, March 6, 2010

Go: Google’s new open source programming language

The Go language, in development since September 2007, has been unveiled by Google along with the release of a free and open source compiler. In fact, Google has released both a stand-along compiler implementation with cryptic names such as 6g (amd64 compiler), 8g (x86 compiler), and 5g (ARM compiler) and one which is a front-end for GCC (gccgo).


Born out of frustration with existing system languages, Go attempts to bring something new to the table, and mix the ease of dynamically typed and interpreted languages with the efficiency of compiled languages.



So why make a new programming language?



Google believes that the current languages have run their course. The prominent languages in use today (C/C++, Java, C#) are all based around a similar syntax, and updating and adding new features in these language consists of piling on libraries, with little or no upgrade to the core of the language itself. What Google intends to do requires more than just the addition of a new library.

Hello World in Go

package main

import "fmt"

func main() {
  fmt.Printf("Hello, ??n")
}


The landscape of computing has changed a lot since C, and as Google notes “Computers are enormously quicker but software development is not faster.” Languages have had to morph quite a bit to take on support concepts such as parallel processing, and garbage collection.


Go, on the other hand has been designed by Google from the ground up as “a concurrent, garbage-collected language with fast compilation”.


In order to not alienate the majority of developers though, its syntax is quite similar to C, and would not take much time for a developer to catch on to.


Go has accomplished some impressive feats. The language is designed to compile fast and Go can compile a “large" program in a few seconds on a single computer. It is designed to simplify the creation of application which can better utilize today’s multi-core processors. The language supports concurrent execution and communication between concurrent processes natively, and is fully-garbage collected.


Goroutines allowed are Google’s answer to threading in Go, and any function call which is preceded by the go statement runs in a different goroutine concurrently. A feature called channels allows for easy communication and synchronization between such routines.


Unlike other object oriented languages, Go has a much “simplified” type structure, which disallows sub-classing! Go offers a different flavour of object oriented programming using interfaces, which Google believes will simplify use.


By using interfaces, explicit type hierarchies need not be defined, instead, a type will satisfy all interfaces which are subsets of its methods. The relationships between types and interfaces need not be defined explicity! This can have some interesting implications as people can add interfaces to connect unrelated types even later in the development of an application.


Go seems inspired by Python as well. Python has been one of Google’s favoured languages and was the sole language supported on Google’s AppEngine when it launched. Like Python, Go supports “slices”, which allow you to refer to parts of arrays using a simple syntax. Thus for an array “a” with 100 elements, a[23,42] will result in an array with elements 23 through 42 of a. Go also tracks the length of arrays internally, further simplifying array usage. Additionally, Maps in Go allow you to create “arrays” with custom index types, and are a native feature of the language.


One consistent point in the features of Go is that it is better to have one excellent implementation of commonly used features such as garbage collection, strings, maps etc. rather than have them rethought and re-implemented in each program.


As nearly all Google products, Go is “beta” and not yet suitable for production use. By releasing it early Google hopes to garner a community around it and hopes that enough people will be interested in it to justify continued development.


Get out there and grab Go now! Like any Google product it has the capacity to become standard for the next generation.