Category Archives: Security & Cryptography

MIT Professor Develops NSA-like Email Data Visualization Software

See for yourself:
https://immersion.media.mit.edu/

Defend and Fix your site attacked by “lizamoon” and other types of SQL Injection

Before I discuss some of the more technical details regarding defense against “lizamoon” and similar attacks, an important note I would like to make to any business executives who may stumble across the article or hear it secondhand:

PCI

if you’re doing ecommerce… is a must!

In an ideal scenario, all developers should follow good coding practice such as SQL Command Parameterization, but realistically, especially depending heavily on the coding language behind used, sometimes this is either difficult or simply forgotten.

PCI Compliance, or at least awareness of OWASP and PCI DSS 2.0 security standards should be an important thought for anyone who is currently in or looking to get into ecommerce.

These standards help outline specific safeguards, and in the case of compliance, certify these safeguards with assessment scans that help developers identify and fix potential security flaws.

lizamoon

This latest exploit, currently live and in the wild at the time of writing this blog, is getting quite some fame for it’s scope of number of businesses affected.

As far as rarity or complexity, the attack is simply some cleverly crafted SQL Injection, which can be avoided altogether using SQL Command Parameterization.

However, if you were victimized by this attack and are utilizing a system which your developers did not implement, you’re in a much tougher scenario since you probably cannot modify the code directly or even identify the attack’s point of entry.

As a quick fix and temporary workaround until a patch for your system is release, to resolve this, go through the following checklist:

1) Find out which ecommerce or web platform you’re using which has been compromised and open a support ticket/initiate a support call with your vendor.
2) Research with your webmaster, provider or IT department if you are using shared or cloud hosting, virtual dedicated hosting or dedicated.
3) If you are using shared hosting, begin migration to a virtual dedicated or dedicated host, since you will not be able to make the necessary changes for the workaround fix on a shared or cloud host.
4) If you are on a virtual or fully dedicated plan, or newly migrated from shared hosting, note if you have a Windows or Linux machine.
5) On Windows, navigate to C:\windows\system32\drivers\etc\, on Linux go to /etc/. Note this path.
6) On Windows, open up notepad (right click and run as administrator if on Vista or later), on Linux open your favorite text editor as root or superuser.
7) In your text editor, open the “hosts” file located at the path you noted in step 5.
8) Add a new line pointing the lizamoon domain to your loopback address. (see code below)

127.0.0.1  lizamoon.com

How this works:

The hosts file maps machine names and domains to IP Addresses (although not vice versa), and overrides the resulting IP address you would otherwise receive from your DNS provider.

In terms of your ecommerce site, this translates to users clicking on a link on your site affected by the exploit, but instead of being directed to lizamoon.com like the attackers intended (no one knows yet why they are doing this..), the users will instead be bounced back to your site root (usually the homepage).

This gives you enough time to hunt down or wait for a more permanent patch, without putting your shoppers at increased risk and at least averting danger temporarily. I would highly advise anyone affected by this attack however to consider PCI auditing or at least security consultation regarding their ecommerce or web application.

Impersonation with Network Credentials in C# .Net

(Mostly) unmodified code, courtesy of Phil Harding (see references below for original post).

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Tools.Network
{
public enum LogonType
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,// Win2K or higher
LOGON32_LOGON_NEW_CREDENTIALS = 9// Win2K or higher
};

public enum LogonProvider
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3
};

public enum ImpersonationLevel
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3
}

class Win32NativeMethods
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LogonUser(string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
}

