MSDN上的一个不错的例子: 那从内存清除密码的句子有个问题。 需要再看看这个问题到底是怎么回事,怎么解决

cannot convert from Sytem.InPtr to ref string

把下面这句

public static extern bool ZeroMemory(ref string Destination, int Length);

用这句替换就OK了

internal static extern void ZeroMemory(IntPtr handle, int length);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;namespace MSDNEncryExample
{class Program{//  Call this function to remove the key from memory after use for security.[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]internal static extern void ZeroMemory(IntPtr handle, int length);// Function to Generate a 64 bits Key.static string GenerateKey(){// Create an instance of Symetric Algorithm. Key and IV is generated automatically.DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();// Use the Automatically generated key for Encryption. return ASCIIEncoding.ASCII.GetString(desCrypto.Key);}static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey){// Create a file stream to read the data to be encryptedFileStream fsInput = new FileStream(sInputFilename,FileMode.Open,FileAccess.Read);//Crete a file stream for the encrypted dataFileStream fsEncrypted = new FileStream(sOutputFilename,FileMode.Create,FileAccess.Write);// Create encryptor by usin the keyDESCryptoServiceProvider DES = new DESCryptoServiceProvider();DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);ICryptoTransform desencrypt = DES.CreateEncryptor();// Create a CrytoStream to link the encrypted stream and the encryptorCryptoStream cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write);// Read the file stream to bytes arraybyte[] bytearrayinput = new byte[fsInput.Length];fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);// Encrypt the byte array by using the CryptoStreamcryptostream.Write(bytearrayinput,0,bytearrayinput.Length);// Close the file streamscryptostream.Close();fsInput.Close();fsEncrypted.Close();}static void DecryptFile(string sInputFilename,string sOutputFilename,string sKey){// Set the DESCryptoServiceProvider classDESCryptoServiceProvider DES = new DESCryptoServiceProvider();//A 64 bit key and IV is required for this provider.//Set secret key For DES algorithm.DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);//Set initialization vector.DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);//Create a file stream to read the encrypted file back.FileStream fsread = new FileStream(sInputFilename,FileMode.Open,FileAccess.Read);//Create a DES decryptor from the DES instance.ICryptoTransform desdecrypt = DES.CreateDecryptor();//Create crypto stream set to read and do a //DES decryption transform on incoming bytes.CryptoStream cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);//Print the contents of the decrypted file.StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());fsDecrypted.Flush();fsDecrypted.Close();} static void Main(string[] args){// Must be 64 bits, 8 bytes.// Distribute this key to the user who will decrypt this file.string sSecretKey;// Get the Key for the file to Encrypt.sSecretKey = GenerateKey();// For additional security Pin the key.GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned);// Encrypt the file.        EncryptFile(@"C:\MyData.txt",@"C:\Encrypted.txt",sSecretKey);// Decrypt the file.DecryptFile(@"C:\Encrypted.txt",@"C:\Decrypted.txt",sSecretKey);// Remove the Key from memory. ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);gch.Free();}}
}

另外一个例子
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;class RijndaelSample
{static void Main(){try{// Create a new Rijndael object to generate a key// and initialization vector (IV).Rijndael RijndaelAlg = Rijndael.Create();// Create a string to encrypt.string sData = "Here is some data to encrypt.";string FileName = "CText.txt";// Encrypt text to a file using the file name, key, and IV.EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV);// Decrypt the text from a file using the file name, key, and IV.string Final = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV);// Display the decrypted string to the console.Console.WriteLine(Final);}catch (Exception e){Console.WriteLine(e.Message);}Console.ReadLine();}public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV){try{// Create or open the specified file.FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);// Create a new Rijndael object.Rijndael RijndaelAlg = Rijndael.Create();// Create a CryptoStream using the FileStream // and the passed key and initialization vector (IV).CryptoStream cStream = new CryptoStream(fStream,RijndaelAlg.CreateEncryptor(Key, IV),CryptoStreamMode.Write);// Create a StreamWriter using the CryptoStream.StreamWriter sWriter = new StreamWriter(cStream);try{// Write the data to the stream // to encrypt it.sWriter.WriteLine(Data);}catch (Exception e){Console.WriteLine("An error occurred: {0}", e.Message);}finally{// Close the streams and// close the file.sWriter.Close();cStream.Close();fStream.Close();}}catch (CryptographicException e){Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);}catch (UnauthorizedAccessException e){Console.WriteLine("A file error occurred: {0}", e.Message);}}public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV){try{// Create or open the specified file. FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);// Create a new Rijndael object.Rijndael RijndaelAlg = Rijndael.Create();// Create a CryptoStream using the FileStream // and the passed key and initialization vector (IV).CryptoStream cStream = new CryptoStream(fStream,RijndaelAlg.CreateDecryptor(Key, IV),CryptoStreamMode.Read);// Create a StreamReader using the CryptoStream.StreamReader sReader = new StreamReader(cStream);string val = null;try{// Read the data from the stream // to decrypt it.val = sReader.ReadLine();}catch (Exception e){Console.WriteLine("An error occurred: {0}", e.Message);}finally{// Close the streams and// close the file.sReader.Close();cStream.Close();fStream.Close();}// Return the string. return val;}catch (CryptographicException e){Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);return null;}catch (UnauthorizedAccessException e){Console.WriteLine("A file error occurred: {0}", e.Message);return null;}}
}

这个

CryptoStream Class

Defines a stream that links data streams to cryptographic transformations. CryptoSteam类提供数据流和加密传递之间的链接。

关于ZeroMemory

ZeroMemory Macro

Fills a block of memory with zeros.

To avoid any undesired effects of optimizing compilers, use the SecureZeroMemory function.

Parameters

Destination [in]

A pointer to the starting address of the block of memory to fill with zeros.

Length [in]

The size of the block of memory to fill with zeros, in bytes.

Return Value

This macro has no return value.

Remarks

Many programming languages include syntax for initializing complex variables to zero. There can be differences between the results of these operations and the ZeroMemory function. Use ZeroMemory to clear a block of memory in any programming language.

This macro is defined as the RtlZeroMemory macro. For more information, see Winbase.h and Winnt.h.

转载于:https://www.cnblogs.com/herbert/archive/2010/05/14/1735683.html

【读书笔记】MSDN 上关于加密解密的一个例子相关推荐

  1. 《MSSQL2008技术内幕:T-SQL语言基础》读书笔记(上)

    索引: 一.SQL Server的体系结构 二.查询 三.表表达式 四.集合运算 五.透视.逆透视及分组 六.数据修改 七.事务和并发 八.可编程对象 一.SQL Server体系结构 1.1 数据库 ...

  2. 【科学究竟是什么/查尔默斯】读书笔记(上)

    [查尔默斯-科学究竟是什么]读书笔记(上)] "主流"科学观 归纳主义 朴素归纳主义 归纳问题 出于"观察事实"角度的反驳 精致的归纳主义 证伪主义 可证伪性 ...

  3. MSDN上的异步socket 服务端例子

    MSDN上的异步socket 服务端例子 2006-11-22 17:12:01|  分类: 代码学习 |  标签: |字号大中小 订阅 Imports System Imports System.N ...

  4. 网络知识 | 《图解HTTP》读书笔记(上)

    [网络知识]| 作者 / Edison Zhou 这是EdisonTalk的第293篇原创内容 作为一个专业的IT技术人,一个Web应用开发者,不了解网络基础和协议,怎么能行?本文是我2016年阅读& ...

  5. 【读书笔记】《数学之美》——一个好方法在形式上总是简单的

    数学之美 作者简介 内容简介 摘抄语录 收获感悟 牛顿曾说"(人们)发觉真理在形式上从来是简单的,而不是复杂和含混的."数学的美妙之处在于它对自然界史诗的总结和归纳,也是抽象思考的 ...

  6. 《深入理解 Java 内存模型》读书笔记(上)(干货,万字长文)

    目录 0. 前提 1. 基础 1.1 并发编程的模型分类 1.1.1 通信 1.1.2 同步 1.2 JAVA 内存模型的抽象 2. 重排序 2.1 处理器重排序 2.2 内存屏障指令 2.3 HAP ...

  7. 网络知识 | 《图解TCP/IP》读书笔记(上)

    [网络知识]| 作者 / Edison Zhou 这是EdisonTalk的第290篇原创内容 作为一个专业的IT技术人,一个Web应用开发者,不了解网络基础和协议,怎么能行?本文是我2016年阅读& ...

  8. 《程序员的呐喊》读书笔记(上)

    <程序员的呐喊>是Google一位老程序员的经验总结,文中展现了他对各大语言如Java.C/C++.Lisp.Python.Ruby.Perl等的极端观点,比如大力吐槽C++,极力推崇C. ...

  9. python解密_python在加密解密中的例子(尽可能去深挖)

    前言 在实际测试中,我们一遇到登录处用户名和密码都加密的例子,我们就没办法进行深入啦.就像下面的例子,其实加密只是增加我们的攻击成本,只要还是客户端,在提交服务器之前,所有的加密基本有迹可循,直接看本 ...

最新文章

  1. 机器学习的基础图表!
  2. linux配置jdk环境
  3. boost::mp11::mp_nth_element相关用法的测试程序
  4. web cache缓存设备的需求与讨论 ( Http://CACHE.MARASYSTEMS.ASIA )
  5. 大数据应用之金融行业-互联网金融对传统银行业的冲击,狼真的来了
  6. 基于 HTML5 WebGL 的 3D 智慧隧道漫游巡检
  7. struts2随笔(一)Action、struts.xml、Interceptor细节
  8. 您不知道Bash:Bash阵列简介
  9. 弹窗实用素材模板|UI设计中的弹窗设计技巧,快get
  10. 系统动力学模型_RCR新文:基于系统动力学模型的中国煤炭产能情景预测
  11. 为什么要学习Kotlin
  12. Django搭建的个人博客
  13. Logisim实验一
  14. 2021年1月PMP考试改版
  15. SVN忽略指定文件或文件夹的提交
  16. 关于Ubuntu下firefox无法观看视频的解决
  17. 关于舵轮AGV 的数学模型
  18. Yii2.0 视频教程
  19. 计算机研究生申请 MIT,麻省理工计算机专业研究生申请条件有什么?
  20. mysql重启后应用也要重启_数据库重启后应用也必须重启

热门文章

  1. 三菱socket通信实例_三菱自动化产品相关知识整理汇总
  2. 未来计算机的功能猜想,全方位猜想,未来计算机发展详细预测
  3. python tabula 使用方法_Python中os.walk()的使用方法
  4. centos mysql 5.6 源码_Centos7环境中mysql-5.6.39 源码安装
  5. java backbone_在Backbone.js中发出POST请求
  6. find linux 目录深度_浪里淘沙,详解Linux系统中Find命令的实用技巧
  7. leetcode268. 缺失数字
  8. Linux下MySQL忘记root密码及解决办法
  9. 剑指offer(刷题21-30)--c++,Python版本
  10. kaggle (02) - 房价预测案例(进阶版)