473,804 Members | 3,126 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Encrypt a string to a string and vice versa

Hi,

I had a look at the vast information on encryption in the MSDN and got
pretty confused. All I want to do is to encrypt a string into an encrypted
string and later decrypt that (encrypted) string again to a human readable
form. Can't be that difficult :).

Could you send me please into the right direction. Thanks in advance.

--

kind regards,

matthias

--

I love deadlines. I like the whooshing sound they make as they fly by.
[Douglas Adams]
Nov 16 '05 #1
7 26799
Hi Matthias,

I haven't really done this myself only implement the classic ROT13
scrambler\descr amber but check out,

http://www.dotnetspider.com/Technology/KBPages/611.aspx

http://www.dotnet247.com/247reference/msgs/5/28421.aspx

Hope this gives you some direction. One thing you should consider about
deadlines as well, if it wasn't for the last minute, nothing would get done.
Hope this assist you.

SpotNet.

"Matthias S." <matthias@_e_m_ v_o_i_d_.de> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
Hi,

I had a look at the vast information on encryption in the MSDN and got
pretty confused. All I want to do is to encrypt a string into an encrypted
string and later decrypt that (encrypted) string again to a human readable
form. Can't be that difficult :).

Could you send me please into the right direction. Thanks in advance.

--

kind regards,

matthias

--

I love deadlines. I like the whooshing sound they make as they fly by.
[Douglas Adams]

Nov 16 '05 #2
Hi Matthias,

..NET provides cryptographics services in class contained in the
System.Security .Cryptography namespace.

First, you need to decide on which type of encryption you would like to use
- basically, there are three: symmetric, asymmetric, and hashing. From what
you said, you should go for either of the first two. Go for symmetric for
more performance, and asymmetric if you need more security.

Once that is decided, you create an instance of the required
CryptoServicePr ovider in the required class. For example,
System.Security .Cryptography.R SACryptoService Provider which derives from
System.Security .Cryptography.A symmetricAlgori thm and then use the required
method (eg. Enrypt). Note that most of these method accept a Stream or an
array of bytes, so you will have to use UTF8 encoding class to convert your
string.

Check out this MSDN link for a detailed implementation
http://msdn.microsoft.com/library/en...yptingdata.asp

Let me know if I could help more.

HTH,
Rakesh Rajan



"Matthias S." wrote:
Hi,

I had a look at the vast information on encryption in the MSDN and got
pretty confused. All I want to do is to encrypt a string into an encrypted
string and later decrypt that (encrypted) string again to a human readable
form. Can't be that difficult :).

Could you send me please into the right direction. Thanks in advance.

--

kind regards,

matthias

--

I love deadlines. I like the whooshing sound they make as they fly by.
[Douglas Adams]

Nov 16 '05 #3
Matthias S. <matthias@_e_m_ v_o_i_d_.de> wrote:
I had a look at the vast information on encryption in the MSDN and got
pretty confused. All I want to do is to encrypt a string into an encrypted
string and later decrypt that (encrypted) string again to a human readable
form. Can't be that difficult :).

Could you send me please into the right direction. Thanks in advance.


The encryption libraries in .NET (like most encryption libraries) are
from binary to binary. So, you need to:

1) Convert your string to binary: use an Encoding and its GetBytes
method. I would suggest Encoding.UTF8.

2) Encrypt the binary data. Look at CryptoStream for some sample code.
You need to make sure you call FlushFinalBlock or Close - Dispose isn't
correctly implemented in CryptoStream.

3) Convert the resulting binary data into a string again. For this, I'd
suggest using Base64 - Convert.ToBase6 4String.
To decrypt, just reverse - use Convert.FromBas e64String, then a
CryptoStream, then Encoding.UTF8.G etString(bytes) .

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
hi john,

thanks for your reply which was of big help. So far I managed to encrypt
the string but running into problems when decrypting:

Here is how I encrypt:
+++
// sSource contains the string to be encrypted
UTF8Encoding utf8 = new UTF8Encoding();
byte[] utf8Bytes = utf8.GetBytes(s Source);

// encrypt
SymmetricAlgori thm rijn = SymmetricAlgori thm.Create();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms , rijn.CreateEncr yptor(),
CryptoStreamMod e.Write);

for (int i = 0; i < utf8Bytes.Lengt h; i++) {
cs.WriteByte(ut f8Bytes[i]);
}

cs.Flush();
// return the encrypted string
return Convert.ToBase6 4String(ms.ToAr ray());
+++

it seems to work fine. I will be knowing it once I've managed to decrypt
the whole thing again.

