c#


How to encrypt a string in .NET? [duplicate]


This question already has an answer here:
Encrypt and decrypt a string
24 answers
I have to encrypt/decrypt some sensitive information in a Xml file?
Yes I can do that by writing my own custom algorithms. I am wondering if there is already a built in way in .NET to do that and also what points I always need to take care..
Here's a couple of functions that use the .NET framework to encrypt and decrypt a string:
public string EncryptString(string plainText)
{
// Instantiate a new RijndaelManaged object to perform string symmetric encryption
RijndaelManaged rijndaelCipher = new RijndaelManaged();
// Set key and IV
rijndaelCipher.Key = Convert.FromBase64String("ABC");
rijndaelCipher.IV = Convert.FromBase64String("123");
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our RijndaelManaged object
ICryptoTransform rijndaelEncryptor = rijndaelCipher.CreateEncryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelEncryptor, CryptoStreamMode.Write);
// Convert the plainText string into a byte array
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
// Encrypt the input plaintext string
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
// Complete the encryption process
cryptoStream.FlushFinalBlock();
// Convert the encrypted data from a MemoryStream to a byte array
byte[] cipherBytes = memoryStream.ToArray();
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
// Convert the encrypted byte array to a base64 encoded string
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
// Return the encrypted data as a string
return cipherText;
}
public string DecryptString(string cipherText)
{
// Instantiate a new RijndaelManaged object to perform string symmetric encryption
RijndaelManaged rijndaelCipher = new RijndaelManaged();
// Set key and IV
rijndaelCipher.Key = Convert.FromBase64String("ABC");
rijndaelCipher.IV = Convert.FromBase64String("123");
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our RijndaelManaged object
ICryptoTransform rijndaelDecryptor = rijndaelCipher.CreateDecryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelDecryptor, CryptoStreamMode.Write);
// Will contain decrypted plaintext
string plainText = String.Empty;
try
{
// Convert the ciphertext string into a byte array
byte[] cipherBytes = Convert.FromBase64String(cipherText);
// Decrypt the input ciphertext string
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
// Complete the decryption process
cryptoStream.FlushFinalBlock();
// Convert the decrypted data from a MemoryStream to a byte array
byte[] plainBytes = memoryStream.ToArray();
// Convert the encrypted byte array to a base64 encoded string
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
}
// Return the encrypted data as a string
return plainText;
}
Of course I don't advise hardcoding the key and initialisation vector like this :)
You will probably want to dive into the System.Security.Cryptography namespace. I guess the articles Cryptography Overview, Encrypting Data and Decrypting Data at MSDN could be good starters.

Related Links

WCF Service calling WCF Service - Where to put client service reference?
Match a hash created in C# with sql
Selecting an image on property change in viewmodel
WCF Service Library only works when run from Visual Studio
How to Convert DataReader Result to Entity? ->use Emit
Recalc Cart In ASP.NET Site
how to get expiration date of local windows account?
Replace Version Information (C#)
Regex match pull href link and string in between <a></a> [duplicate]
Executing commands from C# problem
Cloning AJAX TabPanels
Problems serializing types for a .NET WCF Service: Service WSDL defines empty types in XSD
MaxArrayLength Exception in WPF
Contains functionality in Linq to XML Where Clause
How can you do a mass unload of Assemblies from GAC by PublicKeyToken?
How to convert some C# code to Pascal?

Categories

HOME
qlikview
airflow
internet-explorer
url
azure-documentdb
pyspark
packet
formatting
boxplot
stdout
pandoc
sugarcrm
atlassian-fisheye
rmarkdown
pip
fetch
ldap-query
resharper
console-application
appsettings
google-calendar-api3
project-reactor
django-rest-auth
bootstrap-datetimepicker
keystone
monad-transformers
ejb-3.1
prepros
inspec
traveling-salesman
mex
drombler-fx
marionette
windows-10-mobile
deferred
overflow
foxpro
login-required
urhosharp
postgresql-9.6
unity3d-5
azure-vm-scale-set
blueimp
lfe
google-chrome-console
compiled-query
datagridviewcombobox
head
codepen
easyquery
kendo-scheduler
group
spring-social-twitter
copy-constructor
timefield
networkstream
scriptengine
gdi
music-player
datamodel
nslocalizedstring
dynamics-nav
overlapping
taverna
exchange-server-2007
first-order-logic
roslyn-code-analysis
pagecontrol
connection-timeout
service-broker
teamstudio-unplugged
nsq
powershell-v1.0
xts
triplestore
email-headers
logo-lang
dynamic-expresso
proj4
gmail-imap
string-length
phone-state-listener
urlfetch
antixsslibrary
linqdatasource
webpage-screenshot
android-memory
optimistic-concurrency
automapper-2
vectorwise
xpolog
soapexception
conditional-operator
arraycollection
subdirectories
linq-to-mysql
newspeak
content-delivery-network
cross-cutting-concerns
ironpython-studio

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App