[引]生成加密和解密的密钥

1.对称密钥
2.不对称密钥
3.将非对称密钥存储在密钥容器中
4.将非对称密钥存储在密钥容器中示例
===============================

创建和管理密钥是加密过程的一个重要部分。
对称算法要求创建必须对不应解密数据的任何人保密的密钥和初始化向量 (IV)。
不对称算法要求创建一个公钥和一个私钥。
公钥可以对任何人公开,
而私钥必须只为将要对用公钥加密的数据进行解密的一方知道。

对称密钥
========
.NET Framework 提供的对称加密类
需要一个密钥和一个新的初始化向量 (IV) 来加密和解密数据。
每当使用默认构造函数创建某个托管对称加密类的新实例时,
都将自动创建新的密钥和 IV。
无论您允许谁解密您的数据,
他或她都必须拥有同样的密钥和 IV 并使用相同的算法。
通常,应该为每个会话创建新的密钥和 IV,
并且无论是密钥还是 IV 都不应存储以用于稍后的会话中。

为了将对称密钥和 IV 传送给远程方,
通常使用不对称加密来加密对称密钥和 IV。
通过不安全的网络发送这些值而不对这些值进行加密会极不安全,
这是因为截获这些值的任何人都能够解密您的数据。

下面的示例显示
实现TripleDES 算法的 TripleDESCryptoServiceProvider 类的新实例的创建。

Visual Basic:
Dim TDES As TripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()

C#:
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

在执行上面的代码时,将生成新的密钥和 IV 并将其分别放置在 Key 和 IV 属性中。

有时您可能需要生成多个密钥。
这种情况下,可以创建实现对称算法的类的新实例,
然后通过调用 GenerateKey 和 GenerateIV 方法创建新的密钥和 IV。
下面的代码示例阐释如何在创建了不对称加密类的新实例后创建新的密钥和 IV。

Visual Basic :
Dim TDES As TripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()
TDES.GenerateIV()
TDES.GenerateKey()

C# :
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
TDES.GenerateIV();
TDES.GenerateKey();

当执行上面的代码时,创建 TripleDESCryptoServiceProvider 的新实例后将生成密钥和 IV。
调用 GenerateKey 和 GenerateIV 方法时将创建另一个密钥和 IV。

不对称密钥
==========
.NET Framework 为不对称加密提供了
RSACryptoServiceProvider 和 DSACryptoServiceProvider 类。
这些类在您使用默认构造函数创建新实例时创建一个公钥/私钥对。
既可以存储不对称密钥以用在多个会话中,
也可以只为一个会话生成不对称密钥。
公钥可以被广泛地使用,私钥应被严密地保护起来。

每当创建不对称算法类的新实例时,都生成一个公钥/私钥对。
创建该类的新实例后,可以用以下两种方法之一提取密钥信息:

ToXMLString 方法,它返回密钥信息的 XML 表示形式。
ExportParameters 方法,它返回 RSAParameters 结构以保存密钥信息。
两个方法都接受布尔值,该值指示是只返回公钥信息还是同时返回公钥和私钥信息。

通过使用 ImportParameters 方法,
可以将 RSACryptoServiceProvider 类初始化为 RSAParameters 结构的值。

千万不要将不对称私钥逐字存储(或者说以明文形式存储)在本地计算机上。
如果需要存储私钥,则应使用密钥容器。
有关如何在密钥容器中存储私钥的更多信息,
请参见如何:将非对称密钥存储在密钥容器中。

下面的代码示例创建 RSACryptoServiceProvider 类的一个新实例,
创建一个公钥/私钥对,并将公钥信息保存在 RSAParameters 结构中。

Visual Basic  复制代码
'Generate a public/private key pair.
Dim RSA as RSACryptoServiceProvider = new RSACryptoServiceProvider()
'Save the public key information to an RSAParameters structure.
Dim RSAKeyInfo As RSAParameters = RSA.ExportParameters(false)

 
C#  复制代码
//Generate a public/private key pair.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Save the public key information to an RSAParameters structure.
RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
 
将非对称密钥存储在密钥容器中
============================