Here is how I'd like to decrypt:
+++
SymmetricAlgori thm rijn = SymmetricAlgori thm.Create();
MemoryStream ms = new MemoryStream(Co nvert.FromBase6 4String(sSource ));
CryptoStream cs = new CryptoStream(ms , rijn.CreateDecr yptor(),
CryptoStreamMod e.Read);

for (int i = 0; i < ms.Length; i++) {
// the next line with throw a CryptographicEx ception with the
// message: "Padding is invalid and can not be removed."
cs.ReadByte();
}
+++

Besides that I figured that the CryptoStream does not support a Length
property. So how am I can I get my cs variable into a byte[]?

Thanks for any help again!
kind regards,

matthias

--

I love deadlines. I like the whooshing sound they make as they fly by.
[Douglas Adams]

Jon Skeet [C# MVP] wrote:
Matthias S. <matthias@_e_m_ v_o_i_d_.de> wrote:
I had a look at the vast information on encryption in the MSDN and got
pretty confused. All I want to do is to encrypt a string into an encrypted
string and later decrypt that (encrypted) string again to a human readable
form. Can't be that difficult :).

Could you send me please into the right direction. Thanks in advance.

The encryption libraries in .NET (like most encryption libraries) are
from binary to binary. So, you need to:

1) Convert your string to binary: use an Encoding and its GetBytes
method. I would suggest Encoding.UTF8.

2) Encrypt the binary data. Look at CryptoStream for some sample code.
You need to make sure you call FlushFinalBlock or Close - Dispose isn't
correctly implemented in CryptoStream.

3) Convert the resulting binary data into a string again. For this, I'd
suggest using Base64 - Convert.ToBase6 4String.
To decrypt, just reverse - use Convert.FromBas e64String, then a
CryptoStream, then Encoding.UTF8.G etString(bytes) .

Nov 16 '05 #5
Matthias S. <matthias@_e_m_ v_o_i_d_.de> wrote:
thanks for your reply which was of big help. So far I managed to encrypt
the string but running into problems when decrypting:

Here is how I encrypt:
+++
// sSource contains the string to be encrypted
UTF8Encoding utf8 = new UTF8Encoding();
byte[] utf8Bytes = utf8.GetBytes(s Source);

// encrypt
SymmetricAlgori thm rijn = SymmetricAlgori thm.Create();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms , rijn.CreateEncr yptor(),
CryptoStreamMod e.Write);

for (int i = 0; i < utf8Bytes.Lengt h; i++) {
cs.WriteByte(ut f8Bytes[i]);
}

cs.Flush();


You're neither calling Close() nor FlushFinalBlock () on the
CryptoStream. That may well be the problem.

By the way: using ReadByte and WriteByte is a pretty painful way of
reading and writing data. Use the forms which read and write blocks of
data at a time, paying attention to the return value from Read.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
hi john,

sorry if I didn't make myself clear enough. The encryption method works
fine (at least I don't get an exception anywhere, if the string is
correctly encryption is left aside). The problem lies in the
Decryption-part of the task, where I'm just creating a MemoryStream by
converting the result of my previously mentioned encryption method using
Convert.FromBas e64String().

The problem is, as soon as I call ReadByte on the CryptoStream, I get the
CryptographicEx ception mentioned below.

+++
SymmetricAlgori thm rijn = SymmetricAlgori thm.Create();
MemoryStream ms = new MemoryStream(Co nvert.FromBase6 4String(sSource ));
CryptoStream cs = new CryptoStream(ms , rijn.CreateDecr yptor(),
CryptoStreamMod e.Read);