/// <summary>
/// Allows code to be executed under the security context of a specified user account.
/// </summary>
/// <remarks>
///
/// Implements IDispose, so can be used via a using-directive or method calls;
///...
///
///var imp = new Impersonator( "myUsername", "myDomainname", "myPassword" );
///imp.UndoImpersonation();
///
///...
///
/// var imp = new Impersonator();
///imp.Impersonate("myUsername", "myDomainname", "myPassword");
///imp.UndoImpersonation();
///
///...
///
///using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
///{
///...
///1
///...
///}
///
///...
/// </remarks>
public class Impersonator : IDisposable
{
private WindowsImpersonationContext _wic;

/// <summary>
/// Begins impersonation with the given credentials, Logon type and Logon provider.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
/// <param name="logonType">Type of the logon.</param>
/// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
public Impersonator(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
{
Impersonate(userName, domainName, password, logonType, logonProvider);
}

/// <summary>
/// Begins impersonation with the given credentials.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
public Impersonator(string userName, string domainName, string password)
{
Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
}

/// <summary>
/// Initializes a new instance of the <see cref="Impersonator"/> class.
/// </summary>
public Impersonator()
{}

/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
UndoImpersonation();
}

/// <summary>
/// Impersonates the specified user account.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
public void Impersonate(string userName, string domainName, string password)
{
Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
}

/// <summary>
/// Impersonates the specified user account.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
/// <param name="logonType">Type of the logon.</param>
/// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
public void Impersonate(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
{
UndoImpersonation();

IntPtr logonToken = IntPtr.Zero;
IntPtr logonTokenDuplicate = IntPtr.Zero;
try
{
// revert to the application pool identity, saving the identity of the current requestor
_wic = WindowsIdentity.Impersonate(IntPtr.Zero);

// do logon & impersonate
if (Win32NativeMethods.LogonUser(userName,
domainName,
password,
(int)logonType,
(int)logonProvider,
ref logonToken) != 0)
{
if (Win32NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0)
{
var wi = new WindowsIdentity(logonTokenDuplicate);
wi.Impersonate();// discard the returned identity context (which is the context of the application pool)
}
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
finally
{
if (logonToken != IntPtr.Zero)
Win32NativeMethods.CloseHandle(logonToken);

if (logonTokenDuplicate != IntPtr.Zero)
Win32NativeMethods.CloseHandle(logonTokenDuplicate);
}
}

/// <summary>
/// Stops impersonation.
/// </summary>
private void UndoImpersonation()
{
// restore saved requestor identity
if (_wic != null)
_wic.Undo();
_wic = null;
}
}
}

References
http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/

aspnet_setreg in Server 2008

The aspnet_setreg utility is very useful for storing encrypted domain credentials, connection strings and other values referenced in a web.config which should not be visible in plaintext.

One such technique is when using the .Net “impersonation” mechanism. Typically, this would look something like:

<system.web>
<identity impersonate="true" userName="WindowsDomain\YourUserName" password="YourPassword" />
</system.web> 

However, if you download and unzip/install the aspnet_setreg utility, you can now use the following syntax to store these credentials in a binary encrypted field in the registry:

c:\Tools>aspnet_setreg.exe -k:SOFTWARE\MY_SECURE_APP\identity -u:"yourdomainname\username" -p:"password"

Your web.config should now be updated to reflect the new stored values. (Note: this is the exact syntax, don't replace username and password with your own...):

<identity impersonate="true"
userName="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,username"
password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,password" />

An important thing to note is in Server 2008 on a 64 bit machine after running this utility is a different location it is stored in the registry. To find it you must browse to:

[HKEY_CURRENT_USER\Software\Classes\VirtualStore\MACHINE\SOFTWARE\Wow6432Node]

You can then right click and export this key from here, then open the .reg file in notepad and change to the correct key and import. The end result should be a reg file to import that looks like this:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\Software\MY_SECURE_APP]

[HKEY_LOCAL_MACHINE\Software\MY_SECURE_APP\identity]

[HKEY_LOCAL_MACHINE\Software\MY_SECURE_APP\identity\ASPNET_SETREG]
"userName"=hex:01,00,00, etc
"password"=hex:01,00,00, etc

References
MSDN, http://support.microsoft.com/kb/329290
ASPDEV, http://www.aspdev.org/articles/web.config/
ASPNET FORUMS, http://forums.asp.net/t/1650965.aspx/1?aspnet_setreg+under+Win+2008

ZyXel Port Forwarding Issues

After what seemed like endless search over short period of time, and much wasted time on phone calls to support reps who were not familiar with telnet.. I finally stumbled across this article below from howtoforge

Big thanks goes out to sugree and cpbotha on this one and all the guys at howtoforge that helped google index their site so I could find this article. :)

1. Telnet to the router and enter administrative password
2. Go to menu 24 and then 8
3. Run command "ip nat loopback on"
4. Type "exit" and then 99 to quit from the management screen


For a little background history, this was originally a double NAT scenario. If you have another router and the ZyXel, my recommendation would be to disable DHCP on your second router, enable it on the ZyXel and connect the second router to the ZyXel via LAN port instead of the second routers WAN port. This will utilize the second router as a bridge and maintain a single subnet instead of two separate subnets. All port forwarding can then be done from the ZyXel.

References
http://www.howforge.com/4-steps-to-turn-on-nat-loopback-in-zyxel-router

Reset Password from Command Prompt in Server 2008

For a developer or IT admin working in Windows Server 2008 environment, you may have noticed ctrl+alt+del does not work over remote connection and you can no longer change your password from control panel.

The best solution to this in my opinion, that will likely work far into the future, is the command line.

Also keep in mind you are a server admin and disable much functionality for your remote users, sometimes these permissions don’t always apply to command line variants and the latter can be used for privilege escalation in the event of a workstation or user profile compromise.

net user user_name * /domain

net user user_name  new_password

ex.
net user Bob 12bdir5$

References
Microsoft Support, "How to Change User Password at Command Prompt",

File Shredder Shortcut using SDelete in Windows XP, Vista, 7

Computer enthusiasts have been using file shredders to delete files for many years. Sysinternals makes a very cool utility called “SDelete” that “shreds” a file

See below for batch file code snippet to use with SDelete. Add to your “User/Administrator/AppData/Roaming/Microsoft/Windows/SendTo” (In Vista/7/Serv08) or “Documents and Settings\%username%\SendTo” (In XP).

(%APPDATA% environment variable actually points to “C:\users\\AppData\Roaming”)

I have modified the code below from it’s original source on blog (see references) to 3 passes instead of four. See wikipedia page for more information on data remanence. If the script runs slow on your system consider decreasing this to 3 or 4.


@echo off
:START
if "%~f1"=="" (
echo No more args given. Done.
exit /b 0
)
:WORK
ECHO Y| cacls %1 /T /C /G Administrators:F
attrib -h -s -r -a %1 /S /D
attrib -h -s -r -a %1\*.* /S /D
sdelete -p 7 -s -q %1
:NEXTARG
shift
goto START

Addendum 2012.11.09
Windows 7 environment path seems to be buggy at times. Absolute references to executables is more reliable.

@echo off
:START
if "%~f1"=="" (
echo No more args given. Done.
exit /b 0
)
:WORK
ECHO Y| C:\Windows\System32\cacls.exe %1 /T /C /G Administrators:F
C:\Windows\System32\attrib.exe -h -s -r -a %1 /S /D
C:\Windows\System32\attrib.exe -h -s -r -a %1\*.* /S /D
C:\Windows\System32\sdelete.exe -p 7 -s -q %1
:NEXTARG
shift
goto START


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All server side code examples are in C# .Net.

References
Sysinternals, Blog: "My Handy sdelete scripts", Soulstace, http://forum.sysinternals.com/my-handy-sdelete-scripts_topic6065.html
Wikipedia, "Data Remanance", http://en.wikipedia.org/wiki/Data_remanence
HowToGeek, http://www.howtogeek.com/howto/windows-vista/customize-the-windows-vista-send-to-menu/

Strong Password Generator

Pretty good little web based site to generate strong passwords on the fly. Once I have some time to whip up a little tool to do the same I’ll be sure to post code here.

(Requires javascript:)
StrongPasswordGenerator

References
StrongPasswordGenerator, http://strongpasswordgenerator.com/

Encryption 101 and Security for the Paranoid

Asymmetric Cryptography

Asymmetric Cryptography

Modern day television, cinemas and news have created a big hype around security, especially computer security, usually without any good explanation.

I’m not going to tell you that hype is false, there is definitely a growing need to be careful in these areas, but in order to make informed decisions you need to become knowledgeable about the subject.

Unfortunately most literature and content that comes from these media outlets glances on these topics just enough to make a cautious viewer paranoid, but are not necessarily informative.

Fact:
Computer security issues are increasing as well as personal safety in general with regards to technology, such as card swiping, identity theft, etc. (Source: US GOVT).

Fiction:
By spending all your money on expensive antivirus software, home security systems, identity theft protection and specialized credit cards you will be completely safe and can rest soundly.

The reality is the best protection you can really offer yourself is mostly common sense and can be remembered with a simple timeless phrase…

Never put all your eggs in one basket.

24 Security Tips for the Paranoid

(that don’t require emptying your wallet)

(see glossary below for any terms you are unfamiliar with)

[1]

If there’s a little flashing icon in the bottom of your screen that says viruses have been found on your PC, or notifications offering to help you “fix” your PC, DON’T CLICK ON IT. 75% of all computer repairs I handle were victims of this circumstance. Well known vendors such as Norton, AVG and CA allow you to run timed and manual scans. If you’re not sure where this flashing little icon came from, Google it.. or email me. :)

[2]

If you’re concerned about online credit card theft, get a separate credit card just for online purchases with a very low spending limit.

[3]

Try to use common checkout methods you are familiar with such as Paypal and Google Checkout. Google and paypal have certain specifications for these methods that in many cases make them more secure than the standard method on a particular site.

[4]

Keep track of sites where you store your credit card numbers (if you choose to store them at all). In the event of compromise from online purchases this will help you identify the point of breach and you were likely not the only person affected.

[5]

Research pre-paid cards which aren’t necessarily tied to a long term account and already have many built in securities.

[6]

Memorize important numbers that do not change, such as your SS, Bank and Routing. Don’t write them down and especially don’t store them electronically.

[7]

It’s hard to memorize all your passwords, so write down hints instead. If your password is related to the date you bought your first $animal (<- dog), write down something obscure like the last name of your $animal veterinarian or something even harder to relate like just a number representing the age of your animal (in $animal years).

[8]

Visit only well known websites and be careful of links from blogs ;) and places your friends may refer you to which could unknowingly be compromised. Social networks, much like school, are an easy place to pick up germs. Secure ecommerce sites should certify that they are PCI compliant.

[9]

Learn how basic encryption works. Many applications such as outlook contain plugins for popular encryption techniques such as GPG.

[10]

Be wary of public terminals, airports and coffee shops. Even if you’re on your smart phone and browsing the WiFi at your favorite Starbucks or even JFK, the entire location or an individual access point could have been compromised or an attacker could be snooping and that cool remote banking app on your phone could open up a can of worms.

