• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > C#创建自签名认证文件的方法

C#创建自签名认证文件的方法

作者:jiangzhenyu 字体:[增加 减小] 来源:互联网 时间:2017-05-28

jiangzhenyu 通过本文主要向大家介绍了马桶c的个人空间,c语言,欲情 c max,维生素c,奔驰c200等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

本文实例讲述了C#创建自签名认证文件的方法。分享给大家供大家参考。具体如下:

using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using SecureString = System.Security.SecureString;
using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers;
internal class Certificate
{
 public static byte[] CreateSelfSignCertificatePfx(
  string x500,
  DateTime startTime,
  DateTime endTime)
 {
  byte[] pfxData = CreateSelfSignCertificatePfx(
   x500,
   startTime,
   endTime,
   (SecureString)null);
  return pfxData;
 }
 public static byte[] CreateSelfSignCertificatePfx(
  string x500,
  DateTime startTime,
  DateTime endTime,
  string insecurePassword)
 {
  byte[] pfxData;
  SecureString password = null;
  try
  {
   if (!string.IsNullOrEmpty(insecurePassword))
   {
    password = new SecureString();
    foreach (char ch in insecurePassword)
    {
     password.AppendChar(ch);
    }
    password.MakeReadOnly();
   }
   pfxData = CreateSelfSignCertificatePfx(
    x500,
    startTime,
    endTime,
    password);
  }
  finally
  {
   if (password != null)
   {
    password.Dispose();
   }
  }
  return pfxData;
 }
 public static byte[] CreateSelfSignCertificatePfx(
  string x500,
  DateTime startTime,
  DateTime endTime,
  SecureString password)
 {
  byte[] pfxData;
  if (x500 == null)
  {
   x500 = "";
  }
  SystemTime startSystemTime = ToSystemTime(startTime);
  SystemTime endSystemTime = ToSystemTime(endTime);
  string containerName = Guid.NewGuid().ToString();
  GCHandle dataHandle = new GCHandle();
  IntPtr providerContext = IntPtr.Zero;
  IntPtr cryptKey = IntPtr.Zero;
  IntPtr certContext = IntPtr.Zero;
  IntPtr certStore = IntPtr.Zero;
  IntPtr storeCertContext = IntPtr.Zero;
  IntPtr passwordPtr = IntPtr.Zero;
  RuntimeHelpers.PrepareConstrainedRegions();
  try
  {
   Check(NativeMethods.CryptAcquireContextW(
    out providerContext,
    containerName,
    null,
    1, // PROV_RSA_FULL
    8)); // CRYPT_NEWKEYSET
   Check(NativeMethods.CryptGenKey(
    providerContext,
    1, // AT_KEYEXCHANGE
    1, // CRYPT_EXPORTABLE
    out cryptKey));
   IntPtr errorStringPtr;
   int nameDataLength = 0;
   byte[] nameData;
   // errorStringPtr gets a pointer into the middle of the x500 string,
   // so x500 needs to be pinned until after we've copied the value
   // of errorStringPtr.
   dataHandle = GCHandle.Alloc(x500, GCHandleType.Pinned);
   if (!NativeMethods.CertStrToNameW(
    0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
    dataHandle.AddrOfPinnedObject(),
    3, // CERT_X500_NAME_STR = 3
    IntPtr.Zero,
    null,
    ref nameDataLength,
    out errorStringPtr))
   {
    string error = Marshal.PtrToStringUni(errorStringPtr);
    throw new ArgumentException(error);
   }
   nameData = new byte[nameDataLength];
   if (!NativeMethods.CertStrToNameW(
    0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
    dataHandle.AddrOfPinnedObject(),
    3, // CERT_X500_NAME_STR = 3
    IntPtr.Zero,
    nameData,
    ref nameDataLength,
    out errorStringPtr))
   {
    string error = Marshal.PtrToStringUni(errorStringPtr);
    throw new ArgumentException(error);
   }
   dataHandle.Free();
   dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned);
   CryptoApiBlob nameBlob = new CryptoApiBlob(
    nameData.Length,
    dataHandle.AddrOfPinnedObject());
   CryptKeyProviderInformation kpi = new CryptKeyProviderInformation();
   kpi.ContainerName = containerName;
   kpi.ProviderType = 1; // PROV_RSA_FULL
   kpi.KeySpec = 1; // AT_KEYEXCHANGE
   certContext = NativeMethods.CertCreateSelfSignCertificate(
    providerContext,
    ref nameBlob,
    0,
    ref kpi,
    IntPtr.Zero, // default = SHA1RSA
    ref startSystemTime,
    ref endSystemTime,
    IntPtr.Zero);
   Check(certContext != IntPtr.Zero);
   dataHandle.Free();
   certStore = NativeMethods.CertOpenStore(
    "Memory", // sz_CERT_STORE_PROV_MEMORY
    0,
    IntPtr.Zero,
    0x2000, // CERT_STORE_CREATE_NEW_FLAG
    IntPtr.Zero);
   Check(certStore != IntPtr.Zero);
   Check(NativeMethods.CertAddCertificateContextToStore(
    certStore,
    certContext,
    1, // CERT_STORE_ADD_NEW
    out storeCertContext));
   NativeMethods.CertSetCertificateContextProperty(
    storeCertContext,
    2, // CERT_KEY_PROV_INFO_PROP_ID
    0,
    ref kpi);
   if (password != null)
   {
    passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password);
   }
   CryptoApiBlob pfxBlob = new CryptoApiBlob();
   Check(NativeMethods.PFXExportCertStoreEx(
    certStore,
    ref pfxBlob,
    passwordPtr,
    IntPtr.Zero,
    7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
   pfxData = new byte[pfxBlob.DataLength];
   dataHandle = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
   pfxBlob.Data = dataHandle.AddrOfPinnedObject();
   Check(NativeMethods.PFXExportCertStoreEx(
    certStore,
    ref pfxBlob,
    passwordPtr,
    IntPtr.Zero,
    7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
   dataHandle.Free();
  }
  finally
  {
   if (passwordPtr != IntPtr.Zero)
   {
    Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
   }
   if (dataHandle.IsAllocated)
   {
    dataHandle.Free();
   }
   if (certContext != IntPtr.Zero)
   {
    NativeMethods.CertFreeCertificateContext(certContext);
   }
   if (storeCertContext != IntPtr.Zero)
   {
    NativeMethods.CertFreeCertificateContext(storeCertContext);
   }
   if (certStore != IntPtr.Zero)
   {
    NativeMethods.CertCloseStore(certStore, 0);
   }
   if (cryptKey != IntPtr.Zero)
   {
    NativeMethods.CryptDestroyKey(cryptKey);
   }
   if (providerContext != IntPtr.Zero)
   {
    NativeMethods.CryptReleaseContext(providerContext, 0);
    NativeMethods.CryptAcquireContextW(
     out providerContext,
     containerName,
     null,
     1, // PROV_RSA_FULL
     0x10); // CRYPT_DELETEKEYSET
   }
  }
  return pfxData;
 }
 private static SystemTime ToSystemTime(DateTime dateTime)
 {
  long fileTime = dateTime.ToFileTime();
  SystemTime systemTime;
  Check(NativeMethods.FileTimeToSystemTime(ref fileTime, out systemTime));
  return systemTime;
 }
 private static void Check(bool nativeCallSucceeded)
 {
  if (!nativeCallSucceeded)
  {
   int error = Marshal.GetHRForLastWin32Error();
   Marshal.ThrowExceptionForHR(error);
  }
 }
 [StructLayout(LayoutKind.Sequential)]
 private struct SystemTime
 {
  public short Year;
  public short Month;
  public short DayOfWeek;
  public short Day;
  public short Hour;
  public short Minute;
  public short Second;
  public short Milliseconds;
 }
 [StructLayout(LayoutKind.Sequential)]
 private struct CryptoApiBlob
 {
  public int DataLength;
  public IntPtr Data;
  public CryptoApiBlob(int dataLength, IntPtr data)
  {
   this.DataLength = dataLength;
   this.Data = data;
  }
 }
 [StructLayout(LayoutKind.Sequential)]
 private struct CryptKeyProviderInformation
 {
  [MarshalAs(UnmanagedType.LPWStr)] public string ContainerName;
  [MarshalAs(UnmanagedType.LPWStr)] public string ProviderName;
  public int ProviderType;
  public int Flags;
  public int ProviderParameterCount;
  public IntPtr ProviderParameters; // PCRYPT_KEY_PROV_PARAM
  public int KeySpec;
 }
 private static class NativeMethods
 {
  [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs(UnmanagedType.Bool)]
  public static extern bool FileTimeToSystemTime(
   [In] ref long fileTime,
   out SystemTime systemTime);
  [DllImport("AdvApi32.dll", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs(UnmanagedType.Bool)]
  public static extern bool CryptAcquireContextW(




 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • C#利用ReportViewer生成报表
  • C#基于正则去掉注释的方法示例
  • C#中new的用法及与override的区别分析
  • C#实现两个richtextbox控件滚动条同步滚动的简单方法
  • C# for循环的经典案例集锦
  • C#操作word的方法示例
  • C#使用WebClient登录网站并抓取登录后的网页信息实现方法
  • C# WinForm制作异形窗体与控件的方法
  • C#实现Excel表数据导入Sql Server数据库中的方法
  • C#使用NPOI上传excel

相关文章

  • 2017-05-28C#中面向对象编程机制之多态学习笔记
  • 2017-05-28C#实现按数据库邮件列表发送邮件的方法
  • 2017-05-28C#中调用命令行cmd开启wifi热点的实例代码
  • 2017-05-28c#中使用自动属性减少代码输入量
  • 2017-05-28winform 实现选择文件和选择文件夹对话框的简单实例
  • 2017-05-28C#实现DataTable映射成Model的方法(附源码)
  • 2017-05-28C#读取视频的宽度和高度等信息的方法
  • 2017-05-28C#关闭指定名字进程的方法
  • 2017-05-28C#中类与结构的区别实例分析
  • 2017-05-28C#中调用SAPI实现语音合成的2种方法

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • c#连接access数据库操作类分享
    • C#拷贝文件简单实现方法
    • c#定时器和global实现自动job示例
    • C#处理JPEG头信息的方法
    • C# Winform 实现屏蔽键盘的win和alt+F4的实现代码
    • C#中static void Main(string[] args) 参数示例详解
    • c#和javascript函数相互调用示例分享
    • C#在后台运行操作(BackgroundWorker用法)示例分享
    • 利用多线程句柄设置鼠标忙碌状态的实现方法
    • C#静态构造函数用法实例分析

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有