473,396 Members | 2,140 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

String Encryption

Lee

Does anyone have any recommendation for encrypting simple strings to
be stored in a db?

Thank you,
--
Warm Regards,
Lee

"Upon further investigation it appears that your software is missing
just one thing. It definitely needs more cow bell..."
Mar 24 '06 #1
9 9156
How strong does it have to be?

Simple encryption that does'nt change the string size is nice, so you
don't outrun your db string space!

Unless I had a reason to be very paranoid about security, I'd go with
that ...

Mar 25 '06 #2
How strong does it have to be?

Simple encryption that does'nt change the string size is nice, so you
don't outrun your db string space!

Unless I had a reason to be very paranoid about security, I'd go with
that ...

Mar 25 '06 #3
Hello lee,

See codesnippet below

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.
using (MemoryStream memStream = new
MemoryStream(originalStrAsBytes.Length))
{
using (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.
using (ICryptoTransform rdTransform =
rijndael.CreateEncryptor((byte[])savedKey.
Clone( ),(byte[])savedIV.Clone( )))
{
using (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( );
}
}
}
}
// 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];

using (RijndaelManaged rijndael = new RijndaelManaged( ))
{
using (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.
using (ICryptoTransform rdTransform =
rijndael.CreateDecryptor((byte[])savedKey.
Clone( ),(byte[])savedIV.Clone( )))
{
using (CryptoStream cryptoStream = new CryptoStream(memStream,
rdTransform, CryptoStreamMode.Read))
{
// Read in decrypted string as a byte[].
cryptoStream.Read(initialText, 0, initialText.Length);
}
}
}
}

// Convert byte[] to string.
string decryptedStr = Encoding.ASCII.GetString(initialText);
return (decryptedStr);
}
}
l> Does anyone have any recommendation for encrypting simple strings to
l> be stored in a db?
l>
l> Thank you,
l>
l> "Upon further investigation it appears that your software is missing
l> just one thing. It definitely needs more cow bell..."
l>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Mar 25 '06 #4
Michael Nemtsev <ne*****@msn.com> wrote:
See codesnippet below


Two suggested changes:
1) Use UTF-8 instead of ASCII
2) Use StreamReaders/Writers instead of creating an intermediate byte
array.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 25 '06 #5
Lee
Michael Nemtsev enlightened me by writing:
Hello lee,

See codesnippet below


Thank you. Do you know if this is save for database insertion? I've
tried to use encrypted strings but the characters sometimes cause
problems in a sql script.

Thanks again,
--
Warm Regards,
Lee

"Upon further investigation it appears that your software is missing
just one thing. It definitely needs more cow bell..."
Mar 25 '06 #6
Lee <lu*************@yahoo.com> wrote:
See codesnippet below


Thank you. Do you know if this is save for database insertion? I've
tried to use encrypted strings but the characters sometimes cause
problems in a sql script.


That suggests that you've tried to use the encrypted binary data as if
it were plain text. Michael's code takes the binary data and base64-
encodes it, which is an excellent way of doing things.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 25 '06 #7

Lee wrote:
Does anyone have any recommendation for encrypting simple strings to
be stored in a db?

Thank you,

1 Encryption is not a simple subject.

2 Have a look at the encryption already built into .NET, for instance
AES/Rijndael.

3 Most good encryption will produce random looking bytes, if you want
to store it as a string then have a look at Base64, also in .NET though
that will take up more space.

rossum

Mar 25 '06 #8
Lee
Jon Skeet [C# MVP] enlightened me by writing:


That suggests that you've tried to use the encrypted binary data as
if it were plain text. Michael's code takes the binary data and
base64- encodes it, which is an excellent way of doing things.


Oops, you're right. I missed that.

Thank you.

--
Warm Regards,
Lee

"Upon further investigation it appears that your software is missing
just one thing. It definitely needs more cow bell..."
Mar 26 '06 #9
You can make use many classes available in Cryptography namespace. Are you
using SQL Server 2005 as you database? If so you can also leverage new
security features in SQL Server 2005 and do the encryption directly in
database.
Mar 26 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Nathan | last post by:
Is there a way to convert a string to a CipherMessage? I am calling a function that decrypts a CipherMessage and returns the value. The only problem is when I want to use an encrypted value stored...
14
by: msnews.microsoft.com | last post by:
How can I encrypt and decrypt string?
7
by: Matthias S. | last post by:
Hi, I had a look at the vast information on encryption in the MSDN and got pretty confused. All I want to do is to encrypt a string into an encrypted string and later decrypt that (encrypted)...
2
by: Mike P | last post by:
I need a way of encrypting strings that provides a fairly high level of encryption. I've looked at System.Security.Cryptography at...
12
by: Charlie | last post by:
Hi: My host will not allow me use a trusted connection or make registry setting, so I'm stuck trying find a way to hide connection string which will be stored in web.config file. If I encrypt...
6
by: larry mckay | last post by:
Hi, Does anyone have any simple text string encryption routines that are easy to implement? I'm trying to prevent users and system administrators from figuring out how I implement things....
14
by: WebMatrix | last post by:
Hello, I have developed a web application that connects to 2 different database servers. The connection strings with db username + password are stored in web.config file. After a code review,...
4
by: JJ | last post by:
I need to encrypt credit card # and store that in a database (and be able to decrypt it). Any codes that use strong encyption algorithm like AES 256 on the web that I can copy and paste? Thanks
8
by: Jeremy Kitchen | last post by:
I have encoded a string into Base64 for the purpose of encryption. I then later decrypted it and converted it back from Base64 the final string returns with four nothing characters. "pass" what...
22
by: j1mb0jay | last post by:
I have had to create a simple string encryption program for coursework, I have completed the task and now have to do a write up on how it could be improved at a later date. If you could look...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.