[11]

Similar to the above, always use https and/or secure networks only (esp. if wireless) whenever possible. Learn how to add Mac address filtering on your local wireless network or call your favorite local IT guy (me!) and ask them what you could do to lock down.

[12]

If possible, keep a small safety net. While disputing fraud or identity theft, you may need funds temporarily to cover bills and other perishables until the issue is resolved.

[13]

If you’re loaning money to your son/daughter/family member or close friend, give them cash or a prepaid credit card which you can refill as needed or transfer money to their bank. Loaning credit cards can be very dangerous especially if the one you are helping doesn’t follow similar security tips as these.

[14]

If you’re traveling or visiting somewhere you don’t go very often, such as a business or personal family trip, or a not frequently visited restaurant – use cash. Most types of fraud occur overseas and on long-distance trips. (Source: US GOVT).

[15]

If you lose your cell phone or wallet, make sure to cancel any and all cards and identification contained within or have numbers re-issued. This will be a hassle, but it’s worth it.

[16]

Always lock or password protect your computer and electronic devices whenever possible. A lost cellphone or laptop could contain personal information and lead to compromise. In addition, many devices such as smartphones contain security countermeasures which allow you to remotely wipe the device if it is lost.

[17]

Own at least two forms of photo identification and only carry at most one on your person if possible. Whether it is military ID, state ID, drivers license or passport, if you happen to lose one it is often easier to re-obtain if you still have the other.

[18]

When you’re leaving the house, only bring the necessities. You should probably always carry your drivers license, especially if you’re pulled over for speeding ;). You or a relative’s social security card and other non-critical credit cards may not always need to be in your possession however. If you frequently use checks, keep a few in your wallet or purse, but don’t bring the whole checkbook.

[19]

Don’t share passwords or accounts! Your husband or spouse might be the exception, but make sure he/she is also familiar with these tips if you do.

[20]

If you’re concerned about home invasion, theft or burglary, purchase or make a sign which indicates the home is under surveillance and protected. Even if no such protection exists, this will often ward would-be attackers casing your home. If one or more of your neighbors has the same protection, they will likely avoid your neighborhood altogether permanently.

[21]

When traveling and away from home for a long period, a webcam can be setup as basic home surveillance. Keep in mind, this could also open up the possibility of your webcam becoming compromised so make sure they are setup in places such as the main room or doors and entry ways and do not make them accessible over the internet unless you first tunnel through a VPN.

[22]

Place anything important in a safe whenever possible. Jewelry or belongings which are rarely used fall into this category.

[23]

For home based businesses or small business owners – Beware of dumpster diving and make sure you have locked filing cabinets and shred any documents you don’t need. Old documents can be scanned and archived electronically and stored onto tape or other persistent media which can be encrypted. This can also be helpful in the event of a flood or fire.

[24]

