C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

How to encrypt and decrypt a string - a simple encryption/decryption


Posted Date: 10 Jul 2004    Resource Type: Articles    Category: .NET Framework
Author: Sweet CousinMember Level: Bronze    
Rating: 1 out of 5Points: 10



This programme takes a string as input and generates a new string for you.

I have pasted the complete class here. All you need to do is to create a class file and paste the code there and add reference. Create an object of this class and using Encrypt(string strValue), pass your string and you will get a new string in return. If this new string is again passed to the Encrypt(string strValue) you will get the string you passed earlier. It can be used for some minor encryption.


public class EncryptString
{

public string Encrypt(string strValue)
{
return genNewString(strValue);

}
private string genNewString(string strValue)
{
int i,j,k;
string strNewStringValue="";
char [] chrValue = strValue.ToCharArray();

for ( i=0; i<=chrValue.Length-1; i++)
{
// take the next character in the string
j = (int)chrValue[i];

// find out the character code
k = (int)j;

if (k >= 97 && k <= 109)
{
// a ... m inclusive become n ... z
k = k + 13;
}
else if( k >= 110 && k <= 122 )
{
// n ... z inclusive become a ... m
k = k - 13;
}
else if (k >= 65 && k <= 77)
{
// A ... m inclusive become n ... z
k = k + 13 ;
}
else if( k >= 78 && k <= 90 )
{
// N ... Z inclusive become A ... M
k = k - 13;
}

//add the current character to the string returned by the function
strNewStringValue = strNewStringValue +(char)k;
}

return strNewStringValue ;
}
}





Responses

Author: TMH    09 Aug 2004Member Level: Bronze   Points : 0
Replacing letters by others is a very weak encryption scheme that can easily be cracked using letter frequency analysis. .Net framework offers ready made class for encryption.

This sample demonstrates how public key encryption can be used to securely exchange messages between 3 entities. The messages are encrypted using a symmetric algorithm (RC2) and then the RC2 key is encrypted using an asymmetric algorithm (RSA).

Example found under .Net SDK v1.1\Samples\Technologies\Security\PublicKeyCryptography



'=====================================================================
' File: PublicKey.vb
'
' Summary: Demonstrates public key cryptography using the .NET
' Framework implementation of RSA.
'
'---------------------------------------------------------------------
' This file is part of the Microsoft .NET Framework SDK Code Samples.
'
' Copyright (C) Microsoft Corporation. All rights reserved.
'
'This source code is intended only as a supplement to Microsoft
'Development Tools and/or on-line documentation. See these other
'materials for detailed information regarding Microsoft code samples.
'
'THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
'KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
'IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
'PARTICULAR PURPOSE.
'=====================================================================

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


Module PublicKey
Sub Main()
' Instantiate 3 People for example. See the Person class below
Dim alice As New Person("Alice")
Dim bob As New Person("Bob")
Dim steve As New Person("Steve")

' Messages that will exchanged. See CipherMessage class below
Dim aliceMessage As CipherMessage
Dim bobMessage As CipherMessage
Dim steveMessage As CipherMessage

' Example of encrypting/decrypting your own message
Console.WriteLine("Encrypting/Decrypting Your Own Message")
Console.WriteLine("-----------------------------------------")

' Alice encrypts a message using her own public key
aliceMessage = alice.EncryptMessage("Alice wrote this message")
' then using her private key can decrypt the message
alice.DecryptMessage(aliceMessage)
' Example of Exchanging Keys and Messages
Console.WriteLine()
Console.WriteLine("Exchanging Keys and Messages")
Console.WriteLine("-----------------------------------------")

' Alice Sends a copy of her public key to Bob and Steve
bob.GetPublicKey(alice)
steve.GetPublicKey(alice)

' Bob and Steve both encrypt messages to send to Alice
bobMessage = bob.EncryptMessage("Hi Alice! - Bob.")
steveMessage = steve.EncryptMessage("How are you? - Steve")

' Alice can decrypt and read both messages
alice.DecryptMessage(bobMessage)
alice.DecryptMessage(steveMessage)

Console.WriteLine()
Console.WriteLine("Private Key required to read the messages")
Console.WriteLine("-----------------------------------------")

' Steve cannot read the message that Bob encrypted
steve.DecryptMessage(bobMessage)
' Not even Bob can use the Message he encrypted for Alice.
' The RSA private key is required to decrypt the RS2 key used
' in the decryption.
bob.DecryptMessage(bobMessage)
End Sub 'Main

Class CipherMessage
Public cipherBytes() As Byte ' RC2 encrypted message text
Public rc2Key() As Byte ' RSA encrypted rc2 key
Public rc2IV() As Byte ' RC2 initialization vector
End Class 'CipherMessage

Class Person
Private rsa As RSACryptoServiceProvider
Private rc2 As RC2CryptoServiceProvider
Private name As String

' Maximum key size for the RC2 algorithm
Private keySize As Integer = 128


' Person constructor
Public Sub New(p_Name As String)
rsa = New RSACryptoServiceProvider()
rc2 = New RC2CryptoServiceProvider()
rc2.KeySize = keySize
name = p_Name
End Sub 'New