创建非对称密钥并将其保存在密钥容器中
------------
1.创建 CspParameters 类的一个新实例,
  并将您要密钥容器使用的名称传递给 CspParameters.KeyContainerName 字段。
2.为从 AsymmetricAlgorithm 类派生的一个类
 (通常是 RSACryptoServiceProvider 或 DSACryptoServiceProvider)创建一个新实例,
  并将先前创建的 CspParameters 对象传递给其构造函数。

从密钥容器中删除密钥
------------
1.创建 CspParameters 类的一个新实例,
  并将您要密钥容器使用的名称传递给 CspParameters.KeyContainerName 字段。
2.为从 AsymmetricAlgorithm 类派生的一个类
(通常是 RSACryptoServiceProvider 或 DSACryptoServiceProvider)创建一个新实例,
 并将先前创建的 CspParameters 对象传递给其构造函数。
3.将从 AsymmetricAlgorithm 中派生的类
  的 PersistKeyInCSP 属性设置为 false(在 Visual Basic 中为 False)。
4.调用从 AsymmetricAlgorithm 派生的类的 Clear 方法。
  该方法释放该类所有的资源并清除密钥容器。

将非对称密钥存储在密钥容器中示例
====
下面的示例说明下面这一过程:
创建一个非对称密钥,将其保存在密钥容器中,
以后检索此密钥,最后从该容器中删除此密钥。

请注意,GenKey_SaveInContainer 方法和 GetKeyFromContainer 方法的代码相似。
当为 CspParameters 对象指定密钥容器名称并将其传递给 PersistKeyInCsp 属性
   或 PersistKeyInCsp 属性设置为 true 的 AsymmetricAlgorithm 对象时,
  将会发生以下情况。
  如果不存在具有指定名称的密钥容器,
        则系统将创建一个密钥容器,但密钥保持不变。
  如果确实存在具有指定名称的密钥容器,
        则将此容器中的密钥自动加载到当前 AsymmetricAlgorithm 对象中。
  因此,GenKey_SaveInContainer 方法中的代码保持密钥不变,因为它首先运行;
  而 GetKeyFromContainer 方法中的代码加载此密钥,因为它随后运行。

Visual Basic  复制代码
Imports System
Imports System.IO
Imports System.Security.Cryptography
 _

Public Class StoreKey

    Public Shared Sub Main()
        Try
            ' Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer")

            ' Retrieve the key from the container.
            GetKeyFromContainer("MyKeyContainer")

            ' Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer")

            ' Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer")

            ' Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer")
        Catch e As CryptographicException
            Console.WriteLine(e.Message)
        End Try
    End Sub

    Public Shared Sub GenKey_SaveInContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        ' name used to store the RSA key pair.
        Dim cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Display the key information to the console.
        Console.WriteLine("Key added to container:  {0}", rsa.ToXmlString(True))
    End Sub

    Public Shared Sub GetKeyFromContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        '  name used to store the RSA key pair.
        Dim cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Display the key information to the console.
        Console.WriteLine("Key retrieved from container : {0}", rsa.ToXmlString(True))
    End Sub

    Public Shared Sub DeleteKeyFromContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        '  name used to store the RSA key pair.
        Dim cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Delete the key entry in the container.
        rsa.PersistKeyInCsp = False

        ' Call Clear to release resources and delete the key from the container.
        rsa.Clear()

        Console.WriteLine("Key deleted.")
    End Sub
End Class

 
C#  复制代码
using System;
using System.IO;
using System.Security.Cryptography;

public class StoreKey

{
    public static void Main()
    {
        try
        {
            // Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer");
           
            // Retrieve the key from the container.
            GetKeyFromContainer("MyKeyContainer");
   
            // Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer");

            // Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer");

            // Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer");
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }

    }

    public static void GenKey_SaveInContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container MyKeyContainerName.
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

        // Display the key information to the console.
        Console.WriteLine("Key added to container: \n  {0}", rsa.ToXmlString(true));
    }

    public static void GetKeyFromContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container MyKeyContainerName.
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

        // Display the key information to the console.
        Console.WriteLine("Key retrieved from container : \n {0}", rsa.ToXmlString(true));
    }

    public static void DeleteKeyFromContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container.
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

        // Delete the key entry in the container.
        rsa.PersistKeyInCsp = false;

        // Call Clear to release resources and delete the key from the container.
        rsa.Clear();

        Console.WriteLine("Key deleted.");
    }
}
 

输出
 
Key added to container:
<RSAKeyValue> Key Information A</RSAKeyValue>
Key retrieved from container :
<RSAKeyValue> Key Information A</RSAKeyValue>
Key deleted.
Key added to container:
<RSAKeyValue> Key Information B</RSAKeyValue>
Key deleted.
 

 

转载于:https://www.cnblogs.com/freeliver54/archive/2007/03/05/664695.html

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

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

相关文章

centos7装单机hadoop2.7.3

&#xff08;1&#xff09;hadoop2.7.3下载(前提&#xff1a;先安装java环境)下载地址&#xff1a;http://hadoop.apache.org/releases.html&#xff08;注意是binary文件&#xff0c;source那个是源码&#xff09;&#xff08;2&#xff09;解压tar.gz &#xff08;3&#xff…

计算机指令称,通俗解释什么叫计算机指令?

实际上能接触到“计算机指令”的人&#xff0c;只是少数电脑工程师。现在一般的电脑程序员都已经无需使用计算机指令了&#xff0c;因为他们编程序已经使用高级的计算机语言了。下面我尽量用通俗的语言来试着解释。计算机由CPU、内存、硬盘、显示器和键盘等部件组成。计算机软件…

JAVA_Thread_deadlock