If you’re extremely paranoid and worried that basic antivirus and a home alarm system or sign/neighborhood watch won’t be enough, purchase DIY home booby traps, watch every Home Alone movie in one sitting, and be prepared to lose all friend and family relations. Get ready for a long and lonely life. :P

Glossary of Terms:

safety net – An alternative bank account, safe or separately managed funds to help you pay for expenses while recovering from fraud or any other event which could affect your existing assets.

SSL – A protocol which wraps your connection to a website inside a “secure socket layer” of encryption.

Dumpster Diving – Bad guys going through your trash looking for information.

VPN – Virtual Private Network. A secure way of accessing your home remotely. Call your local IT guy or do some Googling to set one up.

Casing – Bad guys driving through your neighborhood looking for targets. To prevent, talk to your neighbors, or put a sign and/or camera in front of the house.

skim / skimming / swiping – This is when bad guys posing as good guys, at your local restaurant or favorite retail store in the city, illicitly obtain your credit card number. Remember the tips regarding credit cards above as this crime is likely to increase over the next few years.

snoop / snooping / sniffing – In the context of computer security, this is usually when another user on the network is listening or capturing all information going to and from. Stick to SSL sites and secure wireless networks only.

encrypt / decrypt – Encryption is the process of transforming content from plaintext into ciphertext. decryption is the reverse; from ciphertext to plaintext.

plaintext / ciphertext – plaintext is human readable. like your email or the text messages on your phone. ciphertext is garbled and in many cases not even alphanumeric characters. writing in pig-latin or through a mirror is not making ciphertext. ciphertext requires someone to either know or guess the key, password, passphrase and/or vectors and apply a specific type of decryption to reverse.

key / password / passphrase / vector – These are all roughly synonymous with password and are sometimes stored in files instead of being typed in. Research encryption for more info on vectors.

TDES / AES / Rijndael / 128bit /block cipher – If you see or hear any words like this, they are talking about encryption and cryptography. These are different types. Read more on Wikipedia or my other pages.

bit (strength) – In the context of computer security or encryption this usually is in reference to the strength of the security, measured in bits. This can also apply to SSL strength since this utilizes encryption. Common values include 40bit, 64bit, 128bit, 256bit and 512bit.

asymmetric / symmetric – This identifies the process a particular encryption method uses, generally with regards to how information is communicated between two or more parties. It doesn’t necessarily govern HOW the data is encrypted, just the process flow of the data itself from beginning to end. See references below and research GPG for examples on how this might be usable in your everyday life.

pci compliance – Payment Card Industry standard on how personal data should be stored, processed and transmitted. Very important and might be better to understand for your general knowledge than you might think. See references for links.

Conclusion

For a technical illustration, take a look at my quick net encryption reference for a working example in Microsoft .Net which illustrates asymmetric key encryption.

See articles on encryption at Wikipedia and similarly linked articles for a more complete reference.

References:
Wikipedia, Encryption, http://en.wikipedia.org/wiki/Encryption
U.S. CERT, http://www.us-cert.gov/cas/tips/
GPG, http://www.gnupg.org/
PCI DSS, https://www.pcisecuritystandards.org/security_standards/index.php

Quick .Net Encryption Reference

The code below represents a very basic .NET encryption class which has been tested and should work in your application – simply plug and play. :)

Contains two static methods that can be called without needing to instantiate the class.

Keep in mind the initialization vector below (indicated by rgbIV) is generic, and you will need to come up with your own. Remember not to share this. Even if the password is compromised, the attacker would also need to know the initialization vector to crack your value.

Also note the code which has been commented out. This illustrates cases where passwords and/or IV can be statically set in the class and/or shared based on value passed in for password parameter.

Sharing IV and password or storing either statically is a security risk and could cause errors depending on byte differences of the values. If you statically store these values, you will still create secure cipher text, but it will be much easier to crack.

Enjoy. ;)

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

namespace AIS.Common.Crypto
{

public static class Rijndael
{
    public static string Encrypt(string ClearText,string password)
    {

        byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        MemoryStream ms = new MemoryStream();
        
        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),
   CryptoStreamMode.Write);

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);

        cs.Close();

        return Convert.ToBase64String(ms.ToArray());
    }

    public static string Decrypt(string EncryptedText, string password)
    {
        byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

        MemoryStream ms = new MemoryStream();

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
        CryptoStreamMode.Write);

        cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

        cs.Close();

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

    }

}
}

References:
Wikipedia - Encryption, http://en.wikipedia.org/wiki/Encryption

Follow

Get every new post delivered to your Inbox.