找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 1033|回复: 3

[分享] Managed I/O - Streams, Readers, and Writers

[复制链接]

已领礼包: 859个

财富等级: 财运亨通

发表于 2015-10-7 08:16:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×

C++ CryptoStream Example

Create a new CLR console application project and you might want  to use CryptoStreamSampleCP as the project and solution names.

0.jpg

Add the following code.

//  CryptoStreamSampleCP.cpp : main project file.
// < summary>
//  This sample is designed to show how to use the composable stream  CryptoStream
//  to read and write encrypted data to a file. The sample uses the  DES encryption
//  standard to encrypt data.
// < /summary>

#include "stdafx.h"

using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;

// < summary>
//  The main entry point for the application.
// < /summary>
[STAThread]
int main(array<System::String  ^> ^args)
{
    // Let's create a  private key that will be used to encrypt and decrypt the data stored  in the file hantu.dat.
    array< Byte >^ DESKey = gcnew array< Byte >{200, 5, 78, 232, 9, 6, 0, 4};
    array< Byte >^ DESInitializationVector = gcnew array< Byte >{0, 1, 2, 3,  4, 5, 6, 7, 8, 9};
     String^ FileName = "C:\\temp\\hantu.dat";
     CryptoStream^ MyStreamEncrypter = nullptr;

    try
     {
        // Let's create a  file named hantu.dat in the current C:\Temp directory  
         FileStream^ MyFileStream = nullptr;
        try
         {
              MyFileStream = gcnew FileStream(FileName, FileMode::Create, FileAccess::Write);
              Console::WriteLine("{0}  file created/opened successfully", FileName);
         }
        catch (Exception^ e)
         {
            throw gcnew Exception("Failed  to create/open filestream with error: " + e->Message);
         }

        // Let's create a  Symmetric crypto stream using the DES algorithm to encode all the  bytes written to the file hantu.
        try
         {
             Console::WriteLine("Instantiate  DESCryptoServiceProvider & CryptoStream, encrypting {0}...",  FileName);
             DES^ DESAlgorithm = gcnew DESCryptoServiceProvider();
             MyStreamEncrypter = gcnew CryptoStream(MyFileStream, DESAlgorithm->CreateEncryptor(DESKey,  DESInitializationVector), CryptoStreamMode::Write);
         }
        catch (Exception^ e)
         {
             MyFileStream->Close();
            throw gcnew Exception("Failed  to create DES Symmetric CryptoStream with error: " + e->Message);
         }

        // Let's write 10  bytes to our crypto stream. For simplicity
        // we will write an  array of 10 bytes where each byte contains a numeric value 0 - 9.
        array< Byte >^ MyByteArray = gcnew array< Byte >(10);
         
          Console::WriteLine("Writing...");
         for (short i = 0; i < MyByteArray->Length; i++)
         {
             MyByteArray = (Byte)i;
             Console::Write("{0},  ", MyByteArray);
          }
              Console::WriteLine();

        try
         {
               MyStreamEncrypter->Write(MyByteArray, 0, MyByteArray->Length);
               Console::WriteLine("Writing  10 bytes to the crypto stream...");
         }
        catch (Exception^ e)
         {
            throw gcnew Exception("Write  failed with error: " + e->Message);
         }
     }
    catch (Exception^ e)
     {
         Console::WriteLine(e->Message);
        return 0;
     }
    finally
     {
        // Let's close the  crypto stream now that we are finished writing data.
         Console::WriteLine("Closing  the encrypter stream...");
         MyStreamEncrypter->Close();
     }
    // Now let's open  the encrypted file Jim.dat and decrypt the contents.
     Console::WriteLine();
     Console::WriteLine("Opening  the encrypted {0} file and decrypting it...", FileName);
     CryptoStream^ MyStreamDecrypter = nullptr;

    try
     {
         FileStream^ MyFileStream = nullptr;

        try
         {
              MyFileStream = gcnew FileStream(FileName, FileMode::Open, FileAccess::Read);
              Console::WriteLine("Decrypted  {0} file opened successfully", FileName);
         }
        catch (Exception^ e)
         {
            throw gcnew Exception("Failed  to open filestream with error: " + e->Message);
         }

        try
         {
             Console::WriteLine("Instantiate  DESCryptoServiceProvider & CryptoStream, decrypting {0}...",  FileName);
             DES^ DESAlgorithm = gcnew DESCryptoServiceProvider();
             MyStreamDecrypter = gcnew CryptoStream(MyFileStream, DESAlgorithm->CreateDecryptor(DESKey,  DESInitializationVector), CryptoStreamMode::Read);
         }
        catch (Exception^ e)
         {
             MyFileStream->Close();
            throw gcnew Exception("Failed  to create DES Symmetric CryptoStream with error: " + e->Message);
         }

        array< Byte >^ MyReadBuffer = gcnew array< Byte >(1);
         Console::WriteLine("Reading  the decrypted {0} file content...", FileName);
        while (true)
         {
            int BytesRead;

            try
             {
                 BytesRead = MyStreamDecrypter->Read(MyReadBuffer, 0, MyReadBuffer->Length);
             }
            catch (Exception^ e)
             {
                throw gcnew Exception("Read  failed with error: " + e->Message);
             }
            if (BytesRead  == 0)
             {
                 Console::WriteLine("No  more bytes to read...");
                break;
             }
             Console::WriteLine("Read  byte -> " + MyReadBuffer[0].ToString());
         }
     }
    catch (Exception^ e)
     {
               Console::WriteLine(e->Message);
     }
    finally
     {
        // We are finished  performing IO on the file. We need to close the file to release  operating system resources related to the file.
         Console::WriteLine("Closing  the decrypter stream...");
         MyStreamDecrypter->Close();
     }
    return 0;
}