package com.kk.thread;/* * 本类演示死锁的形成 * 基本数据类型是不能作为同步块的参考,例:int b;synchronized(b)*/public class TicketsSystem {public static void main(String[] args)throws Exception { SellThread sellnew SellThread();new Thread(sell).start(…

STM32和Arduino对比,谁更厉害?

前两天有一个同学问我嵌入式的学习路线他是一个大三的学生&#xff0c;我看了他的简历&#xff0c;里面几乎没什么项目经验&#xff0c;对于企业来说这样的学生就好比一张白纸一样&#xff0c;当然&#xff0c;这样的学生很难拿到一份好的offer。学习路线的文章我记得已经发了很…

窗体中实现按 回车键 跳到下一个可选的TabIndex控件

Form中一“textbox”&#xff0c;两“button”,如何实现在textbox中按下回车响应button.click事件 &#xff1a;1)把按钮的tabindex依次设置&#xff0e;如btnSure 1 ,btnModify 2, textbox 5等// 把下面的代码放到窗体中可以实现按回车键跳到下一个可选的TabIndex控件:protec…

技术支持

iOS技术支持 有问题的可以留言。 邮箱地址&#xff1a;838086119qq.com 地址&#xff1a;上海市复旦软件园 谢谢! iOS program design & system consultation if you have any question, please contact me with no hesitate Email: 838086119qq.com Add: 2B05 of Fudan So…

人大计算机在职考研好考吗,人大在职研究生好考吗?通过率高吗?

答&#xff1a;最近咨询人大在职研究生进行学习的人非常多&#xff0c;其中咨询最多的问题是考试难度及通过率。下面就通过在职研究生招生信息网为大家介绍一下&#xff0c;人大在职研究生好考吗?通过率高吗?人大在职研究生招生是采用同等学力申硕的方式&#xff0c;该方式是…

可能你还不懂浮点数

在网上看到一个问题然后看到这篇关于浮点数的文章&#xff0c;希望大家看了之后有所启发想一下&#xff0c;为什么第一个打印的和预设值不同&#xff0c;但是第二个是相同的&#xff1f;如图&#xff1a;尾数部分是如何转变成二进制的&#xff1f;前言很多人在初学写程式时都会…

股票自动交易使用协议

国家的法律规定其它人是不可能代替别人进行股票操作的。所以我们让用户使用股票自动交易软件的时候必须很清楚的让用户知道&#xff0c;他使用这个软件是他自己的意图&#xff0c;软件执行的策略也是它自己的策略&#xff0c;而不是我强加给他的。这样我们就需要写一个协议给用…

RTP协议的封装

最近一段时间学习了RTP协议相关的内容&#xff0c;一方面为了将自己学到的部分记录下来&#xff0c;便于后续查找&#xff0c;另一方面用于记录笔记 一个协议的封装是为了满足协议的功能需求的。从前面提出的功能需求&#xff0c;可以推测出RTP封装中应该有同步源和时戳等字段&…

【收集】ADOADO.NET 读取 Oracle 数据集

开始尝试用存储过程读取Oracle 数据集&#xff0c;收集了一些文章&#xff0c;基本上都来自MSDN&#xff1a;使用 ADO.NET 访问 Oracle 9i 存储过程 http://www.microsoft.com/china/MSDN/library/data/dataAccess/DMSDNorsps.mspx?mfrtrue如果包返回多个游标&#xff0c;则 D…

python 运行shell命令

在python 中实现运行多条shell命令 今天小编就为大家分享一篇在python 中实现运行多条shell命令&#xff0c;具有很好的参考价值&#xff0c;希望对大家有所帮助。 一起跟随小编过来看看吧 使用py时可能需要连续运行多条shell 命令 # coding: UTF-8 import sys reload(sys) sy…

组合公式计算机,(最新整理)排列与组合的概念与计算公式

《(最新整理)排列与组合的概念与计算公式》由会员分享&#xff0c;可在线阅读&#xff0c;更多相关《(最新整理)排列与组合的概念与计算公式(3页珍藏版)》请在人人文库网上搜索。1、完整)排列与组合的概念与计算公式(完整)排列与组合的概念与计算公式编辑整理&#xff1a;尊敬的…

sudo应用

sudo需求&#xff0c;公司程序员某些数据同步后需重启服务&#xff0c;给予root免登录权限固然简单&#xff0c;但存在太大的风险&#xff1b;所以我做了sudo限制&#xff0c;只允许用户从固定IP连接执行指定的命令&#xff0c;不需输入用户名 密码技术要点&#xff1a;sudo …

Alpha冲刺(7/10)

团队信息 队名&#xff1a;爸爸饿了组长博客&#xff1a;here作业博客&#xff1a;here组员情况 组员1&#xff08;组长&#xff09;&#xff1a;王彬 过去两天完成了哪些任务 学会了POSTMAN的使用&#xff0c;对后端已经完成的接口进行了收发消息正确性的验证推进项目进度&…

biztalk BLogs

http://biztalkdev.com/blogs/default.aspx http://www.biztalkgurus.com/tags/http/default.aspx http://tag.csdn.net/tag/biztalk.xml http://www.cnblogs.com/team/BiztalkSolution%20.html 转载于:https://www.cnblogs.com/lianyonglove/archive/2007/04/02/697270.html

epoll模型之服务器设计

Linux2.6内核中提高网络I/O性能的新方法-epoll I/O多路复用技术在比较多的TCP网络服务器中有使用&#xff0c;即比较多的用到select函数。1、为什么select落后首先&#xff0c;在Linux内核中&#xff0c;select所用到的FD_SET是有限的&#xff0c;即内核中有个参数__FD_SETSIZE…

服务器分虚拟空间,服务器怎样分虚拟主机

自己操作的话&#xff0c;首先有一个固定ip&#xff0c;做主机的电脑可以24小时开机。装上服务器软件&#xff0c;可以装 IIS 或者 linux/bsdapache。数据库的话是看你的网页设计需要的&#xff0c;如果有数据库开发的动态网页&#xff0c;那就必须装了。最好是专用服务的web服…

AIX 用户管理

http://www.ibm.com/developerworks/cn/aix/library/au-aixuseradmin/

不限学历、不限学校、华为天才少年招聘

我在前同事的朋友圈看到的招聘信息。不限学历&#xff0c;不限学校我相信这个规则一定会让后续的很多企业效仿&#xff0c;工作至今&#xff0c;遇到很多能力很强但是学历一般的人&#xff0c;而对于面试者&#xff0c;可以大胆的说出那句话&#xff0c;人家华为都不限制学校学…