diff --git a/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.File/CPP/fileexample.cpp b/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.File/CPP/fileexample.cpp index b690b82bd2c..99c669d9f27 100644 --- a/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.File/CPP/fileexample.cpp +++ b/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.File/CPP/fileexample.cpp @@ -1,119 +1,146 @@ - // 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 TripleDES object. - TripleDES^ tripleDESalg = TripleDES::Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( fStream,tripleDESalg->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 access error occurred: {0}", e->Message ); - } + try + { + array^ key; + array^ iv; + + // Create a new TripleDES object to generate a random key + // and initialization vector (IV). + { + TripleDES^ tripleDes; + + try + { + tripleDes = TripleDES::Create(); + key = tripleDes->Key; + iv = tripleDes->IV; + } + finally + { + delete tripleDes; + } + } + + // 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 TripleDES object. - TripleDES^ tripleDESalg = TripleDES::Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( fStream,tripleDESalg->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 access error occurred: {0}", e->Message ); - return nullptr; - } + FileStream^ fStream = nullptr; + TripleDES^ tripleDes = nullptr; + ICryptoTransform^ encryptor = nullptr; + CryptoStream^ cStream = nullptr; + try + { + // Create or open the specified file. + fStream = File::Open(path, FileMode::Create); + // Create a new TripleDES object. + tripleDes = TripleDES::Create(); + // Create a TripleDES encryptor from the key and IV + encryptor = tripleDes->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 (tripleDes != nullptr) + delete tripleDes; + + if (fStream != nullptr) + delete fStream; + } } -int main() +String^ DecryptTextFromFile(String^ path, array^ key, array^ iv) { - try - { - - // Create a new TripleDES object to generate a key - // and an initialization vector (IV). - TripleDES^ TripleDESalg = TripleDES::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, TripleDESalg->Key, TripleDESalg->IV ); - - // Decrypt the text from a file using the file name, key, and IV. - String^ Final = DecryptTextFromFile( FileName, TripleDESalg->Key, TripleDESalg->IV ); - - // Display the decrypted string to the console. - Console::WriteLine( Final ); - } - catch ( Exception^ e ) - { - Console::WriteLine( e->Message ); - } + FileStream^ fStream = nullptr; + TripleDES^ tripleDes = nullptr; + ICryptoTransform^ decryptor = nullptr; + CryptoStream^ cStream = nullptr; + StreamReader^ reader = nullptr; + + try + { + // Open the specified file + fStream = File::OpenRead(path); + // Create a new TripleDES object. + tripleDes = TripleDES::Create(); + // Create a TripleDES decryptor from the key and IV + decryptor = tripleDes->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 (tripleDes != nullptr) + delete tripleDes; + if (fStream != nullptr) + delete fStream; + } } // diff --git a/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/CPP/memoryexample.cpp b/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/CPP/memoryexample.cpp index 3533dbf3675..f1d7dc04657 100644 --- a/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/CPP/memoryexample.cpp +++ b/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/CPP/memoryexample.cpp @@ -1,114 +1,170 @@ - // -#using - 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 TripleDES object. - TripleDES^ tripleDESalg = TripleDES::Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( mStream,tripleDESalg->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 TripleDES object to generate a random key + // and initialization vector (IV). + { + TripleDES^ tripleDes; + + try + { + tripleDes = TripleDES::Create(); + key = tripleDes->Key; + iv = tripleDes->IV; + } + finally + { + delete tripleDes; + } + } + // 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 TripleDES object. - TripleDES^ tripleDESalg = TripleDES::Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream^ csDecrypt = gcnew CryptoStream( msDecrypt,tripleDESalg->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; + + TripleDES^ tripleDes = nullptr; + ICryptoTransform^ encryptor = nullptr; + CryptoStream^ cStream = nullptr; + + try + { + // Create a new TripleDES object. + tripleDes = TripleDES::Create(); + // Create a TripleDES encryptor from the key and IV + encryptor = tripleDes->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 (tripleDes != nullptr) + delete tripleDes; + } + } + 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 TripleDES object to generate a key - // and initialization vector (IV). - TripleDES^ TripleDESalg = TripleDES::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, TripleDESalg->Key, TripleDESalg->IV ); - - // Decrypt the buffer back to a string. - String^ Final = DecryptTextFromMemory( Data, TripleDESalg->Key, TripleDESalg->IV ); - - // Display the decrypted string to the console. - Console::WriteLine( Final ); - } - catch ( Exception^ e ) - { - Console::WriteLine( e->Message ); - } + MemoryStream^ mStream = nullptr; + TripleDES^ tripleDes = nullptr; + ICryptoTransform^ decryptor = nullptr; + CryptoStream^ cStream = nullptr; + + try + { + // Create buffer to hold the decrypted data. + // TripleDES-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 TripleDES object. + tripleDes = TripleDES::Create(); + // Create a TripleDES decryptor from the key and IV + decryptor = tripleDes->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 (tripleDes != nullptr) + delete tripleDes; + if (mStream != nullptr) + delete mStream; + } } // diff --git a/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.Create.File/CPP/fileexample.cpp b/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.Create.File/CPP/fileexample.cpp index e95eaf01d2a..c6753a5be6f 100644 --- a/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.Create.File/CPP/fileexample.cpp +++ b/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.Create.File/CPP/fileexample.cpp @@ -1,119 +1,146 @@ - // 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 RC2 object. - RC2^ RC2alg = RC2::Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( fStream,RC2alg->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 RC2 object to generate a random key + // and initialization vector (IV). + { + RC2^ rc2; + + try + { + rc2 = RC2::Create(); + key = rc2->Key; + iv = rc2->IV; + } + finally + { + delete rc2; + } + } + + // 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 RC2 object. - RC2^ RC2alg = RC2::Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( fStream,RC2alg->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; + RC2^ rc2 = nullptr; + ICryptoTransform^ encryptor = nullptr; + CryptoStream^ cStream = nullptr; + try + { + // Create or open the specified file. + fStream = File::Open(path, FileMode::Create); + // Create a new RC2 object. + rc2 = RC2::Create(); + // Create an RC2 encryptor from the key and IV + encryptor = rc2->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 (rc2 != nullptr) + delete rc2; + + if (fStream != nullptr) + delete fStream; + } } -int main() +String^ DecryptTextFromFile(String^ path, array^ key, array^ iv) { - try - { - - // Create a new RC2 object to generate a key - // and initialization vector (IV). - RC2^ RC2alg = RC2::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, RC2alg->Key, RC2alg->IV ); - - // Decrypt the text from a file using the file name, key, and IV. - String^ Final = DecryptTextFromFile( FileName, RC2alg->Key, RC2alg->IV ); - - // Display the decrypted string to the console. - Console::WriteLine( Final ); - } - catch ( Exception^ e ) - { - Console::WriteLine( e->Message ); - } + FileStream^ fStream = nullptr; + RC2^ rc2 = nullptr; + ICryptoTransform^ decryptor = nullptr; + CryptoStream^ cStream = nullptr; + StreamReader^ reader = nullptr; + + try + { + // Open the specified file + fStream = File::OpenRead(path); + // Create a new RC2 object. + rc2 = RC2::Create(); + // Create an RC2 decryptor from the key and IV + decryptor = rc2->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 (rc2 != nullptr) + delete rc2; + if (fStream != nullptr) + delete fStream; + } } // diff --git a/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/CPP/memoryexample.cpp b/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/CPP/memoryexample.cpp index 94bce29c0d9..3179ea1bfc1 100644 --- a/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/CPP/memoryexample.cpp +++ b/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2.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 RC2 object. - RC2^ RC2alg = RC2::Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream^ cStream = gcnew CryptoStream( mStream,RC2alg->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 RC2 object to generate a random key + // and initialization vector (IV). + { + RC2^ rc2; + + try + { + rc2 = RC2::Create(); + key = rc2->Key; + iv = rc2->IV; + } + finally + { + delete rc2; + } + } + + // 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 RC2 object. - RC2^ RC2alg = RC2::Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream^ csDecrypt = gcnew CryptoStream( msDecrypt,RC2alg->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; + + RC2^ rc2 = nullptr; + ICryptoTransform^ encryptor = nullptr; + CryptoStream^ cStream = nullptr; + + try + { + // Create a new RC2 object. + rc2 = RC2::Create(); + // Create an RC2 encryptor from the key and IV + encryptor = rc2->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 (rc2 != nullptr) + delete rc2; + } + } + 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 RC2 object to generate a key - // and initialization vector (IV). - RC2^ RC2alg = RC2::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, RC2alg->Key, RC2alg->IV ); - - // Decrypt the buffer back to a string. - String^ Final = DecryptTextFromMemory( Data, RC2alg->Key, RC2alg->IV ); - - // Display the decrypted string to the console. - Console::WriteLine( Final ); - } - catch ( Exception^ e ) - { - Console::WriteLine( e->Message ); - } + MemoryStream^ mStream = nullptr; + RC2^ rc2 = nullptr; + ICryptoTransform^ decryptor = nullptr; + CryptoStream^ cStream = nullptr; + + try + { + // Create buffer to hold the decrypted data. + // RC2-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 RC2 object. + rc2 = RC2::Create(); + // Create an RC2 decryptor from the key and IV + decryptor = rc2->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 (rc2 != nullptr) + delete rc2; + if (mStream != nullptr) + delete mStream; + } } // diff --git a/snippets/csharp/System.Security.Cryptography/RC2/Create/fileexample.cs b/snippets/csharp/System.Security.Cryptography/RC2/Create/fileexample.cs index 5d4f6a46ef6..2ce0e304bd7 100644 --- a/snippets/csharp/System.Security.Cryptography/RC2/Create/fileexample.cs +++ b/snippets/csharp/System.Security.Cryptography/RC2/Create/fileexample.cs @@ -1,32 +1,39 @@ // using System; +using System.IO; using System.Security.Cryptography; using System.Text; -using System.IO; class RC2Sample { - static void Main() { try { - // Create a new RC2 object to generate a key + byte[] key; + byte[] iv; + + // Create a new RC2 object to generate a random key // and initialization vector (IV). - RC2 RC2alg = RC2.Create(); + using (RC2 rc2 = RC2.Create()) + { + key = rc2.Key; + iv = rc2.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, RC2alg.Key, RC2alg.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, RC2alg.Key, RC2alg.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - RC2alg.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 (RC2 rc2 = RC2.Create()) + // Create an RC2 encryptor from the key and IV + using (ICryptoTransform encryptor = rc2.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - RC2alg.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 (RC2 rc2 = RC2.Create()) + // Create an RC2 decryptor from the key and IV + using (ICryptoTransform decryptor = rc2.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/RC2/Create/fileexample1.cs b/snippets/csharp/System.Security.Cryptography/RC2/Create/fileexample1.cs deleted file mode 100644 index f6d284cc3f9..00000000000 --- a/snippets/csharp/System.Security.Cryptography/RC2/Create/fileexample1.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -using System; -using System.Security.Cryptography; -using System.Text; -using System.IO; - -class RC2Sample -{ - - static void Main() - { - try - { - // Create a new RC2 object to generate a key - // and initialization vector (IV). Specify one - // of the recognized simple names for this - // algorithm. - RC2 RC2alg = RC2.Create("RC2"); - - // 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, RC2alg.Key, RC2alg.IV); - - // Decrypt the text from a file using the file name, key, and IV. - string Final = DecryptTextFromFile(FileName, RC2alg.Key, RC2alg.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - RC2alg.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - RC2alg.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/RC2/Create/memoryexample.cs b/snippets/csharp/System.Security.Cryptography/RC2/Create/memoryexample.cs index f2fffcf440e..2b8d2725a7a 100644 --- a/snippets/csharp/System.Security.Cryptography/RC2/Create/memoryexample.cs +++ b/snippets/csharp/System.Security.Cryptography/RC2/Create/memoryexample.cs @@ -4,27 +4,34 @@ using System.Text; using System.IO; -class RC2Sample +class RC2Sample2 { static void Main() { try { - // Create a new RC2 object to generate a key + byte[] key; + byte[] iv; + + // Create a new RC2 object to generate a random key // and initialization vector (IV). - RC2 RC2alg = RC2.Create(); + using (RC2 rc2 = RC2.Create()) + { + key = rc2.Key; + iv = rc2.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, RC2alg.Key, RC2alg.IV); + byte[] encrypted = EncryptTextToMemory(original, key, iv); // Decrypt the buffer back to a string. - string Final = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(mStream, - RC2alg.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 RC2 object. + using (RC2 rc2 = RC2.Create()) + // Create an RC2 encryptor from the key and IV + using (ICryptoTransform encryptor = rc2.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream csDecrypt = new CryptoStream(msDecrypt, - RC2alg.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. + // RC2-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 RC2 object. + using (RC2 rc2 = RC2.Create()) + // Create an RC2 decryptor from the key and IV + using (ICryptoTransform decryptor = rc2.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/RC2/Create/memoryexample1.cs b/snippets/csharp/System.Security.Cryptography/RC2/Create/memoryexample1.cs deleted file mode 100644 index 793001b3511..00000000000 --- a/snippets/csharp/System.Security.Cryptography/RC2/Create/memoryexample1.cs +++ /dev/null @@ -1,113 +0,0 @@ -// -using System; -using System.Security.Cryptography; -using System.Text; -using System.IO; - -class RC2Sample -{ - static void Main() - { - try - { - // Create a new RC2 object to generate a key - // and initialization vector (IV). Specify one - // of the recognized simple names for this - // algorithm. - RC2 RC2alg = RC2.Create("RC2"); - - // 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, RC2alg.Key, RC2alg.IV); - - // Decrypt the buffer back to a string. - string Final = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(mStream, - RC2alg.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 RC2 object. - RC2 RC2alg = RC2.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream csDecrypt = new CryptoStream(msDecrypt, - RC2alg.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/csharp/System.Security.Cryptography/RC2/Create/project.csproj b/snippets/csharp/System.Security.Cryptography/RC2/Create/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/csharp/System.Security.Cryptography/RC2/Create/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample.cs b/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample.cs index 9c713aca387..fd7a0d04ec5 100644 --- a/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample.cs +++ b/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample.cs @@ -1,33 +1,39 @@ // using System; +using System.IO; using System.Security.Cryptography; using System.Text; -using System.IO; class TripleDESSample { - static void Main() { try { - // Create a new TripleDES object to generate a key - // and an initialization vector (IV). - using (TripleDES TripleDESalg = TripleDES.Create()) + byte[] key; + byte[] iv; + + // Create a new TripleDES object to generate a random key + // and initialization vector (IV). + using (TripleDES tripleDes = TripleDES.Create()) { - // Create a string to encrypt. - string sData = "Here is some data to encrypt."; - string FileName = "CText.enc"; + key = tripleDes.Key; + iv = tripleDes.IV; + } - // Encrypt text to a file using the file name, key, and IV. - EncryptTextToFile(sData, FileName, TripleDESalg.Key, TripleDESalg.IV); + // 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"; - // Decrypt the text from a file using the file name, key, and IV. - string Final = DecryptTextFromFile(FileName, TripleDESalg.Key, TripleDESalg.IV); + // Encrypt the string to a file. + EncryptTextToFile(original, filename, key, iv); - // Display the decrypted string to the console. - Console.WriteLine(Final); - } + // 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) { @@ -35,90 +41,58 @@ 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. - using (FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate)) + using (FileStream fStream = File.Open(path, FileMode.Create)) + // Create a new TripleDES object. + using (TripleDES tripleDes = TripleDES.Create()) + // Create a TripleDES encryptor from the key and IV + using (ICryptoTransform encryptor = tripleDes.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); - // Create a new TripleDES object. - using (TripleDES tripleDESalg = TripleDES.Create()) - { - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - using (CryptoStream cStream = new CryptoStream(fStream, - tripleDESalg.CreateEncryptor(Key, IV), - CryptoStreamMode.Write)) - { - - // Create a StreamWriter using the CryptoStream. - using (StreamWriter sWriter = new StreamWriter(cStream)) - { - - // Write the data to the stream - // to encrypt it. - sWriter.WriteLine(Data); - } - } - } + // 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); - } - catch (UnauthorizedAccessException e) - { - Console.WriteLine("A file access 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 { - string retVal = ""; - // Create or open the specified file. - using (FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate)) + // Open the specified file + using (FileStream fStream = File.OpenRead(path)) + // Create a new TripleDES object. + using (TripleDES tripleDes = TripleDES.Create()) + // Create a TripleDES decryptor from the key and IV + using (ICryptoTransform decryptor = tripleDes.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)) { - - // Create a new TripleDES object. - using (TripleDES tripleDESalg = TripleDES.Create()) - { - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - using (CryptoStream cStream = new CryptoStream(fStream, - tripleDESalg.CreateDecryptor(Key, IV), - CryptoStreamMode.Read)) - { - - // Create a StreamReader using the CryptoStream. - using (StreamReader sReader = new StreamReader(cStream)) - { - - // Read the data from the stream - // to decrypt it. - retVal = sReader.ReadLine(); - } - } - } + // 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(); } - // Return the string. - return retVal; } catch (CryptographicException e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); - return null; - } - catch (UnauthorizedAccessException e) - { - Console.WriteLine("A file access error occurred: {0}", e.Message); - return null; + throw; } } } diff --git a/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample1.cs b/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample1.cs deleted file mode 100644 index ee802d81c32..00000000000 --- a/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample1.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -using System; -using System.Security.Cryptography; -using System.Text; -using System.IO; - -class TripleDESSample -{ - - static void Main() - { - try - { - // Create a new TripleDES object to generate a key - // and initialization vector (IV). Specify one - // of the recognized simple names for this - // algorithm. - TripleDES TripleDESalg = TripleDES.Create("TripleDES"); - - // 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, TripleDESalg.Key, TripleDESalg.IV); - - // Decrypt the text from a file using the file name, key, and IV. - string Final = DecryptTextFromFile(FileName, TripleDESalg.Key, TripleDESalg.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 TripleDES object. - TripleDES tripleDESalg = TripleDES.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - tripleDESalg.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 TripleDES object. - TripleDES tripleDESalg = TripleDES.Create(); - - // Create a CryptoStream using the FileStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(fStream, - tripleDESalg.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/TripleDES/Create/memoryexample.cs b/snippets/csharp/System.Security.Cryptography/TripleDES/Create/memoryexample.cs index 9c3432dc377..ec5c701c37f 100644 --- a/snippets/csharp/System.Security.Cryptography/TripleDES/Create/memoryexample.cs +++ b/snippets/csharp/System.Security.Cryptography/TripleDES/Create/memoryexample.cs @@ -4,29 +4,34 @@ using System.Text; using System.IO; -class TripleDESSample +class TripleDESSample2 { static void Main() { try { - // Create a new TripleDES object to generate a key - // and initialization vector (IV). Specify one - // of the recognized simple names for this - // algorithm. - TripleDES TripleDESalg = TripleDES.Create("TripleDES"); + byte[] key; + byte[] iv; + + // Create a new TripleDES object to generate a random key + // and initialization vector (IV). + using (TripleDES tripleDes = TripleDES.Create()) + { + key = tripleDes.Key; + iv = tripleDes.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, TripleDESalg.Key, TripleDESalg.IV); + byte[] encrypted = EncryptTextToMemory(original, key, iv); // Decrypt the buffer back to a string. - string Final = DecryptTextFromMemory(Data, TripleDESalg.Key, TripleDESalg.IV); + string decrypted = DecryptTextFromMemory(encrypted, key, iv); // Display the decrypted string to the console. - Console.WriteLine(Final); + Console.WriteLine(decrypted); } catch (Exception e) { @@ -34,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 TripleDES object. - TripleDES tripleDESalg = TripleDES.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream cStream = new CryptoStream(mStream, - tripleDESalg.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 TripleDES object. + using (TripleDES tripleDes = TripleDES.Create()) + // Create a TripleDES encryptor from the key and IV + using (ICryptoTransform encryptor = tripleDes.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 TripleDES object. - TripleDES tripleDESalg = TripleDES.Create(); - - // Create a CryptoStream using the MemoryStream - // and the passed key and initialization vector (IV). - CryptoStream csDecrypt = new CryptoStream(msDecrypt, - tripleDESalg.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. + // TripleDES-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 TripleDES object. + using (TripleDES tripleDes = TripleDES.Create()) + // Create a TripleDES decryptor from the key and IV + using (ICryptoTransform decryptor = tripleDes.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/TripleDES/Create/project.csproj b/snippets/csharp/System.Security.Cryptography/TripleDES/Create/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/csharp/System.Security.Cryptography/TripleDES/Create/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.File/VB/fileexample.vb b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.File/VB/fileexample.vb index 780a23efe4f..c43b32acd50 100644 --- a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.File/VB/fileexample.vb +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.File/VB/fileexample.vb @@ -1,104 +1,88 @@ ' +Imports System.IO Imports System.Security.Cryptography Imports System.Text -Imports System.IO Module TripleDESSample Sub Main() Try + Dim key As Byte() + Dim iv As Byte() + ' Create a new TripleDES object to generate a key ' and initialization vector (IV). - Using TripleDESalg As TripleDES = TripleDES.Create + Using tripleDes As TripleDES = TripleDES.Create + key = tripleDes.Key + iv = tripleDes.IV + End Using - ' Create a string to encrypt. - Dim sData As String = "Here is some data to encrypt." - Dim FileName As String = "CText.txt" + ' Create a string to encrypt. + 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, TripleDESalg.Key, TripleDESalg.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, TripleDESalg.Key, TripleDESalg.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) - End Using + ' Display the decrypted string to the console. + 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. - Using fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate) - - ' Create a new TripleDES object. - Using TripleDESalg As TripleDES = TripleDES.Create - - ' Create a CryptoStream using the FileStream - ' and the passed key and initialization vector (IV). - Using cStream As New CryptoStream(fStream, _ - TripleDESalg.CreateEncryptor(Key, IV), _ - CryptoStreamMode.Write) - - ' Create a StreamWriter using the CryptoStream. - Using sWriter As New StreamWriter(cStream) - - ' Write the data to the stream - ' to encrypt it. - sWriter.WriteLine(Data) - - End Using - End Using - End Using + ' Create a new TripleDES object, + ' Create a TripleDES encryptor from the key and IV, + ' Create a CryptoStream using the MemoryStream And encryptor + Using fStream As FileStream = File.Open(path, FileMode.Create), + tripleDes As TripleDES = TripleDES.Create, + encryptor As ICryptoTransform = tripleDes.CreateEncryptor(key, iv), + cStream = New CryptoStream(fStream, encryptor, CryptoStreamMode.Write) + + ' Convert the passed string to a byte array. + Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text) + + ' Write the byte array to the crypto stream. + cStream.Write(toEncrypt, 0, toEncrypt.Length) End Using - Catch e As CryptographicException Console.WriteLine("A Cryptographic error occurred: {0}", e.Message) - Catch e As UnauthorizedAccessException - Console.WriteLine("A file access 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 - Dim retVal As String - ' Create or open the specified file. - Using fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate) - - ' Create a new TripleDES object. - Using TripleDESalg As TripleDES = TripleDES.Create - - ' Create a CryptoStream using the FileStream - ' and the passed key and initialization vector (IV). - Using cStream As New CryptoStream(fStream, _ - TripleDESalg.CreateDecryptor(Key, IV), CryptoStreamMode.Read) - - ' Create a StreamReader using the CryptoStream. - Using sReader As New StreamReader(cStream) - - ' Read the data from the stream - ' to decrypt it. - retVal = sReader.ReadLine() - End Using - End Using - End Using + ' Open the specified file + ' Create a new TripleDES object. + ' Create a TripleDES 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), + tripleDes As TripleDES = TripleDES.Create, + decryptor As ICryptoTransform = tripleDes.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 - - Return retVal Catch e As CryptographicException Console.WriteLine("A Cryptographic error occurred: {0}", e.Message) Return Nothing - Catch e As UnauthorizedAccessException - Console.WriteLine("A file access 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.3DES.Create.File/VB/project.csproj b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.File/VB/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.File/VB/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/VB/memoryexample.vb b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/VB/memoryexample.vb index b87b6808656..d8c539e0d8c 100644 --- a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/VB/memoryexample.vb +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/VB/memoryexample.vb @@ -1,106 +1,103 @@ - ' +' Imports System.Security.Cryptography Imports System.Text Imports System.IO -Module TripleDESPSample +Module TripleDESSample Sub Main() Try + Dim key As Byte() + Dim iv As Byte() + ' Create a new TripleDES object to generate a key ' and initialization vector (IV). - Using TripleDESalg As TripleDES = TripleDES.Create - - ' Create a string to encrypt. - Dim sData As String = "Here is some data to encrypt." + Using tripleDes As TripleDES = TripleDES.Create + key = tripleDes.Key + iv = tripleDes.IV + End Using - ' Encrypt the string to an in-memory buffer. - Dim Data As Byte() = EncryptTextToMemory(sData, TripleDESalg.Key, TripleDESalg.IV) + ' Create a string to encrypt. + Dim original As String = "Here is some data to encrypt." - ' Decrypt the buffer back to a string. - Dim Final As String = DecryptTextFromMemory(Data, TripleDESalg.Key, TripleDESalg.IV) + ' Encrypt the string to an in-memory buffer. + Dim encrypted As Byte() = EncryptTextToMemory(original, key, iv) - ' Display the decrypted string to the console. - Console.WriteLine(Final) - End Using + ' Decrypt the buffer back to a string. + Dim decrypted As String = DecryptTextFromMemory(encrypted, key, iv) + ' Display the decrypted string to the console. + 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 - Dim ret As Byte() ' Create a MemoryStream. Using mStream As New MemoryStream + ' Create a new TripleDES object, + ' Create a TripleDES encryptor from the key and IV, + ' Create a CryptoStream using the MemoryStream And encryptor + Using tripleDes As TripleDES = TripleDES.Create, + encryptor As ICryptoTransform = tripleDes.CreateEncryptor(key, iv), + cStream = New CryptoStream(mStream, encryptor, CryptoStreamMode.Write) - ' Create a new TripleDES object. - Using tripleDESalg As TripleDES = TripleDES.Create + ' Convert the passed string to a byte array. + Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text) - ' Create a CryptoStream using the MemoryStream - ' and the passed key and initialization vector (IV). - Using cStream As New CryptoStream(mStream, _ - tripleDESalg.CreateEncryptor(Key, IV), CryptoStreamMode.Write) + ' Write the byte array to the crypto stream and flush it. + cStream.Write(toEncrypt, 0, toEncrypt.Length) - ' Convert the passed string to a byte array. - Dim toEncrypt As Byte() = New ASCIIEncoding().GetBytes(Data) + ' Ending the using block for the CryptoStream completes the encryption. + End Using - ' 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. + Dim ret As Byte() = mStream.ToArray() - ' Get an array of bytes from the - ' MemoryStream that holds the - ' encrypted data. - ret = mStream.ToArray() - End Using - End Using + ' Return the encrypted buffer. + Return ret End Using - - ' Return the encrypted buffer. - Return ret 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 - Dim ret As String - ' Create a new MemoryStream using the passed - ' array of encrypted data. - Using msDecrypt As New MemoryStream(Data) - - ' Create a new TripleDES object. - Using tripleDESalg As TripleDES = TripleDES.Create - - ' Create a CryptoStream using the MemoryStream - ' and the passed key and initialization vector (IV). - Using csDecrypt As New CryptoStream(msDecrypt, _ - tripleDESalg.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. - ret = New ASCIIEncoding().GetString(fromEncrypt) - End Using - End Using + ' Create a buffer to hold the decrypted data. + ' TripleDES-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 TripleDES object. + ' Create a TripleDES decryptor from the key and IV + ' Create a CryptoStream using the MemoryStream and decryptor + Using mStream As New MemoryStream(encrypted), + tripleDes As TripleDES = TripleDES.Create, + decryptor As ICryptoTransform = tripleDes.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 - Return ret + ' 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 +' diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/project.csproj b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Create.Memory/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.File/VB/fileexample.vb b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.File/VB/fileexample.vb index 5faa821655e..5050281aff1 100644 --- a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.File/VB/fileexample.vb +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.File/VB/fileexample.vb @@ -1,104 +1,88 @@ ' +Imports System.IO Imports System.Security.Cryptography Imports System.Text -Imports System.IO Module RC2Sample Sub Main() Try + Dim key As Byte() + Dim iv As Byte() + ' Create a new RC2 object to generate a key ' and initialization vector (IV). - Dim RC2alg As RC2 = RC2.Create + Using rc2 As RC2 = RC2.Create + key = rc2.Key + iv = rc2.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, RC2alg.Key, RC2alg.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, RC2alg.Key, RC2alg.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 RC2 object, + ' Create an RC2 encryptor from the key and IV, + ' Create a CryptoStream using the MemoryStream And encryptor + Using fStream As FileStream = File.Open(path, FileMode.Create), + rc2 As RC2 = RC2.Create, + encryptor As ICryptoTransform = rc2.CreateEncryptor(key, iv), + cStream = New CryptoStream(fStream, encryptor, CryptoStreamMode.Write) - ' Create a new RC2 object. - Dim RC2alg As RC2 = RC2.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, _ - RC2alg.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 RC2 object. - Dim RC2alg As RC2 = RC2.Create - - ' Create a CryptoStream using the FileStream - ' and the passed key and initialization vector (IV). - Dim cStream As New CryptoStream(fStream, _ - RC2alg.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 an RC2 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), + rc2 As RC2 = RC2.Create, + decryptor As ICryptoTransform = rc2.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.RC2.Create.File/VB/project.csproj b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.File/VB/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.File/VB/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/VB/memoryexample.vb b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/VB/memoryexample.vb index c436a98bbac..de3cfff8bdf 100644 --- a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/VB/memoryexample.vb +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/VB/memoryexample.vb @@ -7,94 +7,97 @@ Module RC2Sample Sub Main() Try + Dim key As Byte() + Dim iv As Byte() + ' Create a new RC2 object to generate a key ' and initialization vector (IV). - Dim RC2alg As RC2 = RC2.Create + Using rc2 As RC2 = RC2.Create + key = rc2.Key + iv = rc2.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, RC2alg.Key, RC2alg.IV) + Dim encrypted As Byte() = EncryptTextToMemory(original, key, iv) ' Decrypt the buffer back to a string. - Dim Final As String = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.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 RC2 object. - Dim RC2alg As RC2 = RC2.Create + Using mStream As New MemoryStream + ' Create a new RC2 object, + ' Create an RC2 encryptor from the key and IV, + ' Create a CryptoStream using the MemoryStream And encryptor + Using rc2 As RC2 = RC2.Create, + encryptor As ICryptoTransform = rc2.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, _ - RC2alg.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. + ' RC2-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 RC2 object. - Dim RC2alg As RC2 = RC2.Create - - ' Create a CryptoStream using the MemoryStream - ' and the passed key and initialization vector (IV). - Dim csDecrypt As New CryptoStream(msDecrypt, _ - RC2alg.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 an RC2 decryptor from the key and IV + ' Create a CryptoStream using the MemoryStream and decryptor + Using mStream As New MemoryStream(encrypted), + rc2 As RC2 = RC2.Create, + decryptor As ICryptoTransform = rc2.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 +' diff --git a/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/project.csproj b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/project.csproj new file mode 100644 index 00000000000..b76fb495a36 --- /dev/null +++ b/snippets/visualbasic/VS_Snippets_CLR/Cryptography.RC2.Create.Memory/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net6.0 + + + diff --git a/xml/System.Security.Cryptography/RC2.xml b/xml/System.Security.Cryptography/RC2.xml index 44610293f8e..1de9917c92a 100644 --- a/xml/System.Security.Cryptography/RC2.xml +++ b/xml/System.Security.Cryptography/RC2.xml @@ -274,29 +274,7 @@ The name of the specific implementation of to use. Creates an instance of a cryptographic object to perform the specified implementation of the algorithm. An instance of a cryptographic object. - - - + To be added. The algorithm described by the parameter was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible. Cryptographic Services diff --git a/xml/System.Security.Cryptography/TripleDES.xml b/xml/System.Security.Cryptography/TripleDES.xml index 921281cc21a..76844bd86a7 100644 --- a/xml/System.Security.Cryptography/TripleDES.xml +++ b/xml/System.Security.Cryptography/TripleDES.xml @@ -288,24 +288,7 @@ The name of the specific implementation of to use. Creates an instance of a cryptographic object to perform the specified implementation of the algorithm. An instance of a cryptographic object. - - object to encrypt and decrypt data in a file. - - :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/Cryptography.3DES.Createstring.File/CPP/fileexample.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/TripleDES/Create/fileexample1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.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.3DES.Createstring.Memory/CPP/memoryexample.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/TripleDES/Create/memoryexample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Cryptography.3DES.Createstring.Memory/VB/memoryexample.vb" id="Snippet1"::: - - ]]> - + To be added. Cryptographic Services