Build and run the project. The following is an output example.

1.jpg


论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2015-10-7 15:25:56 | 显示全部楼层
本帖最后由 csharp 于 2015-10-7 16:40 编辑

  1. #include "stdafx.h"

  2. using namespace System;
  3. using namespace System::Text;
  4. using namespace System::Security::Cryptography;
  5. using namespace System::IO;

  6. int main(array<System::String ^> ^args)
  7. {
  8.         MemoryStream^ mStream = gcnew MemoryStream();
  9.         array< Byte >^ DESKey = gcnew array< Byte >{200, 5, 78, 232, 9, 6, 0, 4};
  10.     array< Byte >^ DESInitializationVector = gcnew array< Byte >{0, 1, 2, 3,  4, 5, 6, 7};

  11.         String^ unicodeString = L"This unicode string contains two characters with codes outside an 8-bit";

  12.         UTF8Encoding^ utf8 = gcnew UTF8Encoding;
  13.         array<Byte>^ data=utf8->GetBytes(unicodeString);

  14.         DES^ DESAlgorithm =  gcnew DESCryptoServiceProvider();

  15.         CryptoStream^ cStream = gcnew CryptoStream(mStream,
  16.                 DESAlgorithm->CreateEncryptor(DESKey, DESInitializationVector),
  17.                 CryptoStreamMode::Write);

  18.         cStream->Write(data, 0, data->Length);
  19.         cStream->FlushFinalBlock();

  20.         array<Byte>^ ret = mStream->ToArray();
  21.         Convert^ cvt;
  22.         String^ retstr=cvt->ToBase64String(ret);

  23.         cStream->Close();
  24.         mStream->Close();

  25.         Console::WriteLine(retstr );
  26.         System::Console::ReadLine();
  27.     return 0;
  28. }
FWj4VvUHOr6Yp6ZgwKPid7C9uacUdychc5DXigKnZ8JtKAJNB7G9PzWBi++z+Z92GR5YFDnpwkc8tY0M7bnIzGG8hYLPLiP7
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|申请友链|Archiver|手机版|小黑屋|辽公网安备|晓东CAD家园 ( 辽ICP备15016793号 )

GMT+8, 2024-5-13 16:38 , Processed in 0.372411 second(s), 32 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表