Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Encrypting data 1

Status
Not open for further replies.

sthmpsn1

MIS
Sep 26, 2001
456
US
I was looking at a website that talked about encrypting passwords and such for database entry. They give the following code

<%@ Import Namespace=&quot;System.Web.Security&quot; %>
<html>
<head>
<script language=&quot;VB&quot; runat=server>
' This function encrypts the input string using the SHA1 and MD5
' encryption algorithms
Sub encryptString(Src As Object, E As EventArgs)
SHA1.Text = CookieAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, &quot;SHA1&quot;)
MD5.Text = CookieAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, &quot;MD5&quot;)
End Sub
</script>
</head>
<body>

Say I take SHA1.text and input it into a database encrypted. How would I decrypted it when pulling it back to the page. I didn't see any data on that.

 
Here is an encryption/decryption class that I have built I found that it work quite nicely.


Public Class Encryptor

' Use DES CryptoService with Private key pair
Private SEncryptionKey As String = &quot;encryptstring&quot;
Private IV() As Byte = {&H25, &H29, &H93, &H27, &H52, &HFD, &HAE, &HBC}
Private key() As Byte = {}

Public Function Decrypt(ByVal stringToDecrypt As String) As String
Dim inputByteArray(stringToDecrypt.Length) As Byte
' Note: The DES CryptoService only accepts certain key byte lengths
' We are going to make things easy by insisting on an 8 byte legal key length

Try
key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
' we have a base 64 encoded string so first must decode to regular unencoded (encrypted) string
inputByteArray = Convert.FromBase64String(stringToDecrypt)
' now decrypt the regular string
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch e As Exception
Return e.Message
End Try
End Function

Public Function Encrypt(ByVal stringToEncrypt As String) As String
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
' convert our input string to a byte array
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
'now encrypt the bytearray
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
' now return the byte array as a &quot;safe for XMLDOM&quot; Base64 String
Return Convert.ToBase64String(ms.ToArray())
Catch e As Exception
Return e.Message
End Try
End Function


Took me a while to get it to properly encrypt and decrypt strings. But it works perfectly now.

HTH That'l do donkey, that'l do
[bravo] Mark
 
how does this grab the value from say a texbox to encypt??
 
It is a class. In you web form do something like so.

dim myEncryptor as new Encryptor
dim EncryptedString as string

EncryptedString = myEncryptor.Encrypt(textbox1.text)

textbox2.text = myEncryptor.Decrypt(EncryptedString)

myEncryptor = nothing


Works very well. You will probably want to change the IV array and SEncryptionKey string. The IV is just any Hex Value.

dim reward as new star
Mark.Collection.Add(reward)
reward = nothing
That'l do donkey, that'l do
[bravo] Mark
 
so when you say &quot;You will probably want to change the IV array and SEncryptionKey string. The IV is just any Hex Value.&quot; Are you saying the encryption turns it into a hex value?? I am very new to this and don't quite understand what you mean?

 
In this class I used the DES encryption algorithm. Any algorithm worth anything doesn't use a static equation. You or I could easily write an equation that turns normal text to something else.
Ex turn the text to assci and add 1.

The DES algorithmm takes two parameters. The main encryption key and a second key. The second key encrypts the first part of the encrypted string farther to prevent any ease of breaking the code.

If you use the Class as it is anyone that visits this forum can break your encryted data. If you notice at the top of the class I included these lines

' Use DES CryptoService with Private key pair
Private SEncryptionKey As String = &quot;encryptstring&quot;
Private IV() As Byte = {&H25, &H29, &H93, &H27, &H52, &HFD, &HAE, &HBC}
Private key() As Byte = {}


The SEncryptionKey is any string you want to be your key. Change it to your hearts content.

THE IV array is an array of bytes. The numbers you see there are in hexidecimal form. I am assuming you know what hexadecimal is. This is the secondary key I was speaking of. Change the array to anything you want as long as it remains a hex number. Note leave the &

quick note about hex. It is a number system that runs from 0-9 and A-F. F being 16 and A 11 so to speak. That'l do donkey, that'l do
[bravo] Mark
 
Now I understand! I get it, I get it.

I will give this a world and see how it goes. Hopefully I won't need your help anymore. :(
 
What namespaces do you need to declare to use this?
 
Apparently you still do :p
This is what I got
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography That'l do donkey, that'l do
[bravo] Mark
 
I know I know, but look at as your teaching me. Your awesome man.
 
[rofl]

Thanks Glad to help. It took me a while to figure out the encryption stuff, but I got it now.

Hope my posts were helpful *wink wink That'l do donkey, that'l do
[bravo] Mark
 
okay I think this is my last question, (really hoping) I got the Encryption working just fine, Now I just want to take the decrypted part and throw it into a dropdown menu. Here is what I have.

Dim dbconn As SqlConnection = New SqlConnection(&quot;server=AM1ST_FS1;database=HRINFO;uid=sa;&quot;)
Dim selectCMD1 As SqlCommand = New SqlCommand()
Dim myEncryptor as new Encryptor
Dim EncryptedString as string
selectCMD1.CommandText = &quot;Select * From testy &quot;
selectCMD1.Connection = dbconn
selectCMD1.CommandTimeout = 30
dbconn.Open()
themonths.DataSource = selectCMD1.ExecuteReader()
themonths.DataTextField = myEncryptor.Decrypt(EncryptedString)
themonths.DataValueField = &quot;Name&quot;
themonths.DataBind()
dbconn.Close()

