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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/463012.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[luogu3380][bzoj3196]【模板】二逼平衡树【树套树】

题目地址 【洛谷传送门】 题目大意 区间查询k的排名,查找k排名的数,单点修改,区间前驱,区间后继。 感想 真的第一次写树套树,整个人都不对了。重构代码2次,发现样例都过不了,splay直接爆炸&…

Parquet格式描述

背景 2010年 google 发表了一篇论文《Dremel: Interactive Analysis of Web-Scale Datasets》,介绍了其 Dermel 系统是如何利用列式存储管理嵌套数据的,嵌套数据就是层次数据,如定义一个班级,班级由同学组成,同学的信…

Notepad++ 快捷键 大全

修改快捷键的话:设置----管理快捷键----就好比第一个快捷键新建吧--------鼠标双击,然后会弹出来对话框让你对具体想要设置的快捷键进行设置,所有的快捷键都是这么设置的,但是我就是不明白,你要设置的是哪个&#xff1…

Kevin专栏---如何制作试用版安装包

首先需要在http://activationservice.installshield.com/doLogin.do注册一个试用账号。注册完成后系统会自动发送一个15天的试用账号和密码。 在图标Trialware Files上点击鼠标右键,创建一个试用配置项(见下图)。 首先选择试用文件&#xff0…

ldd命令解析

在linux中,经常会碰到查看可执行文件需要依赖哪些动态链接库,这时ldd命令就可以排上用场了 由于某种原因,屏蔽了一些内容,结果如下: 可以根据结果查找对应的动态链接库

UDP和TCP协议包大小的计算-转

UDP和TCP协议包大小的计算 UDP一次发送数据包的大小,TCP一次发送数据包的大小。MTU最大传输单元,这个最大传输单元实际上和链路层协议有着密切的关系,EthernetII帧的结构DMACSMACTypeDataCRC由于以太网传输电气方面的限制,每个以太…

洛谷 - P1361 - 小M的作物 - 最小割 - 最大权闭合子图

第一次做最小割,不是很理解。 https://www.luogu.org/problemnew/show/P1361 要把东西分进两类里,好像可以应用最小割的模板,其中一类A作为源点,另一类B作为汇点,价值就是边的容量。 然后最小割一定会割断每个中间结点…

LVS

1、安装lvs 在分发器上在172.16.10.1上执行,事先应该配置好你的yum源,保证能够读取介质中的Cluster目录!#yum install ipvsadm编写,分发规则(注意,清空之前的防火墙iptable -F ; iptable -t nat…

linux Swap交换分区概念

Swap交换分区概念 什么是Linux swap space呢?我们先来看看下面两段关于Linux swap space的英文介绍资料: Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copie…

ThinkPHP 数据库操作(七) : 视图查询、子查询、原生查询

视图查询 视图查询可以实现不依赖数据库视图的多表查询,并不需要数据库支持视图,例如: Db::view(User,id,name)->view(Profile,truename,phone,email,Profile.user_idUser.id)->view(Score,score,Score.user_idProfile.id)->where(…

C++中的结构体函数

代码 #include "stdafx.h"structTest{ intnum; Test() { printf("11111111"); } Test(inti) { this->numi; } voidfun() { printf("fun"); }};voidmain( void){ Test a(1); …

Linux 查看进程的命令

1、ps ps -x : 只显示当前用户下的所有进程信息 ps -aux : 所有用户下的进程信息 2、top 显示动态的进程信息,5s刷新一次; 3、htop 需要自己安装htop命令,比较牛,个人也只是简单使用过,比top命令快,可…

关于安卓手机在微信浏览器中无法调起相机的原因

最近功在做公司的一个项目,遇到安卓手机在微信浏览器中更换头像无法调起相机的问题,特来此记录一下。 1.微信没有相机权限,开启就行了。 2.〈input type“file” accept“image/*”/〉。图库和相机都能调起。 3.部分冷门手机因系统原因不开放…

使用Microsoft Media Service实现网络影音多媒体应用系列第三篇---技术要点

技术要点解说: l 对Media Service的引用 Imports Microsoft.WindowsMediaServices.Interop Imports System.Runtime.InteropServices 引入以上两个命名空间以后,就可以看到WMSServer这个类,它就是指向Media Service的类。Activator.CreateIn…

SEO新手入门笔记

2019独角兽企业重金招聘Python工程师标准>>> 上个月公司让我给产品网站做SEO,第一次做这种事情,从中学到一些新东西,在这里做一个总结。 什么是SEO SEO是“搜索引擎优化”的简称,目的是提升网站在搜索引擎结果中的排名…

学习进度(4)

记录时间: 第五周 所花时间(包括上课) 10h 代码量(行) 200行 博客量(篇) 0篇 了解到的知识点 深入学习数据库语句 转载于:https://www.cnblogs.com/quxiangjia/p/10676086.html

linux top 命令的结果

PID:进程标志号,是非零正整数USER:进程所有者的用户名PR:进程的优先级别NI:进程的优先级别数值VIRT:进程占用的虚拟内存值RES:进程占用的物理内存值SHR:进程使用的共享内存值S&#…

从语义开始 – 概念、意义、实践

从语义开始 – 概念、意义、实践http://bbs.blueidea.com/thread-2944769-1-1.html 转载于:https://www.cnblogs.com/javashi/archive/2010/05/21/1741019.html

通过Python脚本理解系统进程间通信

from socket import * #导入socket包中的所有内容from time import ctime #导入time包,同时在本地可使用ctime进行调用import os,sys #导入os,sys包HOSTlocalhost#定义主机PORT21567#定义端口BUFSIZ1024 #定义缓冲区ADDR(HOST,PORT) #定义元组tcpSerSoc…

EnterpriseDB Replication,复制Oracle数据测试(1)

EntepriseDB 复制软件目前支持多种数据库到postgre的复制,其基本结构由发布者(Publication)与订阅者(Subscriptions)组成,Replication软件可针对来自不同类型数据库的多个发布者,将其数据复制到多个订阅者(Subscriptions)数据库中。 其可能的几种拓扑结构…