for (int i = 0; i < ms.Length; i++) {
// the next line with throw a CryptographicEx ception with the
// message: "Padding is invalid and can not be removed."
cs.ReadByte();
+++

As to your answer on the Read-Method, I actually don't know how to Read
*anything* from the stream if I can't retrieve the current Position or
Length (both not provided in the CryptoStream).

btw, big thanks to you for helping me out on this one.

kind regards,

matthias

--

I love deadlines. I like the whooshing sound they make as they fly by.
[Douglas Adams]

Jon Skeet [C# MVP] wrote:
Matthias S. <matthias@_e_m_ v_o_i_d_.de> wrote:
thanks for your reply which was of big help. So far I managed to encrypt
the string but running into problems when decrypting:

Here is how I encrypt:
+++
// sSource contains the string to be encrypted
UTF8Encodin g utf8 = new UTF8Encoding();
byte[] utf8Bytes = utf8.GetBytes(s Source);

// encrypt
SymmetricAlgo rithm rijn = SymmetricAlgori thm.Create();
MemoryStrea m ms = new MemoryStream();
CryptoStrea m cs = new CryptoStream(ms , rijn.CreateEncr yptor(),
CryptoStreamM ode.Write);

for (int i = 0; i < utf8Bytes.Lengt h; i++) {
cs.WriteByte(ut f8Bytes[i]);
}

cs.Flush();

You're neither calling Close() nor FlushFinalBlock () on the
CryptoStream. That may well be the problem.

By the way: using ReadByte and WriteByte is a pretty painful way of
reading and writing data. Use the forms which read and write blocks of
data at a time, paying attention to the return value from Read.

Nov 16 '05 #7
Matthias S. <matthias@_e_m_ v_o_i_d_.de> wrote:
sorry if I didn't make myself clear enough. The encryption method works
fine (at least I don't get an exception anywhere, if the string is
correctly encryption is left aside). The problem lies in the
Decryption-part of the task, where I'm just creating a MemoryStream by
converting the result of my previously mentioned encryption method using
Convert.FromBas e64String().

The problem is, as soon as I call ReadByte on the CryptoStream, I get the
CryptographicEx ception mentioned below.


The problem is that the encryption *hasn't* worked - you've not got all
the data. You didn't get an exception, but you didn't get the right
data, either.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
22741
by: Espen Ruud Schultz | last post by:
Lets say I have a char pointer and an std::string. Is it possible to get a pointer to the std::string's "content" so that the char pointer can point to the same text? And vice versa; can I give the std::string a pointer and a length and then give the std::string control over the pointer and its content? I'm basically trying to avoid copying large text between an std::string and a char pointer, and vice versa. Is there anyhing in the...
1
3350
by: Dharmendra Singh | last post by:
Hi I'm using .Net(C#) and working on the form(Screen) which have text boxes for both arabic and english data to store. So i want to change the language at run time from arabic to english and vice-versa, when the control moves from one text box to another. Regards Dharmendra
2
6834
by: Steve - DND | last post by:
Just wondering if anyone out there has any code to convert a plural word to it's singular form and vice versa. Most of our database tables are named in a plural fashion. When we go to create templates to select a single record, we end up with a class name that sounds as if it's a collection instead of just one data object. Just wondering if anyone has a nice workaround. I started working on something, but it quickly turned into a large...
1
2536
by: Eugene Anthony | last post by:
Private Function BStr2UStr(BStr) 'Byte string to Unicode string conversion Dim lngLoop BStr2UStr = "" For lngLoop = 1 to LenB(BStr) BStr2UStr = BStr2UStr & Chr(AscB(MidB(BStr,lngLoop,1))) Next End Function Private Function UStr2Bstr(UStr)
16
2157
by: Hugh Janus | last post by:
Hi all, I am using the below functions in order to convert strings to bytes and vice versa. I totally ans shamefully stole these functions from this group btw! Anyway, they work great but as sooooo slow. Anyone know how I can speed this functions up? I basically need to convert a byte to string, perform a function on each 'section' of the string, then reconvert it to a byte. The slow part is the conversion to and from byte, not the...
6
39291
yabansu
by: yabansu | last post by:
Hi all, I think most of you probably know the two .NET framework functions, namely Encoding.GetBytes(string) and Encoding.GetString(byte), to convert string into byte array and vice versa. Now, I want to do the same thing in pure(unmanaged) C++. I searched the Internet but could not find any satisfactory solutions. I am really in need of help! Is there anyone to explain how I can implement these functions by not using .NET library? ...
6
7462
by: =?Utf-8?B?TFBldGVy?= | last post by:
Hi, I would copy the characters of a string variable to a fixed character buffer in a struct (and vice versa) in C#. public struct S { ... public fixed char cBuff; ...
1
2010
by: Maric Michaud | last post by:
Le Tuesday 24 June 2008 07:08:46 swapna mudavath, vous avez écrit : This is not valid xml, there is no commas in attribute list in xml. You could try with minidom if your xml stream isn't too large, else sax parser is to be considered, but minidom is pretty easy to use. Give it a try and come back with more specific questions.
0
4614
by: FarooqRafiq | last post by:
Hi, My requirement is that a string is encrypted in VB.NET and sent to PHP, PHP decrypts the string (till here the logic is working) and then the PHP should encrtyp (where i am having problems) and send the data to VB.NET application. The proble is in encrypting in PHP side. PHP Code <?php //$syscode=$_REQUEST; //The actual string is "blueberry" which is encrypted in VB.NET and sent to PHP $syscode = "8yN73RDmMFuXo9ux8QKC6w==";...
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10564
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10320
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10308
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10073
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7609
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6846
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2981
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.