1 using System; 2 using System.IO; 3 using System.Text; 4 using System.Security.Cryptography; 5 6 /// <summary> 7 /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and
8 /// decrypt data. As long as encryption and decryption routines use the same 9 /// parameters to generate the keys, the keys are guaranteed to be the same. 10 /// The class uses static functions with duplicate code to make it easier to 11 /// demonstrate encryption and decryption logic. In a real-life application,
12 /// this may not be the most efficient way of handling encryption, so - as 13 /// soon as you feel comfortable with it - you may want to redesign this class. 14 /// </summary> 15 public class RijndaelSimple 16 { 17 /// <summary> 18 /// Encrypts specified plaintext using Rijndael symmetric key algorithm 19 /// and returns a base64-encoded result. 20 /// </summary> 21 /// <param name="plainText"> 22 /// Plaintext value to be encrypted. 23 /// </param> 24 /// <param name="passPhrase"> 25 /// Passphrase from which a pseudo-random password will be derived. The 26 /// derived password will be used to generate the encryption key. 27 /// Passphrase can be any string. In this example we assume that this 28 /// passphrase is an ASCII string. 29 /// </param> 30 /// <param name="saltValue"> 31 /// Salt value used along with passphrase to generate password. Salt can 32 /// be any string. In this example we assume that salt is an ASCII string. 33 /// </param> 34 /// <param name="hashAlgorithm"> 35 /// Hash algorithm used to generate password. Allowed values are: "MD5" and 36 /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes. 37 /// </param> 38 /// <param name="passwordIterations"> 39 /// Number of iterations used to generate password. One or two iterations 40 /// should be enough. 41 /// </param> 42 /// <param name="initVector"> 43 /// Initialization vector (or IV). This value is required to encrypt the 44 /// first block of plaintext data. For RijndaelManaged class IV must be
45 /// exactly 16 ASCII characters long. 46 /// </param> 47 /// <param name="keySize"> 48 /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
49 /// Longer keys are more secure than shorter keys. 50 /// </param> 51 /// <returns> 52 /// Encrypted value formatted as a base64-encoded string. 53 /// </returns> 54 public static string Encrypt(string plainText, 55 string passPhrase, 56 string saltValue, 57 string hashAlgorithm, 58 int passwordIterations, 59 string initVector, 60 int keySize) 61 { 62 // Convert strings into byte arrays. 63 // Let us assume that strings only contain ASCII codes. 64 // If strings include Unicode characters, use Unicode, UTF7, or UTF8
65 // encoding. 66 byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); 67 byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue); 68 69 // Convert our plaintext into a byte array. 70 // Let us assume that plaintext contains UTF8-encoded characters. 71 byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); 72 73 // First, we must create a password, from which the key will be derived. 74 // This password will be generated from the specified passphrase and
75 // salt value. The password will be created using the specified hash
76 // algorithm. Password creation can be done in several iterations. 77 PasswordDeriveBytes password = new PasswordDeriveBytes( 78 passPhrase,
79 saltValueBytes,
80 hashAlgorithm,
81 passwordIterations); 82 83 // Use the password to generate pseudo-random bytes for the encryption 84 // key. Specify the size of the key in bytes (instead of bits). 85 byte[] keyBytes = password.GetBytes(keySize / 8); 86 87 // Create uninitialized Rijndael encryption object. 88 RijndaelManaged symmetricKey = new RijndaelManaged(); 89 90 // It is reasonable to set encryption mode to Cipher Block Chaining 91 // (CBC). Use default options for other symmetric key parameters. 92 symmetricKey.Mode = CipherMode.CBC; 93 94 // Generate encryptor from the existing key bytes and initialization
95 // vector. Key size will be defined based on the number of the key
96 // bytes. 97 ICryptoTransform encryptor = symmetricKey.CreateEncryptor( 98 keyBytes,
99 initVectorBytes); 100 101 // Define memory stream which will be used to hold encrypted data. 102 MemoryStream memoryStream = new MemoryStream();
103 104 // Define cryptographic stream (always use Write mode for encryption). 105 CryptoStream cryptoStream = new CryptoStream(memoryStream,
106 encryptor, 107 CryptoStreamMode.Write); 108 // Start encrypting. 109 cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); 110 111 // Finish encrypting. 112 cryptoStream.FlushFinalBlock(); 113 114 // Convert our encrypted data from a memory stream into a byte array. 115 byte[] cipherTextBytes = memoryStream.ToArray(); 116 117 // Close both streams. 118 memoryStream.Close(); 119 cryptoStream.Close(); 120 121 // Convert encrypted data into a base64-encoded string. 122 string cipherText = Convert.ToBase64String(cipherTextBytes); 123 124 // Return encrypted string. 125 return cipherText; 126 } 127 128 /// <summary> 129 /// Decrypts specified ciphertext using Rijndael symmetric key algorithm. 130 /// </summary> 131 /// <param name="cipherText"> 132 /// Base64-formatted ciphertext value. 133 /// </param> 134 /// <param name="passPhrase"> 135 /// Passphrase from which a pseudo-random password will be derived. The 136 /// derived password will be used to generate the encryption key. 137 /// Passphrase can be any string. In this example we assume that this 138 /// passphrase is an ASCII string. 139 /// </param> 140 /// <param name="saltValue"> 141 /// Salt value used along with passphrase to generate password. Salt can 142 /// be any string. In this example we assume that salt is an ASCII string. 143 /// </param> 144 /// <param name="hashAlgorithm"> 145 /// Hash algorithm used to generate password. Allowed values are: "MD5" and 146 /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes. 147 /// </param> 148 /// <param name="passwordIterations"> 149 /// Number of iterations used to generate password. One or two iterations 150 /// should be enough. 151 /// </param> 152 /// <param name="initVector"> 153 /// Initialization vector (or IV). This value is required to encrypt the 154 /// first block of plaintext data. For RijndaelManaged class IV must be 155 /// exactly 16 ASCII characters long. 156 /// </param> 157 /// <param name="keySize"> 158 /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. 159 /// Longer keys are more secure than shorter keys. 160 /// </param> 161 /// <returns> 162 /// Decrypted string value. 163 /// </returns> 164 /// <remarks> 165 /// Most of the logic in this function is similar to the Encrypt 166 /// logic. In order for decryption to work, all parameters of this function 167 /// - except cipherText value - must match the corresponding parameters of 168 /// the Encrypt function which was called to generate the 169 /// ciphertext. 170 /// </remarks> 171 public static string Decrypt(string cipherText, 172 string passPhrase, 173 string saltValue, 174 string hashAlgorithm, 175 int passwordIterations, 176 string initVector, 177 int keySize) 178 { 179 // Convert strings defining encryption key characteristics into byte 180 // arrays. Let us assume that strings only contain ASCII codes. 181 // If strings include Unicode characters, use Unicode, UTF7, or UTF8 182 // encoding. 183 byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); 184 byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue); 185 186 // Convert our ciphertext into a byte array. 187 byte[] cipherTextBytes = Convert.FromBase64String(cipherText); 188 189 // First, we must create a password, from which the key will be
190 // derived. This password will be generated from the specified
191 // passphrase and salt value. The password will be created using 192 // the specified hash algorithm. Password creation can be done in 193 // several iterations. 194 PasswordDeriveBytes password = new PasswordDeriveBytes( 195 passPhrase,
196 saltValueBytes,
197 hashAlgorithm,
198 passwordIterations); 199 200 // Use the password to generate pseudo-random bytes for the encryption 201 // key. Specify the size of the key in bytes (instead of bits). 202 byte[] keyBytes = password.GetBytes(keySize / 8); 203 204 // Create uninitialized Rijndael encryption object. 205 RijndaelManaged symmetricKey =
new RijndaelManaged(); 206 207 // It is reasonable to set encryption mode to Cipher Block Chaining 208 // (CBC). Use default options for other symmetric key parameters. 209 symmetricKey.Mode = CipherMode.CBC; 210 211 // Generate decryptor from the existing key bytes and initialization
212 // vector. Key size will be defined based on the number of the key
213 // bytes. 214 ICryptoTransform decryptor = symmetricKey.CreateDecryptor( 215 keyBytes,
216 initVectorBytes); 217 218 // Define memory stream which will be used to hold encrypted data. 219 MemoryStream memoryStream = new MemoryStream(cipherTextBytes); 220 221 // Define cryptographic stream (always use Read mode for encryption). 222 CryptoStream cryptoStream = new CryptoStream(memoryStream,
223 decryptor, 224 CryptoStreamMode.Read); 225 226 // Since at this point we don't know what the size of decrypted data 227 // will be, allocate the buffer long enough to hold ciphertext; 228 // plaintext is never longer than ciphertext. 229 byte[] plainTextBytes =
new byte[cipherTextBytes.Length]; 230 231 // Start decrypting. 232 int decryptedByteCount = cryptoStream.Read(plainTextBytes,
233 0, 234 plainTextBytes.Length); 235 236 // Close both streams. 237 memoryStream.Close(); 238 cryptoStream.Close(); 239 240 // Convert decrypted data into a string.
241 // Let us assume that the original plaintext string was UTF8-encoded. 242 string plainText = Encoding.UTF8.GetString(plainTextBytes,
243 0, 244 decryptedByteCount); 245 246 // Return decrypted string. 247 return plainText; 248 } 249 }
Happy programming [Idea]
With Thanks.,
R.Chezhian.,
=============================================
Please Mark the helpful post(s) as Answered
>Given any random file, is there a way to tell if it has already been encrypted or not?
Aside of there being a jumple of characters, there is no way, other than it being plain text.
Click "Mark as Answer" on the post that helped you.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
chezhian_in05
Contributor
2512 Points
615 Posts
Encrypt & Decrypt strings
Oct 08, 2008 07:28 AM|LINK
1 using System;
Happy programming [Idea]2 using System.IO;
3 using System.Text;
4 using System.Security.Cryptography;
5
6 /// <summary>
7 /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and
8 /// decrypt data. As long as encryption and decryption routines use the same
9 /// parameters to generate the keys, the keys are guaranteed to be the same.
10 /// The class uses static functions with duplicate code to make it easier to
11 /// demonstrate encryption and decryption logic. In a real-life application, 12 /// this may not be the most efficient way of handling encryption, so - as
13 /// soon as you feel comfortable with it - you may want to redesign this class.
14 /// </summary>
15 public class RijndaelSimple
16 {
17 /// <summary>
18 /// Encrypts specified plaintext using Rijndael symmetric key algorithm
19 /// and returns a base64-encoded result.
20 /// </summary>
21 /// <param name="plainText">
22 /// Plaintext value to be encrypted.
23 /// </param>
24 /// <param name="passPhrase">
25 /// Passphrase from which a pseudo-random password will be derived. The
26 /// derived password will be used to generate the encryption key.
27 /// Passphrase can be any string. In this example we assume that this
28 /// passphrase is an ASCII string.
29 /// </param>
30 /// <param name="saltValue">
31 /// Salt value used along with passphrase to generate password. Salt can
32 /// be any string. In this example we assume that salt is an ASCII string.
33 /// </param>
34 /// <param name="hashAlgorithm">
35 /// Hash algorithm used to generate password. Allowed values are: "MD5" and
36 /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
37 /// </param>
38 /// <param name="passwordIterations">
39 /// Number of iterations used to generate password. One or two iterations
40 /// should be enough.
41 /// </param>
42 /// <param name="initVector">
43 /// Initialization vector (or IV). This value is required to encrypt the
44 /// first block of plaintext data. For RijndaelManaged class IV must be
45 /// exactly 16 ASCII characters long.
46 /// </param>
47 /// <param name="keySize">
48 /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
49 /// Longer keys are more secure than shorter keys.
50 /// </param>
51 /// <returns>
52 /// Encrypted value formatted as a base64-encoded string.
53 /// </returns>
54 public static string Encrypt(string plainText,
55 string passPhrase,
56 string saltValue,
57 string hashAlgorithm,
58 int passwordIterations,
59 string initVector,
60 int keySize)
61 {
62 // Convert strings into byte arrays.
63 // Let us assume that strings only contain ASCII codes.
64 // If strings include Unicode characters, use Unicode, UTF7, or UTF8
65 // encoding.
66 byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
67 byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
68
69 // Convert our plaintext into a byte array.
70 // Let us assume that plaintext contains UTF8-encoded characters.
71 byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
72
73 // First, we must create a password, from which the key will be derived.
74 // This password will be generated from the specified passphrase and
75 // salt value. The password will be created using the specified hash
76 // algorithm. Password creation can be done in several iterations.
77 PasswordDeriveBytes password = new PasswordDeriveBytes(
78 passPhrase,
79 saltValueBytes,
80 hashAlgorithm,
81 passwordIterations);
82
83 // Use the password to generate pseudo-random bytes for the encryption
84 // key. Specify the size of the key in bytes (instead of bits).
85 byte[] keyBytes = password.GetBytes(keySize / 8);
86
87 // Create uninitialized Rijndael encryption object.
88 RijndaelManaged symmetricKey = new RijndaelManaged();
89
90 // It is reasonable to set encryption mode to Cipher Block Chaining
91 // (CBC). Use default options for other symmetric key parameters.
92 symmetricKey.Mode = CipherMode.CBC;
93
94 // Generate encryptor from the existing key bytes and initialization
95 // vector. Key size will be defined based on the number of the key
96 // bytes.
97 ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
98 keyBytes,
99 initVectorBytes);
100
101 // Define memory stream which will be used to hold encrypted data.
102 MemoryStream memoryStream = new MemoryStream();
103
104 // Define cryptographic stream (always use Write mode for encryption).
105 CryptoStream cryptoStream = new CryptoStream(memoryStream,
106 encryptor,
107 CryptoStreamMode.Write);
108 // Start encrypting.
109 cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
110
111 // Finish encrypting.
112 cryptoStream.FlushFinalBlock();
113
114 // Convert our encrypted data from a memory stream into a byte array.
115 byte[] cipherTextBytes = memoryStream.ToArray();
116
117 // Close both streams.
118 memoryStream.Close();
119 cryptoStream.Close();
120
121 // Convert encrypted data into a base64-encoded string.
122 string cipherText = Convert.ToBase64String(cipherTextBytes);
123
124 // Return encrypted string.
125 return cipherText;
126 }
127
128 /// <summary>
129 /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
130 /// </summary>
131 /// <param name="cipherText">
132 /// Base64-formatted ciphertext value.
133 /// </param>
134 /// <param name="passPhrase">
135 /// Passphrase from which a pseudo-random password will be derived. The
136 /// derived password will be used to generate the encryption key.
137 /// Passphrase can be any string. In this example we assume that this
138 /// passphrase is an ASCII string.
139 /// </param>
140 /// <param name="saltValue">
141 /// Salt value used along with passphrase to generate password. Salt can
142 /// be any string. In this example we assume that salt is an ASCII string.
143 /// </param>
144 /// <param name="hashAlgorithm">
145 /// Hash algorithm used to generate password. Allowed values are: "MD5" and
146 /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
147 /// </param>
148 /// <param name="passwordIterations">
149 /// Number of iterations used to generate password. One or two iterations
150 /// should be enough.
151 /// </param>
152 /// <param name="initVector">
153 /// Initialization vector (or IV). This value is required to encrypt the
154 /// first block of plaintext data. For RijndaelManaged class IV must be
155 /// exactly 16 ASCII characters long.
156 /// </param>
157 /// <param name="keySize">
158 /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
159 /// Longer keys are more secure than shorter keys.
160 /// </param>
161 /// <returns>
162 /// Decrypted string value.
163 /// </returns>
164 /// <remarks>
165 /// Most of the logic in this function is similar to the Encrypt
166 /// logic. In order for decryption to work, all parameters of this function
167 /// - except cipherText value - must match the corresponding parameters of
168 /// the Encrypt function which was called to generate the
169 /// ciphertext.
170 /// </remarks>
171 public static string Decrypt(string cipherText,
172 string passPhrase,
173 string saltValue,
174 string hashAlgorithm,
175 int passwordIterations,
176 string initVector,
177 int keySize)
178 {
179 // Convert strings defining encryption key characteristics into byte
180 // arrays. Let us assume that strings only contain ASCII codes.
181 // If strings include Unicode characters, use Unicode, UTF7, or UTF8
182 // encoding.
183 byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
184 byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
185
186 // Convert our ciphertext into a byte array.
187 byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
188
189 // First, we must create a password, from which the key will be
190 // derived. This password will be generated from the specified
191 // passphrase and salt value. The password will be created using
192 // the specified hash algorithm. Password creation can be done in
193 // several iterations.
194 PasswordDeriveBytes password = new PasswordDeriveBytes(
195 passPhrase,
196 saltValueBytes,
197 hashAlgorithm,
198 passwordIterations);
199
200 // Use the password to generate pseudo-random bytes for the encryption
201 // key. Specify the size of the key in bytes (instead of bits).
202 byte[] keyBytes = password.GetBytes(keySize / 8);
203
204 // Create uninitialized Rijndael encryption object.
205 RijndaelManaged symmetricKey = new RijndaelManaged();
206
207 // It is reasonable to set encryption mode to Cipher Block Chaining
208 // (CBC). Use default options for other symmetric key parameters.
209 symmetricKey.Mode = CipherMode.CBC;
210
211 // Generate decryptor from the existing key bytes and initialization
212 // vector. Key size will be defined based on the number of the key
213 // bytes.
214 ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
215 keyBytes,
216 initVectorBytes);
217
218 // Define memory stream which will be used to hold encrypted data.
219 MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
220
221 // Define cryptographic stream (always use Read mode for encryption).
222 CryptoStream cryptoStream = new CryptoStream(memoryStream,
223 decryptor,
224 CryptoStreamMode.Read);
225
226 // Since at this point we don't know what the size of decrypted data
227 // will be, allocate the buffer long enough to hold ciphertext;
228 // plaintext is never longer than ciphertext.
229 byte[] plainTextBytes = new byte[cipherTextBytes.Length];
230
231 // Start decrypting.
232 int decryptedByteCount = cryptoStream.Read(plainTextBytes,
233 0,
234 plainTextBytes.Length);
235
236 // Close both streams.
237 memoryStream.Close();
238 cryptoStream.Close();
239
240 // Convert decrypted data into a string.
241 // Let us assume that the original plaintext string was UTF8-encoded.
242 string plainText = Encoding.UTF8.GetString(plainTextBytes,
243 0,
244 decryptedByteCount);
245
246 // Return decrypted string.
247 return plainText;
248 }
249 }
R.Chezhian.,
=============================================
Please Mark the helpful post(s) as Answered
jp2code
Member
69 Points
29 Posts
Re: Encrypt & Decrypt strings
Nov 21, 2008 03:05 PM|LINK
Very helpful.
Given any random file, is there a way to tell if it has already been encrypted or not?
Joe Pool
jp2code.net
TATWORTH
All-Star
72395 Points
14016 Posts
MVP
Re: Encrypt & Decrypt strings
Nov 28, 2008 02:46 PM|LINK
>Given any random file, is there a way to tell if it has already been encrypted or not?
Aside of there being a jumple of characters, there is no way, other than it being plain text.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239