' Used to send the rsa public key parameters
Public Function SendPublicKey() As RSAParameters
Dim result As New RSAParameters()
Try
result = rsa.ExportParameters(False)
Catch e As CryptographicException
Console.WriteLine(e.Message)
End Try
Return result
End Function 'SendPublicKey

' Used to import the rsa public key parameters
Public Sub GetPublicKey(receiver As Person)
Try
rsa.ImportParameters(receiver.SendPublicKey())
Catch e As CryptographicException
Console.WriteLine(e.Message)
End Try
End Sub 'GetPublicKey


Public Function EncryptMessage([text] As String) As CipherMessage
' Convert string to a byte array
Dim message As New CipherMessage()
Dim plainBytes As Byte() = Encoding.Unicode.GetBytes([text].ToCharArray())

' A new key and iv are generated for every message
rc2.GenerateKey()
rc2.GenerateIV()

' The rc2 initialization doesnt need to be encrypted, but will
' be used in conjunction with the key to decrypt the message.
message.rc2IV = rc2.IV
Try
' Encrypt the RC2 key using RSA encryption
message.rc2Key = rsa.Encrypt(rc2.Key, False)
Catch e As CryptographicException
' The High Encryption Pack is required to run this sample
' because we are using a 128-bit key. See the readme for
' additional information.
Console.WriteLine(("Encryption Failed. Ensure that the" + " High Encryption Pack is installed."))
Console.WriteLine(("Error Message: " + e.Message))
Environment.Exit(0)
End Try
' Encrypt the Text Message using RC2 (Symmetric algorithm)
Dim sse As ICryptoTransform = rc2.CreateEncryptor()
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, sse, CryptoStreamMode.Write)
Try
cs.Write(plainBytes, 0, plainBytes.Length)
cs.FlushFinalBlock()
message.cipherBytes = ms.ToArray()
Catch e As Exception
Console.WriteLine(e.Message)
Finally
ms.Close()
cs.Close()
End Try
Return message
End Function 'EncryptMessage

Public Sub DecryptMessage(message As CipherMessage)
' Get the RC2 Key and Initialization Vector
rc2.IV = message.rc2IV
Try
' Try decrypting the rc2 key
rc2.Key = rsa.Decrypt(message.rc2Key, False)
Catch e As CryptographicException
Console.WriteLine(("Decryption Failed: " + e.Message))
Return
End Try

Dim ssd As ICryptoTransform = rc2.CreateDecryptor()
' Put the encrypted message in a memorystream
Dim ms As New MemoryStream(message.cipherBytes)
' the CryptoStream will read cipher text from the MemoryStream
Dim cs As New CryptoStream(ms, ssd, CryptoStreamMode.Read)
Dim initialText() As Byte = New [Byte](message.cipherBytes.Length) {}

Try
' Decrypt the message and store in byte array
cs.Read(initialText, 0, initialText.Length)
Catch e As Exception
Console.WriteLine(e.Message)
Finally
ms.Close()
cs.Close()
End Try

' Display the message received
Console.WriteLine((name + " received the following message:"))
Console.WriteLine((" " & Encoding.Unicode.GetString(initialText)))
End Sub 'DecryptMessage
End Class 'Person
End Module 'PublicKey


Author: TMH    10 Aug 2004Member Level: Bronze   Points : 0
I will post your feedback that I received on my personal e-mail so for others to appreciate. You will also find my response at the end of this message:

"From: Deepak Urath
To: hoshantm@hotmail.com
Subject: Re: Feedback : How to encrypt and decrypt a string - a simple encryption/decryption
Date: Mon, 9 Aug 2004 04:51:26 -0700 (PDT)

Hi,
If u had to post your encryption u could have done that yourself.. rather that giving a subject weak encryption.. if u had read the complete article, u would'nt be stupid enough to post such a feedback. it was clearly mentioned in the article that "The method used here is juggling the characters in the string and this code should'nt be considered highly secure encryption."

I suggest u should stop fucking around with things like this and read the articles properly.. or if u really want to post something post it as a seperate article.. exclusively for people like u, i have had edited the article and bolded the area which says that its just a minor encryption.. anyways.. u have posted a cool suff ...

and i also suggest that VB.net articles are to be posted in the VB.net Category and not in C# category. If you could change the subject "Weak encryption" to something better would be really fine.. or i think u should post your stuff as a seperate topic..
regards,"

My response:
1) I do not think it is professional to get personal when discussing technical matters. Did the kind of language you use make your argument stronger or make you look smarter? I will leave it for you to think about that.
2) You have plenty of opportunity to anwer technically on the web site and make your point known to the readers and let them judge for themselves. Otherwise, do not get public if you are not able to take criticism.
3) What's the point of "juggling the characters in the string" when there is a ready made infrastructure to encrypt?

Regards...



Author: Ray Sotkiewicz    10 Apr 2006Member Level: Bronze   Points : 0
Wow.. I would have expected more from everyone on this subject matter...

This is a disgrace.. You both should be ashamed of yourselves.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: .Net Compact Framework Programming
Previous Resource: How to implement multiple interface in VB.NET
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use