当前位置:首页>网络学院>程序开发>ASP.NET教程>文章内容

VS2008椭圆曲线签名(ECDSA)

[ 来源:http://www.it55.com | 作者: | 时间:2008-01-03 | 收藏 | 推荐 ] 【

椭圆曲线签名(ECDSA)相对传统签名算法具有速度快、强度高、签名短等优点。VS2008 中提供了椭圆曲线签名(ECDSA),遗憾的是 VS2008 提供的椭圆曲线签名目前只能在 Windwos Vista 上使用。
  
   椭圆曲线签名(ECDSA)的工作原理与大多数签名算法类似,都是使用私钥进行签名,使用公钥进行验证。其模式与其他托管加密类相同,只是椭圆曲线签名(ECDSA)密钥存储在 CNG 中。使用 CNG 您可以安全地存储密钥对、公钥并使用简单的字符串名称对其进行引用;使用 CngKey 类对密钥进行打开、创建、删除和导出等操作。
  
  public class ECDSALibrary
  {
   public static void Test()
   {
   // 密钥名称
   string keyName = "Anjou's ECDSA Key";
   // 公钥,私钥
   byte[] publicKeyBytes, privateKeyBytes;
  
   CngKey cngKey;
   // 打开密钥
   if (CngKey.Exists(keyName))
   {
   cngKey = CngKey.Open(keyName);
   //cngKey.Delete();
   }
   // 生成密钥
   else
   {
   CngKeyCreationParameters creationParameters = new CngKeyCreationParameters();
   // 允许以明文的形式导出私钥
   creationParameters.ExportPolicy = CngExportPolicies.AllowPlaintextExport;
   // 使用 ECDsaP256,ECDsaP384,ECDsaP521 证书长度分别是 64 Bytes, 96 Bytes, 132 Bytes。
   cngKey = CngKey.Create(CngAlgorithm.ECDsaP256, keyName, creationParameters);
   }
  
   // 导出公钥
   publicKeyBytes = cngKey.Export(CngKeyBlobFormat.EccPublicBlob);
   // 导出私钥
   privateKeyBytes = cngKey.Export(CngKeyBlobFormat.EccPrivateBlob);
  
   // 签名数据
   byte[] data = Encoding.Unicode.GetBytes("这里是要签名的字符串。");
   // 签名
   byte[] signature = SignData(data, keyName);
   // 验证签名
   bool verified = VerifyData(data,signature,publicKeyBytes);
   }
  
  
   /// <summary>
   /// 使用私钥签名
   /// </summary>
   public static byte[] SignData(byte[] data, string keyName)
   {
   // 打开密钥
   CngKey cngKey = CngKey.Open(keyName);
   // 签名
   ECDsaCng ecdsa = new ECDsaCng(cngKey);
   byte[] signature = ecdsa.SignData(data);
   ecdsa.Clear();
   cngKey.Dispose();
   return signature;
   }
  
   /// <summary>
   /// 使用公钥验证签名
   /// </summary>
   public static bool VerifyData(byte[] data, byte[] signature, byte[] publicKey)
   {
   bool verified = false;
   // 导入公钥
   CngKey cngKey = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob);
   // 验证签名
   ECDsaCng ecdsa = new ECDsaCng(cngKey);
   verified = ecdsa.VerifyData(data, signature);
   ecdsa.Clear();
   cngKey.Dispose();
   return verified;
   }
  }

(编辑:IT资讯之家 www.it55.com

返回顶部
 

网友评论

[以下评论为网友观点,不代表本站。请自觉遵守互联网相关政策法规,所有连带责任均有评论者自负。]
[不超过250字]