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

How would you unit test an ExpressionVisitor?
Binding ComboBox SelectedItem to double
How to open DBF(dBase) file faster way and update it very fast using VS C#?
How to test a class full of constants
Received file is empty using Chrome and Firefox, but not with IE
Replace string in file using a SQL procedure
.NET config files issues of proprietary soft
How to distinguish NotFound returned from server and NotFound because of bad connectivity?
How to get values from an XML file matching XPath query in C#
Obsolete library class
Sending a font file (.cpf) to zebra Qln320 printer over WLAN
How to analyze the kernel dump in WinDBG
Content-Aware Image Cropping with C#
How to create a camera capture guide line bars
Optimize Dictionary Add on ExpandoObjects in C#
using App_Data in connection string

Categories

HOME
gulp
gcc
cxf
blob
liquibase
mifare
livecharts
azure-resource-manager
assign
artifactory
snmp
jshell
multipartform-data
autocad
servicenow
sequence
sitemap
google-my-business-api
wowza
ng2-charts
logstash-configuration
luis
conditional-formatting
beaker-notebook
onclicklistener
email-client
rancher
sasl
dynamic-memory-allocation
angular-schema-form
custom-fields
apm
oracle-nosql
favorites
webmock
zimbra
angularjs-resource
pyenv
repeat
maven-2
kepserverex
const
libzip
gradlew
qtwebkit
serialversionuid
google-cloud-shell
runtime-permissions
e4
px4
ajv
nservicebus6
opticalflow
senti-wordnet
iban
group
lattice
portaudio
cedar-bdd
eclipse-mars
boost-range
konakart
netlink
init
particle-system
csc
hfp
music-player
skbio
std
app-data
controlpanel
maven-antrun-plugin
properties-file
tooltwist
xml-simple
sparkcore
transparentproxy
page-refresh
teamwork
copy-on-write
google-experiments
numerical-recipes
frisby.js
os.walk
tigase
step
dateadd
smartxls
power-management
starling-framework
autofilter
friendly-id
mobile-robots
azure-scheduler
database-restore
gpl
screensharing
mail-gem
doxia
diazo
win-prolog
motorola-droid
scriptmanager
clgeocoder
wdm
rjs
execjs
nbehave
database-agnostic
xslt-grouping
unauthorized
memory-consumption

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