Solved

How to encrypt/decrypt a string

Posted on 2008-09-30
6
1,232 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

691 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