produces an error when pushing the info to the function saying that
System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 15:
Line 16: Public Function Decrypt(ByVal stringToDecrypt As String) As String
Line 17: Dim inputByteArray(stringToDecrypt.Length) As Byte
Line 18: ' Note: The DES CryptoService only accepts certain key byte lengths
Line 19: ' We are going to make things easy by insisting on an 8 byte legal key length


I know my problem is that I am not pushing anything to the function. How would I rewrite themonths.DataTextField = myEncryptor.Decrypt(EncryptedString) so that it pushes the field &quot;Name&quot; To the function???
 
oh what the heck, i'll do it for ya mark =) Daren J. Lahey
Just another computer guy...
 
Okay so it would help if I had it somewhat like this themonths.DataTextField = myEncryptor.Decrypt(&quot;Name&quot;) that fixes the passing to the function, but now it says

Exception Details: System.Web.HttpException: DataBinder.Eval: 'System.Data.Common.DbDataRecord' does not contain a property with the name Bad Data. .

Source Error:


Line 89: themonths.DataTextField = myEncryptor.Decrypt(&quot;Name&quot;)
Line 90: themonths.DataValueField = &quot;Name&quot;
Line 91: themonths.DataBind()
Line 92: dbconn.Close()


 
Thanks Daren.

sthmpsn1 I am not sure what is happening there. I would suggest running the debugger to see what the Decrypt function is returning. I am guessing that it is an exception error. See the try catch code above

You are trying to decrypt something that isn't encrypted. One way or another this will give you wierd result if not errors. Try passing the Encryptor something that is already encrypted.
Try this one.
myEncryptor.Decrypt(&quot;fGfN+OabJg3Mvfel7IS6uQ==&quot;) That'l do donkey, that'l do
[bravo] Mark
 
This post is now nicely packaged in a new FAQ
faq855-2388 That'l do donkey, that'l do
[bravo] Mark
 
Mark,
in case you wanted to include a c# version to your faq... here it is

using System;
using System.IO;
using System.Text;
using System.Security;
using System.Security.Cryptography;

public class Encryptor
{
static private Byte[] m_Key = new Byte[8];
static private Byte[] m_IV = new Byte[8];

public string EncryptData(String strKey, String strData)
{
string strResult; //Return Result
if (strData.Length > 92160)
{
strResult=&quot;Error. Data String too large. Keep within 90Kb.&quot;;
return strResult;
}

if (!InitKey(strKey))
{
strResult=&quot;Error. Fail to generate key for encryption&quot;;
return strResult;
}

strData = String.Format(&quot;{0,5:00000}&quot;+strData, strData.Length);
byte[] rbData = new byte[strData.Length];
ASCIIEncoding aEnc = new ASCIIEncoding();
aEnc.GetBytes(strData, 0, strData.Length, rbData, 0);

DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
ICryptoTransform desEncrypt = descsp.CreateEncryptor(m_Key, m_IV);

MemoryStream mStream = new MemoryStream(rbData);
CryptoStream cs = new CryptoStream(mStream, desEncrypt, CryptoStreamMode.Read);
MemoryStream mOut = new MemoryStream();

int bytesRead;
byte[] output = new byte[1024];
do
{
bytesRead = cs.Read(output,0,1024);
if (bytesRead != 0)
mOut.Write(output,0,bytesRead);
} while (bytesRead > 0);

if (mOut.Length == 0)
strResult = &quot;&quot;;
else
strResult = Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length);

return strResult;
}

public string DecryptData(String strKey, String strData)
{
string strResult;

if (!InitKey(strKey))
{
strResult=&quot;Error. Fail to generate key for decryption&quot;;
return strResult;
}

int nReturn = 0;
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV);

MemoryStream mOut = new MemoryStream();
CryptoStream cs = new CryptoStream(mOut, desDecrypt, CryptoStreamMode.Write);

byte[] bPlain = new byte[strData.Length];
try
{
bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length);
}
catch (Exception)
{
strResult = &quot;Error. Input Data is not base64 encoded.&quot;;
return strResult;
}

long lRead = 0;
long lTotal = strData.Length;

try
{
while (lTotal >= lRead)
{
cs.Write(bPlain,0,(int)bPlain.Length);
lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize));
};

ASCIIEncoding aEnc = new ASCIIEncoding();
strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length);

String strLen = strResult.Substring(0,5);
int nLen = Convert.ToInt32(strLen);
strResult = strResult.Substring(5, nLen);
nReturn = (int)mOut.Length;

return strResult;
}
catch (Exception)
{
strResult = &quot;Error. Decryption Failed. Possibly due to incorrect Key or corrputed data&quot;;
return strResult;
}
}

static private bool InitKey(String strKey)
{
try
{
byte[] bp = new byte[strKey.Length];
ASCIIEncoding aEnc = new ASCIIEncoding();
aEnc.GetBytes(strKey, 0, strKey.Length, bp, 0);

SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
byte[] bpHash = sha.ComputeHash(bp);
int i;

for (i=0; i<8; i++)
m_Key = bpHash;

for (i=8; i<16; i++)
m_IV[i-8] = bpHash;

return true;
}
catch (Exception)
{
return false;
}
}
} Daren J. Lahey
Just another computer guy...
 
Daren are you bored??? That'l do donkey, that'l do
[bravo] Mark
 
wow, that is awesome of you mark to do that!! Thanks for all the code, and mine works fine on encrypting and decrypting. If I put the data in a text box like this textbox2.text = myEncryptor.Decrypt(empDS.tables(&quot;testy&quot;).Rows(0).Item(&quot;Name&quot;)) it works great, but if I try to do the above where I put all the records into a dropdown menu then I get the above error. So I think my problem is how I am trying to bind this data. themonths.DataTextField = myEncryptor.Decrypt(&quot;Name&quot;)

can you think of another way of doing this?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top