Solved

How to encrypt/decrypt a string

Posted on 2008-09-30
6
1,206 Views
Last Modified: 2009-08-19
I need to encrypt a string to store in a database (credit card number).  How can I do this with c#?
0
Comment
Question by:centdevs
  • 3
  • 3
6 Comments
 
LVL 5

Expert Comment

by:johnaryan
ID: 22605500
Try this:
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            MemoryStream ms = new MemoryStream(Convert.FromBase64String(sSource));

            CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(),

            CryptoStreamMode.Read);
 

            for (int i = 0; i < ms.Length; i++)

            {

                // the next line with throw a CryptographicException with the

                // message: "Padding is invalid and can not be removed."

                cs.ReadByte();

            }

        }

Open in new window

0
 

Author Comment

by:centdevs
ID: 22605536
Do I have to store a key for this somewhere?
0
 
LVL 5

Expert Comment

by:johnaryan
ID: 22605676
It uses the MachineKey as far as i know, but this can be changed.
You can do a search on CryptoStream to find out the specifics.
Here's the MSDN reference: http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:centdevs
ID: 22605872
This is pretty new to me, how do I get the encrypted string back out, cs.ToString() ?  Like if I want to create an encrypt method and a decrypt method, each that returns either an encrypted string or a decrypted string.
0
 
LVL 5

Accepted Solution

by:
johnaryan earned 500 total points
ID: 22606026
This is another snippet from MSDN and should do what you need.
using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Text;

using System.Security.Cryptography;

using System.IO;
 

namespace QueryStringEncryption

{

    public class Cryptography

    {

        #region Fields
 

        private static byte[] key = { };

        private static byte[] IV = { 38, 55, 206, 48, 28, 64, 20, 16 };

        private static string stringKey = "!5663a#KN";
 

        #endregion
 

        #region Public Methods
 

        public static string Encrypt(string text)

        {

            try

            {

                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                Byte[] byteArray = Encoding.UTF8.GetBytes(text);

                MemoryStream memoryStream = new MemoryStream();

                CryptoStream cryptoStream = new CryptoStream(memoryStream,

                    des.CreateEncryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);

                cryptoStream.FlushFinalBlock();

                return Convert.ToBase64String(memoryStream.ToArray());

            }

            catch (Exception ex)

            {

                // Handle Exception Here

            }

            return string.Empty;

        }
 
 
 

        public static string Decrypt(string text)

        {

            try

            {

                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                Byte[] byteArray = Convert.FromBase64String(text);

                MemoryStream memoryStream = new MemoryStream();

                CryptoStream cryptoStream = new CryptoStream(memoryStream,

                    des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);

                cryptoStream.FlushFinalBlock();

                return Encoding.UTF8.GetString(memoryStream.ToArray());

            }

            catch (Exception ex)

            {

                // Handle Exception Here

            }

            return string.Empty;

        }
 
 
 

        #endregion
 

    }
 

}

Open in new window

0
 

Author Comment

by:centdevs
ID: 22607346
How can I test this?  I'm trying to send the encrypt method a string, and then send the result to the decrypt method, but it catches an exception "Bad Data"
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
XAML: Layout 8 25
Excel file not created as expected 7 50
Word Directory is not in the drop down list 4 25
C# HTTP GET method sample code 3 41
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now