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

Web api Authorization filter not firing
fileStream.WriteByte c# can't write in directory. It's need admin permission [duplicate]
A DependencyProperty of Type ObservableCollection<T> set in XAML contains more items than there are declared. c#
V8Context not created when passing “about:blank” to ChromiumWebBrowser's constructor
Comparing game objects Augmented reality game, Unity, Vuforia, C#
How to display image from 2D integer array in Winforms application
Allow PDFium to support x86 and x64
how to show only time from datetime databse data in aspx page?
Remove need for xsi:type from xml?
ERR_CONNECTION_REFUSED - .Net Core 1.0.1
Lost information between scenes
Visual Studio 2017 Application Manifest
Thread state on blocking Stream.Read() call
How to use outlook classes as Outlook.AppoinmentItem and Outlook.meetingItem
how to give path to ipa file in xamrin ui test
What are the responsibilities for the StatefulService contra ICommunicationListener

Categories

HOME
asp.net
alasql
arcgis
magento-1.9.2.1
spss
perl6
yuv
python-3.4
pyodbc
subprocess
dcos
decoding
logstash-configuration
responsive
luis
pylint
openam
scotty
vala
mattermost
windowserror
mongoose-im
libxml2
2checkout
paper-trail-gem
schedule
boost-log
opencsv
qt-designer
restler
webmock
apache-falcon
n1ql
framebuffer
jibx
file-conversion
ng-lightning
idea-plugin
mtm
colorbox
qt-quick
smooth-streaming
nshttpurlresponse
grails-2.0
spring-webflow-2
hierarchical-clustering
dna-sequence
visualizer
dmalloc
chain
node.js-client
nls
cedar-bdd
ldd
boost-range
init
objectify
db2-zos
php-java-bridge
mrunit
transaction-isolation
laterjs
wonderware
ewam
dynamics-nav-2013
dynamics-nav
controlpanel
newlib
ios8-share-extension
play-json
random-sample
vanilla-forums
p4python
vspackage
targetprocess
genero
cl.exe
sony-xperia
random-access
uiblureffect
fedena
launcher
javacompiler
farpoint-spread
new-operator
slimscroll
cvi
ie-developer-tools
nokogiri
google-checkout
http-compression
pymel
microsoft-speech-platform
database-restore
rbm
qt5.1
screensharing
cryptarithmetic-puzzle
flatten
dancer
django-1.4
zend-validate
youtube.net-api
zipstream
meego-harmattan
lwp
llblgen
lgpl
datadude
qlibrary
unauthorized
jettison

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