From ff0d6727c544854881b2eb910ee2cf85c7eb7da8 Mon Sep 17 00:00:00 2001 From: Jeremy Barton Date: Fri, 15 Jul 2022 16:14:10 -0700 Subject: [PATCH 1/2] Clean up DES.Create samples --- .../CPP/fileexample.cpp | 234 +++++++++-------- .../CPP/memoryexample.cpp | 243 +++++++++++------- .../DES/Create/fileexample.cs | 127 ++++----- .../DES/Create/fileexample1.cs | 122 --------- .../DES/Create/memoryexample.cs | 134 +++++----- .../DES/Create/memoryexample1.cs | 113 -------- .../VB/fileexample.vb | 112 ++++---- .../VB/memoryexample.vb | 111 ++++---- xml/System.Security.Cryptography/DES.xml | 19 +- 9 files changed, 510 insertions(+), 705 deletions(-) delete mode 100644 snippets/csharp/System.Security.Cryptography/DES/Create/fileexample1.cs delete mode 100644 snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample1.cs diff --git a/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.File/CPP/fileexample.cpp b/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.File/CPP/fileexample.cpp index 7ad7bc9c22f..e48f4e14aa9 100644 --- a/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.File/CPP/fileexample.cpp +++ b/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.File/CPP/fileexample.cpp @@ -1,122 +1,146 @@ - - // -#using - using namespace System; +using namespace System::IO; using namespace System::Security::Cryptography; using namespace System::Text; -using namespace System::IO; -void EncryptTextToFile( String^ Data, String^ FileName, array^Key, array^IV ) + +void EncryptTextToFile(String^ text, String^ path, array^ key, array^ iv); +String^ DecryptTextFromFile(String^ path, array^ key, array^ iv); + +int main() { - try - { - - // Create or open the specified file. - FileStream^ fStream = File::Open( FileName, FileMode::OpenOrCreate ); - - // Create a new DES object. - DES^ DESalg = DES::Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( fStream,DESalg->CreateEncryptor( Key, IV ),CryptoStreamMode::Write ); - - // Create a StreamWriter using the CryptoStream. - StreamWriter^ sWriter = gcnew StreamWriter( cStream ); - - // Write the data to the stream - // to encrypt it. - sWriter->WriteLine( Data ); - - // 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 ); - } + try + { + array^ key; + array^ iv; + + // Create a new DES object to generate a random key + // and initialization vector (IV). + { + DES^ des; + + try + { + des = DES::Create(); + key = des->Key; + iv = des->IV; + } + finally + { + delete des; + } + } + + // Create a string to encrypt. + String^ original = "Here is some data to encrypt."; + // The name/path of the file to write. + String^ filename = "CText.enc"; + // Encrypt the string to a file. + EncryptTextToFile(original, filename, key, iv); + + // Decrypt the file back to a string. + String^ decrypted = DecryptTextFromFile(filename, key, iv); + + // Display the decrypted string to the console. + Console::WriteLine(decrypted); + } + catch (Exception^ e) + { + Console::WriteLine(e->Message); + } } -String^ DecryptTextFromFile( String^ FileName, array^Key, array^IV ) +void EncryptTextToFile(String^ text, String^ path, array^ key, array^ iv) { - try - { - - // Create or open the specified file. - FileStream^ fStream = File::Open( FileName, FileMode::OpenOrCreate ); - - // Create a new DES object. - DES^ DESalg = DES::Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( fStream,DESalg->CreateDecryptor( Key, IV ),CryptoStreamMode::Read ); - - // Create a StreamReader using the CryptoStream. - StreamReader^ sReader = gcnew StreamReader( cStream ); - - // Read the data from the stream - // to decrypt it. - String^ val = sReader->ReadLine(); - - // 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 nullptr; - } - catch ( UnauthorizedAccessException^ e ) - { - Console::WriteLine( "A file error occurred: {0}", e->Message ); - return nullptr; - } + FileStream^ fStream = nullptr; + DES^ des = nullptr; + ICryptoTransform^ encryptor = nullptr; + CryptoStream^ cStream = nullptr; + + try + { + // Create or open the specified file. + fStream = File::Open(path, FileMode::Create); + // Create a new DES object. + des = DES::Create(); + // Create a DES encryptor from the key and IV + encryptor = des->CreateEncryptor(key, iv); + // Create a CryptoStream using the FileStream and encryptor + cStream = gcnew CryptoStream(fStream, encryptor, CryptoStreamMode::Write); + + // Convert the provided string to a byte array. + array^ toEncrypt = Encoding::UTF8->GetBytes(text); + + // Write the byte array to the crypto stream. + cStream->Write(toEncrypt, 0, toEncrypt->Length); + } + catch (CryptographicException^ e) + { + Console::WriteLine("A Cryptographic error occurred: {0}", e->Message); + throw; + } + finally + { + if (cStream != nullptr) + delete cStream; + + if (encryptor != nullptr) + delete encryptor; + + if (des != nullptr) + delete des; + if (fStream != nullptr) + delete fStream; + } } -int main() +String^ DecryptTextFromFile(String^ path, array^ key, array^ iv) { - try - { - - // Create a new DES object to generate a key - // and initialization vector (IV). - DES^ DESalg = DES::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, DESalg->Key, DESalg->IV ); - - // Decrypt the text from a file using the file name, key, and IV. - String^ Final = DecryptTextFromFile( FileName, DESalg->Key, DESalg->IV ); - - // Display the decrypted string to the console. - Console::WriteLine( Final ); - } - catch ( Exception^ e ) - { - Console::WriteLine( e->Message ); - } + FileStream^ fStream = nullptr; + DES^ des = nullptr; + ICryptoTransform^ decryptor = nullptr; + CryptoStream^ cStream = nullptr; + StreamReader^ reader = nullptr; + + try + { + // Open the specified file + fStream = File::OpenRead(path); + // Create a new DES object. + des = DES::Create(); + // Create a DES decryptor from the key and IV + decryptor = des->CreateDecryptor(key, iv); + // Create a CryptoStream using the FileStream and decryptor + cStream = gcnew CryptoStream(fStream, decryptor, CryptoStreamMode::Read); + // Create a StreamReader to turn the bytes back into text + reader = gcnew StreamReader(cStream, Encoding::UTF8); + + // Read back all of the text from the StreamReader, which receives + // the decrypted bytes from the CryptoStream, which receives the + // encrypted bytes from the FileStream. + return reader->ReadToEnd(); + } + catch (CryptographicException^ e) + { + Console::WriteLine("A Cryptographic error occurred: {0}", e->Message); + throw; + } + finally + { + if (cStream != nullptr) + delete cStream; + + if (decryptor != nullptr) + delete decryptor; + + if (des != nullptr) + delete des; + if (fStream != nullptr) + delete fStream; + } } // diff --git a/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.Memory/CPP/memoryexample.cpp b/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.Memory/CPP/memoryexample.cpp index fe65318f77a..27a8c01000f 100644 --- a/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.Memory/CPP/memoryexample.cpp +++ b/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Create.Memory/CPP/memoryexample.cpp @@ -4,108 +4,167 @@ using namespace System; using namespace System::Security::Cryptography; using namespace System::Text; using namespace System::IO; -array^ EncryptTextToMemory( String^ Data, array^Key, array^IV ) + +array^ EncryptTextToMemory(String^ text, array^ key, array^ iv); +String^ DecryptTextFromMemory(array^ encrypted, array^ key, array^ iv); + +int main() { - try - { - - // Create a MemoryStream. - MemoryStream^ mStream = gcnew MemoryStream; - - // Create a new DES object. - DES^ DESalg = DES::Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( mStream,DESalg->CreateEncryptor( Key, IV ),CryptoStreamMode::Write ); - - // Convert the passed string to a byte array. - array^toEncrypt = (gcnew ASCIIEncoding)->GetBytes( Data ); - - // Write the byte array to the crypto stream and flush it. - cStream->Write( toEncrypt, 0, toEncrypt->Length ); - cStream->FlushFinalBlock(); - - // Get an array of bytes from the - // MemoryStream that holds the - // encrypted data. - array^ret = mStream->ToArray(); - - // Close the streams. - cStream->Close(); - mStream->Close(); - - // Return the encrypted buffer. - return ret; - } - catch ( CryptographicException^ e ) - { - Console::WriteLine( "A Cryptographic error occurred: {0}", e->Message ); - return nullptr; - } + try + { + array^ key; + array^ iv; + + // Create a new DES object to generate a random key + // and initialization vector (IV). + { + DES^ des; + + try + { + des = DES::Create(); + key = des->Key; + iv = des->IV; + } + finally + { + delete des; + } + } + + // Create a string to encrypt. + String^ original = "Here is some data to encrypt."; + // Encrypt the string to an in-memory buffer. + array^ encrypted = EncryptTextToMemory(original, key, iv); + + // Decrypt the buffer back to a string. + String^ decrypted = DecryptTextFromMemory(encrypted, key, iv); + + // Display the decrypted string to the console. + Console::WriteLine(decrypted); + } + catch (Exception^ e) + { + Console::WriteLine(e->Message); + } } -String^ DecryptTextFromMemory( array^Data, array^Key, array^IV ) +array^ EncryptTextToMemory(String^ text, array^ key, array^ iv) { - try - { - - // Create a new MemoryStream using the passed - // array of encrypted data. - MemoryStream^ msDecrypt = gcnew MemoryStream( Data ); - - // Create a new DES object. - DES^ DESalg = DES::Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream^ csDecrypt = gcnew CryptoStream( msDecrypt,DESalg->CreateDecryptor( Key, IV ),CryptoStreamMode::Read ); - - // Create buffer to hold the decrypted data. - array^fromEncrypt = gcnew array(Data->Length); - - // Read the decrypted data out of the crypto stream - // and place it into the temporary buffer. - csDecrypt->Read( fromEncrypt, 0, fromEncrypt->Length ); - - //Convert the buffer into a string and return it. - return (gcnew ASCIIEncoding)->GetString( fromEncrypt ); - } - catch ( CryptographicException^ e ) - { - Console::WriteLine( "A Cryptographic error occurred: {0}", e->Message ); - return nullptr; - } + MemoryStream^ mStream = nullptr; + + try + { + // Create a MemoryStream. + mStream = gcnew MemoryStream; + + DES^ des = nullptr; + ICryptoTransform^ encryptor = nullptr; + CryptoStream^ cStream = nullptr; + + try + { + // Create a new DES object. + des = DES::Create(); + // Create a DES encryptor from the key and IV + encryptor = des->CreateEncryptor(key, iv); + // Create a CryptoStream using the MemoryStream and encryptor + cStream = gcnew CryptoStream(mStream, encryptor, CryptoStreamMode::Write); + + // Convert the provided string to a byte array. + array^ toEncrypt = Encoding::UTF8->GetBytes(text); + + // Write the byte array to the crypto stream. + cStream->Write(toEncrypt, 0, toEncrypt->Length); + // Disposing the CryptoStream completes the encryption and flushes the stream. + delete cStream; + + // Get an array of bytes from the MemoryStream that holds the encrypted data. + array^ ret = mStream->ToArray(); + + // Return the encrypted buffer. + return ret; + } + finally + { + if (cStream != nullptr) + delete cStream; + + if (encryptor != nullptr) + delete encryptor; + + if (des != nullptr) + delete des; + } + } + catch (CryptographicException^ e) + { + Console::WriteLine("A Cryptographic error occurred: {0}", e->Message); + throw; + } + finally + { + if (mStream != nullptr) + delete mStream; + } } -int main() +String^ DecryptTextFromMemory(array^ encrypted, array^ key, array^ iv) { - try - { - - // Create a new DES object to generate a key - // and initialization vector (IV). - DES^ DESalg = DES::Create(); - - // Create a string to encrypt. - String^ sData = "Here is some data to encrypt."; - - // Encrypt the string to an in-memory buffer. - array^Data = EncryptTextToMemory( sData, DESalg->Key, DESalg->IV ); - - // Decrypt the buffer back to a string. - String^ Final = DecryptTextFromMemory( Data, DESalg->Key, DESalg->IV ); - - // Display the decrypted string to the console. - Console::WriteLine( Final ); - } - catch ( Exception^ e ) - { - Console::WriteLine( e->Message ); - } + MemoryStream^ mStream = nullptr; + DES^ des = nullptr; + ICryptoTransform^ decryptor = nullptr; + CryptoStream^ cStream = nullptr; + + try + { + // Create buffer to hold the decrypted data. + // DES-encrypted data will always be slightly bigger than the decrypted data. + array^ decrypted = gcnew array(encrypted->Length); + Int32 offset = 0; + + // Create a new MemoryStream using the provided array of encrypted data. + mStream = gcnew MemoryStream(encrypted); + // Create a new DES object. + des = DES::Create(); + // Create a DES decryptor from the key and IV + decryptor = des->CreateDecryptor(key, iv); + // Create a CryptoStream using the MemoryStream and decryptor + cStream = gcnew CryptoStream(mStream, decryptor, CryptoStreamMode::Read); + + // Keep reading from the CryptoStream until it finishes (returns 0). + Int32 read = 1; + + while (read > 0) + { + read = cStream->Read(decrypted, offset, decrypted->Length - offset); + offset += read; + } + + // Convert the buffer into a string and return it. + return Encoding::UTF8->GetString(decrypted, 0, offset); + } + catch (CryptographicException^ e) + { + Console::WriteLine("A Cryptographic error occurred: {0}", e->Message); + throw; + } + finally + { + if (cStream != nullptr) + delete cStream; + + if (decryptor != nullptr) + delete decryptor; + + if (des != nullptr) + delete des; + if (mStream != nullptr) + delete mStream; + } } // diff --git a/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample.cs b/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample.cs index f214b1a3a45..63f30a3a7a0 100644 --- a/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample.cs +++ b/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample.cs @@ -1,32 +1,39 @@ // using System; +using System.IO; using System.Security.Cryptography; using System.Text; -using System.IO; class DESSample { - static void Main() { try { - // Create a new DES object to generate a key + byte[] key; + byte[] iv; + + // Create a new DES object to generate a random key // and initialization vector (IV). - DES DESalg = DES.Create(); + using (DES des = DES.Create()) + { + key = des.Key; + iv = des.IV; + } // Create a string to encrypt. - string sData = "Here is some data to encrypt."; - string FileName = "CText.txt"; + string original = "Here is some data to encrypt."; + // The name/path of the file to write. + string filename = "CText.enc"; - // Encrypt text to a file using the file name, key, and IV. - EncryptTextToFile(sData, FileName, DESalg.Key, DESalg.IV); + // Encrypt the string to a file. + EncryptTextToFile(original, filename, key, iv); - // Decrypt the text from a file using the file name, key, and IV. - string Final = DecryptTextFromFile(FileName, DESalg.Key, DESalg.IV); + // Decrypt the file back to a string. + string decrypted = DecryptTextFromFile(filename, key, iv); // Display the decrypted string to the console. - Console.WriteLine(Final); + Console.WriteLine(decrypted); } catch (Exception e) { @@ -34,87 +41,59 @@ static void Main() } } - public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV) + public static void EncryptTextToFile(string text, string path, byte[] key, byte[] iv) { try { // Create or open the specified file. - FileStream fStream = File.Open(FileName,FileMode.OpenOrCreate); - + using (FileStream fStream = File.Open(path, FileMode.Create)) // Create a new DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - DESalg.CreateEncryptor(Key,IV), - CryptoStreamMode.Write); - - // Create a StreamWriter using the CryptoStream. - StreamWriter sWriter = new StreamWriter(cStream); - - // Write the data to the stream - // to encrypt it. - sWriter.WriteLine(Data); - - // Close the streams and - // close the file. - sWriter.Close(); - cStream.Close(); - fStream.Close(); + using (DES des = DES.Create()) + // Create a DES encryptor from the key and IV + using (ICryptoTransform encryptor = des.CreateEncryptor(key, iv)) + // Create a CryptoStream using the FileStream and encryptor + using (var cStream = new CryptoStream(fStream, encryptor, CryptoStreamMode.Write)) + { + // Convert the provided string to a byte array. + byte[] toEncrypt = Encoding.UTF8.GetBytes(text); + + // Write the byte array to the crypto stream. + cStream.Write(toEncrypt, 0, toEncrypt.Length); + } } - catch(CryptographicException e) + catch (CryptographicException e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); - } - catch(UnauthorizedAccessException e) - { - Console.WriteLine("A file error occurred: {0}", e.Message); + throw; } } - public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV) + public static string DecryptTextFromFile(string path, byte[] key, byte[] iv) { try { - // Create or open the specified file. - FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate); - + // Open the specified file + using (FileStream fStream = File.OpenRead(path)) // Create a new DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - DESalg.CreateDecryptor(Key,IV), - CryptoStreamMode.Read); - - // Create a StreamReader using the CryptoStream. - StreamReader sReader = new StreamReader(cStream); - - // Read the data from the stream - // to decrypt it. - string val = sReader.ReadLine(); - - // Close the streams and - // close the file. - sReader.Close(); - cStream.Close(); - fStream.Close(); - - // Return the string. - return val; + using (DES des = DES.Create()) + // Create a DES decryptor from the key and IV + using (ICryptoTransform decryptor = des.CreateDecryptor(key, iv)) + // Create a CryptoStream using the FileStream and decryptor + using (var cStream = new CryptoStream(fStream, decryptor, CryptoStreamMode.Read)) + // Create a StreamReader to turn the bytes back into text + using (StreamReader reader = new StreamReader(cStream, Encoding.UTF8)) + { + // Read back all of the text from the StreamReader, which receives + // the decrypted bytes from the CryptoStream, which receives the + // encrypted bytes from the FileStream. + return reader.ReadToEnd(); + } } - catch(CryptographicException e) + 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; + throw; } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample1.cs b/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample1.cs deleted file mode 100644 index daa022ee821..00000000000 --- a/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample1.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -using System; -using System.Security.Cryptography; -using System.Text; -using System.IO; - -class DESSample -{ - - static void Main() - { - try - { - // Create a new DES object to generate a key - // and initialization vector (IV). Specify one - // of the recognized simple names for this - // algorithm. - DES DESalg = DES.Create("DES"); - - // 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, DESalg.Key, DESalg.IV); - - // Decrypt the text from a file using the file name, key, and IV. - string Final = DecryptTextFromFile(FileName, DESalg.Key, DESalg.IV); - - // Display the decrypted string to the console. - Console.WriteLine(Final); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - } - - 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 DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - DESalg.CreateEncryptor(Key,IV), - CryptoStreamMode.Write); - - // Create a StreamWriter using the CryptoStream. - StreamWriter sWriter = new StreamWriter(cStream); - - // Write the data to the stream - // to encrypt it. - sWriter.WriteLine(Data); - - // 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 DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - DESalg.CreateDecryptor(Key,IV), - CryptoStreamMode.Read); - - // Create a StreamReader using the CryptoStream. - StreamReader sReader = new StreamReader(cStream); - - // Read the data from the stream - // to decrypt it. - string val = sReader.ReadLine(); - - // 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; - } - } -} -// \ No newline at end of file diff --git a/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs b/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs index e9912f47845..53a4bdd7418 100644 --- a/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs +++ b/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs @@ -10,21 +10,28 @@ static void Main() { try { - // Create a new DES object to generate a key + byte[] key; + byte[] iv; + + // Create a new DES object to generate a random key // and initialization vector (IV). - DES DESalg = DES.Create(); + using (DES des = DES.Create()) + { + key = des.Key; + iv = des.IV; + } // Create a string to encrypt. - string sData = "Here is some data to encrypt."; + string original = "Here is some data to encrypt."; // Encrypt the string to an in-memory buffer. - byte[] Data = EncryptTextToMemory(sData, DESalg.Key, DESalg.IV); + byte[] encrypted = EncryptTextToMemory(original, key, iv); // Decrypt the buffer back to a string. - string Final = DecryptTextFromMemory(Data, DESalg.Key, DESalg.IV); + string decrypted = DecryptTextFromMemory(encrypted, key, iv); // Display the decrypted string to the console. - Console.WriteLine(Final); + Console.WriteLine(decrypted); } catch (Exception e) { @@ -32,79 +39,80 @@ static void Main() } } - public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV) + public static byte[] EncryptTextToMemory(string text, byte[] key, byte[] iv) { try { // Create a MemoryStream. - MemoryStream mStream = new MemoryStream(); - - // Create a new DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(mStream, - DESalg.CreateEncryptor(Key, IV), - CryptoStreamMode.Write); - - // Convert the passed string to a byte array. - byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data); - - // Write the byte array to the crypto stream and flush it. - cStream.Write(toEncrypt, 0, toEncrypt.Length); - cStream.FlushFinalBlock(); - - // Get an array of bytes from the - // MemoryStream that holds the - // encrypted data. - byte[] ret = mStream.ToArray(); - - // Close the streams. - cStream.Close(); - mStream.Close(); - - // Return the encrypted buffer. - return ret; + using (MemoryStream mStream = new MemoryStream()) + { + // Create a new DES object. + using (DES des = DES.Create()) + // Create a DES encryptor from the key and IV + using (ICryptoTransform encryptor = des.CreateEncryptor(key, iv)) + // Create a CryptoStream using the MemoryStream and encryptor + using (var cStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write)) + { + // Convert the provided string to a byte array. + byte[] toEncrypt = Encoding.UTF8.GetBytes(text); + + // Write the byte array to the crypto stream and flush it. + cStream.Write(toEncrypt, 0, toEncrypt.Length); + + // Ending the using statement for the CryptoStream completes the encryption. + } + + // Get an array of bytes from the MemoryStream that holds the encrypted data. + byte[] ret = mStream.ToArray(); + + // Return the encrypted buffer. + return ret; + } } - catch(CryptographicException e) + catch (CryptographicException e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); - return null; + throw; } } - public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV) + public static string DecryptTextFromMemory(byte[] encrypted, byte[] key, byte[] iv) { try { - // Create a new MemoryStream using the passed - // array of encrypted data. - MemoryStream msDecrypt = new MemoryStream(Data); - - // Create a new DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream csDecrypt = new CryptoStream(msDecrypt, - DESalg.CreateDecryptor(Key, IV), - CryptoStreamMode.Read); - - // Create buffer to hold the decrypted data. - byte[] fromEncrypt = new byte[Data.Length]; - - // Read the decrypted data out of the crypto stream - // and place it into the temporary buffer. - csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); - - //Convert the buffer into a string and return it. - return new ASCIIEncoding().GetString(fromEncrypt); + // Create a buffer to hold the decrypted data. + // DES-encrypted data will always be slightly bigger than the decrypted data. + byte[] decrypted = new byte[encrypted.Length]; + int offset = 0; + + // Create a new MemoryStream using the provided array of encrypted data. + using (MemoryStream mStream = new MemoryStream(encrypted)) + { + // Create a new DES object. + using (DES des = DES.Create()) + // Create a DES decryptor from the key and IV + using (ICryptoTransform decryptor = des.CreateDecryptor(key, iv)) + // Create a CryptoStream using the MemoryStream and decryptor + using (var cStream = new CryptoStream(mStream, decryptor, CryptoStreamMode.Read)) + { + // Keep reading from the CryptoStream until it finishes (returns 0). + int read = 1; + + while (read > 0) + { + read = cStream.Read(decrypted, offset, decrypted.Length - offset); + offset += read; + } + } + } + + // Convert the buffer into a string and return it. + return Encoding.UTF8.GetString(decrypted, 0, offset); } - catch(CryptographicException e) + catch (CryptographicException e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); - return null; + throw; } } } diff --git a/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample1.cs b/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample1.cs deleted file mode 100644 index df74c9e5ccb..00000000000 --- a/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample1.cs +++ /dev/null @@ -1,113 +0,0 @@ -// -using System; -using System.Security.Cryptography; -using System.Text; -using System.IO; - -class DESSample -{ - static void Main() - { - try - { - // Create a new DES object to generate a key - // and initialization vector (IV). Specify one - // of the recognized simple names for this - // algorithm. - DES DESalg = DES.Create("DES"); - - // Create a string to encrypt. - string sData = "Here is some data to encrypt."; - - // Encrypt the string to an in-memory buffer. - byte[] Data = EncryptTextToMemory(sData, DESalg.Key, DESalg.IV); - - // Decrypt the buffer back to a string. - string Final = DecryptTextFromMemory(Data, DESalg.Key, DESalg.IV); - - // Display the decrypted string to the console. - Console.WriteLine(Final); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - } - - public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV) - { - try - { - // Create a MemoryStream. - MemoryStream mStream = new MemoryStream(); - - // Create a new DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(mStream, - DESalg.CreateEncryptor(Key, IV), - CryptoStreamMode.Write); - - // Convert the passed string to a byte array. - byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data); - - // Write the byte array to the crypto stream and flush it. - cStream.Write(toEncrypt, 0, toEncrypt.Length); - cStream.FlushFinalBlock(); - - // Get an array of bytes from the - // MemoryStream that holds the - // encrypted data. - byte[] ret = mStream.ToArray(); - - // Close the streams. - cStream.Close(); - mStream.Close(); - - // Return the encrypted buffer. - return ret; - } - catch(CryptographicException e) - { - Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); - return null; - } - } - - public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV) - { - try - { - // Create a new MemoryStream using the passed - // array of encrypted data. - MemoryStream msDecrypt = new MemoryStream(Data); - - // Create a new DES object. - DES DESalg = DES.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream csDecrypt = new CryptoStream(msDecrypt, - DESalg.CreateDecryptor(Key, IV), - CryptoStreamMode.Read); - - // Create buffer to hold the decrypted data. - byte[] fromEncrypt = new byte[Data.Length]; - - // Read the decrypted data out of the crypto stream - // and place it into the temporary buffer. - csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); - - //Convert the buffer into a string and return it. - return new ASCIIEncoding().GetString(fromEncrypt); - } - catch(CryptographicException e) - { - Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); - return null; - } - } -} -// diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/fileexample.vb b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/fileexample.vb index 55daef57865..e1446d2a3ae 100644 --- a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/fileexample.vb +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/fileexample.vb @@ -1,104 +1,88 @@ - ' +' +Imports System.IO Imports System.Security.Cryptography Imports System.Text -Imports System.IO Module DESSample Sub Main() Try + Dim key As Byte() + Dim iv As Byte() + ' Create a new DES object to generate a key ' and initialization vector (IV). - Dim DESalg As DES = DES.Create + Using des As DES = DES.Create + key = des.Key + iv = des.IV + End Using ' Create a string to encrypt. - Dim sData As String = "Here is some data to encrypt." - Dim FileName As String = "CText.txt" + Dim original As String = "Here is some data to encrypt." + ' The name/path of the file to write. + Dim filename As String = "CText.enc" - ' Encrypt text to a file using the file name, key, and IV. - EncryptTextToFile(sData, FileName, DESalg.Key, DESalg.IV) + ' Encrypt the string to a file. + EncryptTextToFile(original, filename, key, iv) - ' Decrypt the text from a file using the file name, key, and IV. - Dim Final As String = DecryptTextFromFile(FileName, DESalg.Key, DESalg.IV) + ' Decrypt the file back to a string. + Dim decrypted As String = DecryptTextFromFile(filename, key, iv) ' Display the decrypted string to the console. - Console.WriteLine(Final) + Console.WriteLine(decrypted) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub - Sub EncryptTextToFile(ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) + Sub EncryptTextToFile(text As String, path As String, key As Byte(), iv As Byte()) Try ' Create or open the specified file. - Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate) + ' Create a new DES object, + ' Create a DES encryptor from the key and IV, + ' Create a CryptoStream using the MemoryStream And encryptor + Using fStream As FileStream = File.Open(path, FileMode.Create), + des As DES = DES.Create, + encryptor As ICryptoTransform = des.CreateEncryptor(key, iv), + cStream = New CryptoStream(fStream, encryptor, CryptoStreamMode.Write) - ' Create a new DES object. - Dim DESalg As DES = DES.Create + ' Convert the passed string to a byte array. + Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text) - ' Create a CryptoStream using the FileStream - ' and the passed key and initialization vector (IV). - Dim cStream As New CryptoStream(fStream, _ - DESalg.CreateEncryptor(Key, IV), _ - CryptoStreamMode.Write) + ' Write the byte array to the crypto stream. + cStream.Write(toEncrypt, 0, toEncrypt.Length) + End Using - ' Create a StreamWriter using the CryptoStream. - Dim sWriter As New StreamWriter(cStream) - - ' Write the data to the stream - ' to encrypt it. - sWriter.WriteLine(Data) - - ' Close the streams and - ' close the file. - sWriter.Close() - cStream.Close() - fStream.Close() Catch e As CryptographicException Console.WriteLine("A Cryptographic error occurred: {0}", e.Message) - Catch e As UnauthorizedAccessException - Console.WriteLine("A file error occurred: {0}", e.Message) + Throw End Try End Sub - Function DecryptTextFromFile(ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) As String + Function DecryptTextFromFile(path As String, key As Byte(), iv As Byte()) As String Try - ' Create or open the specified file. - Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate) - + ' Open the specified file ' Create a new DES object. - Dim DESalg As DES = DES.Create - - ' Create a CryptoStream using the FileStream - ' and the passed key and initialization vector (IV). - Dim cStream As New CryptoStream(fStream, _ - DESalg.CreateDecryptor(Key, IV), _ - CryptoStreamMode.Read) - - ' Create a StreamReader using the CryptoStream. - Dim sReader As New StreamReader(cStream) - - ' Read the data from the stream - ' to decrypt it. - Dim val As String = sReader.ReadLine() - - ' Close the streams and - ' close the file. - sReader.Close() - cStream.Close() - fStream.Close() - - ' Return the string. - Return val + ' Create a DES decryptor from the key and IV + ' Create a CryptoStream using the MemoryStream and decryptor + ' Create a StreamReader to turn the bytes back into text + Using mStream As FileStream = File.OpenRead(path), + des As DES = DES.Create, + decryptor As ICryptoTransform = des.CreateDecryptor(key, iv), + cStream = New CryptoStream(mStream, decryptor, CryptoStreamMode.Read), + reader = New StreamReader(cStream, Encoding.UTF8) + + ' Read back all of the text from the StreamReader, which receives + ' the decrypted bytes from the CryptoStream, which receives the + ' encrypted bytes from the FileStream. + Return reader.ReadToEnd() + End Using Catch e As CryptographicException Console.WriteLine("A Cryptographic error occurred: {0}", e.Message) Return Nothing - Catch e As UnauthorizedAccessException - Console.WriteLine("A file error occurred: {0}", e.Message) - Return Nothing End Try End Function End Module - ' \ No newline at end of file +' diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/VB/memoryexample.vb b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/VB/memoryexample.vb index 2ef2338bd4f..b59d10d576e 100644 --- a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/VB/memoryexample.vb +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/VB/memoryexample.vb @@ -7,94 +7,97 @@ Module DESSample Sub Main() Try + Dim key As Byte() + Dim iv As Byte() + ' Create a new DES object to generate a key ' and initialization vector (IV). - Dim DESalg As DES = DES.Create + Using des As DES = DES.Create + key = des.Key + iv = des.IV + End Using ' Create a string to encrypt. - Dim sData As String = "Here is some data to encrypt." + Dim original As String = "Here is some data to encrypt." ' Encrypt the string to an in-memory buffer. - Dim Data As Byte() = EncryptTextToMemory(sData, DESalg.Key, DESalg.IV) + Dim encrypted As Byte() = EncryptTextToMemory(original, key, iv) ' Decrypt the buffer back to a string. - Dim Final As String = DecryptTextFromMemory(Data, DESalg.Key, DESalg.IV) + Dim decrypted As String = DecryptTextFromMemory(encrypted, key, iv) ' Display the decrypted string to the console. - Console.WriteLine(Final) + Console.WriteLine(decrypted) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub - Function EncryptTextToMemory(ByVal Data As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte() + Function EncryptTextToMemory(text As String, key As Byte(), iv As Byte()) As Byte() Try ' Create a MemoryStream. - Dim mStream As New MemoryStream - - ' Create a new DES object. - Dim DESalg As DES = DES.Create + Using mStream As New MemoryStream + ' Create a new DES object, + ' Create a DES encryptor from the key and IV, + ' Create a CryptoStream using the MemoryStream And encryptor + Using des As DES = DES.Create, + encryptor As ICryptoTransform = des.CreateEncryptor(key, iv), + cStream = New CryptoStream(mStream, encryptor, CryptoStreamMode.Write) - ' Create a CryptoStream using the MemoryStream - ' and the passed key and initialization vector (IV). - Dim cStream As New CryptoStream(mStream, _ - DESalg.CreateEncryptor(Key, IV), _ - CryptoStreamMode.Write) + ' Convert the passed string to a byte array. + Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text) - ' Convert the passed string to a byte array. - Dim toEncrypt As Byte() = New ASCIIEncoding().GetBytes(Data) + ' Write the byte array to the crypto stream and flush it. + cStream.Write(toEncrypt, 0, toEncrypt.Length) - ' Write the byte array to the crypto stream and flush it. - cStream.Write(toEncrypt, 0, toEncrypt.Length) - cStream.FlushFinalBlock() + ' Ending the using block for the CryptoStream completes the encryption. + End Using - ' Get an array of bytes from the - ' MemoryStream that holds the - ' encrypted data. - Dim ret As Byte() = mStream.ToArray() + ' Get an array of bytes from the MemoryStream that holds the encrypted data. + Dim ret As Byte() = mStream.ToArray() - ' Close the streams. - cStream.Close() - mStream.Close() - - ' Return the encrypted buffer. - Return ret + ' Return the encrypted buffer. + Return ret + End Using Catch e As CryptographicException Console.WriteLine("A Cryptographic error occurred: {0}", e.Message) - Return Nothing + Throw End Try End Function - Function DecryptTextFromMemory(ByVal Data() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String + Function DecryptTextFromMemory(encrypted As Byte(), key As Byte(), iv As Byte()) As String Try - ' Create a new MemoryStream using the passed - ' array of encrypted data. - Dim msDecrypt As New MemoryStream(Data) + ' Create a buffer to hold the decrypted data. + ' DES-encrypted data will always be slightly bigger than the decrypted data. + Dim decrypted(encrypted.Length - 1) As Byte + Dim offset As Integer = 0 + ' Create a new MemoryStream using the provided array of encrypted data. ' Create a new DES object. - Dim DESalg As DES = DES.Create - - ' Create a CryptoStream using the MemoryStream - ' and the passed key and initialization vector (IV). - Dim csDecrypt As New CryptoStream(msDecrypt, _ - DESalg.CreateDecryptor(Key, IV), _ - CryptoStreamMode.Read) - - ' Create buffer to hold the decrypted data. - Dim fromEncrypt(Data.Length - 1) As Byte - - ' Read the decrypted data out of the crypto stream - ' and place it into the temporary buffer. - csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length) - - 'Convert the buffer into a string and return it. - Return New ASCIIEncoding().GetString(fromEncrypt) + ' Create a DES decryptor from the key and IV + ' Create a CryptoStream using the MemoryStream and decryptor + Using mStream As New MemoryStream(encrypted), + des As DES = DES.Create, + decryptor As ICryptoTransform = des.CreateDecryptor(key, iv), + cStream = New CryptoStream(mStream, decryptor, CryptoStreamMode.Read) + + ' Keep reading from the CryptoStream until it finishes (returns 0). + Dim read As Integer = 1 + + While (read > 0) + read = cStream.Read(decrypted, offset, decrypted.Length - offset) + offset += read + End While + End Using + + ' Convert the buffer into a string and return it. + Return New ASCIIEncoding().GetString(decrypted, 0, offset) Catch e As CryptographicException Console.WriteLine("A Cryptographic error occurred: {0}", e.Message) Return Nothing End Try End Function -End Module - ' \ No newline at end of file +End Module + ' diff --git a/xml/System.Security.Cryptography/DES.xml b/xml/System.Security.Cryptography/DES.xml index b2417692655..97ec1fa0c62 100644 --- a/xml/System.Security.Cryptography/DES.xml +++ b/xml/System.Security.Cryptography/DES.xml @@ -264,24 +264,7 @@ The name of the specific implementation of to use. Creates an instance of a cryptographic object to perform the specified implementation of the Data Encryption Standard () algorithm. A cryptographic object. - - object to encrypt and decrypt data in a file. - - :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Createstring.File/CPP/fileexample.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/DES/Create/fileexample1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Createstring.File/VB/fileexample.vb" id="Snippet1"::: - - The following code example shows how to create and use a object to encrypt and decrypt data in memory. - - :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/Cryptography.DES.Createstring.Memory/CPP/memoryexample.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Createstring.Memory/VB/memoryexample.vb" id="Snippet1"::: - - ]]> - + To be added. Cryptographic Services From 7af69c7986e64b885465f1ea59b3d643a1eadd4a Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Thu, 28 Jul 2022 13:42:22 -0700 Subject: [PATCH 2/2] add project files for VB/C# --- .../DES/Create/memoryexample.cs | 2 +- .../DES/Create/project.csproj | 8 ++++++++ .../Cryptography.DES.Create.File/VB/project.csproj | 8 ++++++++ .../Cryptography.DES.Create.Memory/project.csproj | 8 ++++++++ 4 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 snippets/csharp/System.Security.Cryptography/DES/Create/project.csproj create mode 100644 snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/project.csproj create mode 100644 snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/project.csproj diff --git a/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs b/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs index 53a4bdd7418..f96389304dd 100644 --- a/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs +++ b/snippets/csharp/System.Security.Cryptography/DES/Create/memoryexample.cs @@ -4,7 +4,7 @@ using System.Text; using System.IO; -class DESSample +class DESSample2 { static void Main() { diff --git a/snippets/csharp/System.Security.Cryptography/DES/Create/project.csproj b/snippets/csharp/System.Security.Cryptography/DES/Create/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/csharp/System.Security.Cryptography/DES/Create/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/project.csproj b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.File/VB/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/project.csproj b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.DES.Create.Memory/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + +