ArticleDirectory
- Parameters
- Return Value
- Remarks
A good example on msdn: there is a problem in the sentence of clearing the password from memory. Let's take a look at how this problem is solved.
Cannot convert from sytem. inptr to ref string
Take the following sentence
Public static extern bool zeromemory (ref string destination, int length );
Use this sentence to replace it.
Internal static extern void zeromemory (intptr handle, int length );
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; using system. security; using system. security. cryptography; using system. runtime. interopservices; namespace msdnencryexample {class program {// call this function to remove the key from memory after use for security. [system. runtime. interopservices. dllimport ("kernel32.dll", entrypoint = "rtlzeromemory")] internal static extern void zeromemory (intptr handle, int length); // function to generate a 64 bits key. static string generatekey () {// create an instance of symetric algorithm. key and IV is generated automatically. descryptoserviceprovider descrypto = (descryptoserviceprovider) descryptoserviceprovider. create (); // use the automatically generated key for encryption. return asciiencoding. ASCII. getstring (descrypto. key);} static void encryptfile (string sinputfilename, string soutputfilename, string skey) {// create a file stream to read the data to be encrypted filestream fsinput = new filestream (sinputfilename, filemode. open, fileaccess. read); // Crete a file stream for the encrypted data filestream fsencrypted = new filestream (soutputfilename, filemode. create, fileaccess. write); // create encryptor by usin the key descryptoserviceprovider des = new descryptoserviceprovider (); des. key = asciiencoding. ASCII. getbytes (skey); des. IV = asciiencoding. ASCII. getbytes (skey); icryptotransform desencrypt = des. createencryptor (); // create a crytostream to link the encrypted stream and the encryptor cryptostream = new cryptostream (fsencrypted, desencrypt, cryptostreammode. write); // read the file stream to bytes array byte [] bytearrayinput = new byte [fsinput. length]; fsinput. read (bytearrayinput, 0, bytearrayinput. length); // encrypt the byte array by using the cryptostream. write (bytearrayinput, 0, bytearrayinput. length); // close the file streams cryptostream. close (); fsinput. close (); fsencrypted. close ();} static void decryptfile (string sinputfilename, string soutputfilename, string skey) {// set the descryptoserviceprovider class descryptoserviceprovider des = new descryptoserviceprovider (); // a 64-bit key and IV is required for this provider. // set secret key for DES algorithm. des. key = asciiencoding. ASCII. getbytes (skey); // set initialization vector. des. IV = asciiencoding. ASCII. getbytes (skey); // create a file stream to read the encrypted file back. filestream fsread = new filestream (sinputfilename, filemode. open, fileaccess. read); // create a des decryptor from the des instance. icryptotransform desdecrypt = des. createdecryptor (); // create crypto stream set to read and do a // des Decryption Transform on incoming bytes. cryptostream cryptostreamdecr = new cryptostream (fsread, desdecrypt, cryptostreammode. read); // print the contents of the decrypted file. streamwriter fsdecrypted = new streamwriter (soutputfilename); fsdecrypted. write (New streamreader (cryptostreamdecr ). readtoend (); fsdecrypted. flush (); fsdecrypted. close ();} static void main (string [] ARGs) {// must be 64 bits, 8 bytes. // distribute this key to the user who will decrypt this file. string ssecretkey; // get the key for the file to encrypt. ssecretkey = generatekey (); // for additional security pin the key. gchandle gch = gchandle. alloc (ssecretkey, gchandletype. pinned); // encrypt the file. encryptfile (@ "C: \ mydata.txt", @ "C: \ encrypted.txt", ssecretkey); // decrypt the file. decryptfile (@ "C: \ encrypted.txt", @ "C: \ decrypted.txt", ssecretkey); // remove the key from memory. zeromemory (gch. addrofpinnedobject (), ssecretkey. length * 2); gch. free ();}}}
Another example
Using system; using system. security. cryptography; using system. text; using system. io; Class rijndaelsample {static void main () {try {// create a new Rijndael object to generate a key // and initialization vector (IV ). rijndael rijndaelalg = Rijndael. create (); // create a string to encrypt. string sdata = "here is some data to encrypt. "; string filename =" ctext.txt "; // encrypt text to a file using the file name, key, and IV. encrypttexttofile (sdata, filename, rijndaelalg. key, rijndaelalg. IV); // decrypt the text from a file using the file name, key, and IV. string final = decrypttextfromfile (filename, rijndaelalg. key, rijndaelalg. IV); // display the decrypted string to the console. console. writeline (final);} catch (exception e) {console. writeline (E. message);} console. readline ();} public static void encrypttexttofile (string data, string filename, byte [] key, byte [] IV) {try {// create or open the specified file. filestream fstream = file. open (filename, filemode. openorcreate); // create a new Rijndael object. rijndael rijndaelalg = Rijndael. create (); // create a cryptostream using the filestream // and the passed key and initialization vector (IV ). cryptostream cstream = new cryptostream (fstream, rijndaelalg. createencryptor (Key, IV), cryptostreammode. write); // create a streamwriter using the cryptostream. streamwriter swriter = new streamwriter (cstream); try {// write the data to the stream // to encrypt it. swriter. writeline (data);} catch (exception e) {console. writeline ("an error occurred: {0}", E. message);} finally {// close the streams and // close the file. swriter. close (); cstream. close (); fstream. close () ;}} catch (cryptographicexception e) {console. writeline ("A Cryptographic error occurred: {0}", E. message);} catch (unauthorizedaccessexception e) {console. writeline ("A file error occurred: {0}", E. message) ;}} public static string decrypttextfromfile (string filename, byte [] key, byte [] IV) {try {// create or open the specified file. filestream fstream = file. open (filename, filemode. openorcreate); // create a new Rijndael object. rijndael rijndaelalg = Rijndael. create (); // create a cryptostream using the filestream // and the passed key and initialization vector (IV ). cryptostream cstream = new cryptostream (fstream, rijndaelalg. createdecryptor (Key, IV), cryptostreammode. read); // create a streamreader using the cryptostream. streamreader sreader = new streamreader (cstream); string val = NULL; try {// read the data from the stream // to decrypt it. val = sreader. readline ();} catch (exception e) {console. writeline ("an error occurred: {0}", E. message);} finally {// close the streams and // close the file. sreader. close (); cstream. close (); fstream. close ();} // return the string. return val;} catch (cryptographicexception e) {console. writeline ("A Cryptographic error occurred: {0}", E. message); return NULL;} catch (unauthorizedaccessexception e) {console. writeline ("A file error occurred: {0}", E. message); return NULL ;}}}
This
Cryptostream class
Defines a stream that links data streams to cryptographic transformations. cryptosteam class provides links between data streams and encrypted transmission.
About zeromemory
Zeromemory macro
Fills a block of memory with zeros.
To avoid any undesired effects of optimizing compilers, useSecurezeromemoryFunction.
Parameters
-
Destination[In]
-
A pointer to the starting address of the block of memory to fill with zeros.
-
Length[In]
-
The size of the block of memory to fill with zeros, in bytes.
Return Value
This macro has no return value.
Remarks
Extends programming versions include syntax for initializing Complex Variables to zero. There can be differences between the results of these operations andZeromemoryFunction. UseZeromemoryTo clear a block of memory in any programming language.
This macro is defined asRtlzeromemoryMacro. For more information, see WINBASE. h and WinNT. h.