• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Cryptography.CspParameters类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Security.Cryptography.CspParameters的典型用法代码示例。如果您正苦于以下问题:C# CspParameters类的具体用法?C# CspParameters怎么用?C# CspParameters使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CspParameters类属于System.Security.Cryptography命名空间,在下文中一共展示了CspParameters类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Decrypt

        public static string Decrypt(this string stringToDecrypt, string key)
        {
            if (string.IsNullOrEmpty(stringToDecrypt))
            {
                throw new ArgumentException("An empty string value cannot be encrypted.");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
            }

            //var cspp = new CspParameters { KeyContainerName = key };
            var cspp = new CspParameters { KeyContainerName = key, Flags = CspProviderFlags.UseMachineKeyStore };

            var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true };

            var decryptArray = stringToDecrypt.Split(new[] { "-" }, StringSplitOptions.None);
            var decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));


            byte[] bytes = rsa.Decrypt(decryptByteArray, true);

            string result = System.Text.Encoding.UTF8.GetString(bytes);

            return result;
        }
开发者ID:raminmjj,项目名称:SportsSystem,代码行数:27,代码来源:SecurityExtensions.cs


示例2: CapiContext

	// Create an instance using the specified CSP
	public CapiContext (CspParameters csp) 
	{
		providerHandle = IntPtr.Zero;
		if (csp == null) {
			// default parameters
			cspParams = new CspParameters ();
		}
		else {
			// keep of copy of the parameters
			cspParams = new CspParameters (csp.ProviderType, csp.ProviderName, csp.KeyContainerName);
			cspParams.KeyNumber = csp.KeyNumber;
			cspParams.Flags = csp.Flags;
		}
		
		// do not show user interface (CRYPT_SILENT) -  if UI is required then the function fails.
		uint flags = CryptoAPI.CRYPT_SILENT;
		if ((cspParams.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore) {
			flags |= CryptoAPI.CRYPT_MACHINE_KEYSET;
		}

		lastResult = CryptoAPI.CryptAcquireContextA (ref providerHandle, cspParams.KeyContainerName,
			cspParams.ProviderName, cspParams.ProviderType, flags);
		if (!lastResult) {
			// key container may not exist
			flags |= CryptoAPI.CRYPT_NEWKEYSET;
			lastResult = CryptoAPI.CryptAcquireContextA (ref providerHandle, cspParams.KeyContainerName,
				cspParams.ProviderName, cspParams.ProviderType, flags);
		}
	}
开发者ID:REALTOBIZ,项目名称:mono,代码行数:30,代码来源:CapiContext.cs


示例3: PasswordDeriveBytes

 public PasswordDeriveBytes (byte[] password, byte[] salt, String hashName, int iterations, CspParameters cspParams) {
     this.IterationCount = iterations;
     this.Salt = salt;
     this.HashName = hashName;
     _password = password;
     _cspParams = cspParams;
 }
开发者ID:l1183479157,项目名称:coreclr,代码行数:7,代码来源:PasswordDeriveBytes.cs


示例4: Main

        static void Main(string[] args)
        {
            var cspParam = new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey,
            KeyContainerName = "FreeStreamingKeyStore"};
            var keyStore = new RsaKeyStore(cspParam);

                Peer peer1 = new Peer(38412, true, keyStore);
            peer1.ApplicationJoined += new CloudRegistrationEventHandler(OnApplicationJoined);
            peer1.ApplicationDetected += new CloudRegistrationEventHandler(OnApplicationDetected);
            peer1.ApplicationLeaved += new CloudRegistrationEventHandler(OnApplicationLeaved);
            peer1.UserMessageReceived += new UserMessageReceivedEventHandler(OnUserMessageReceived);
            peer1.RegisterInCloud();

                //Peer peer2 = new Peer(10001, true, keyStore);
                //peer2.ApplicationJoined += new CloudRegistrationEventHandler(OnApplication2Joined);
                //peer2.ApplicationDetected += new CloudRegistrationEventHandler(OnApplication2Detected);
                //peer2.ApplicationLeaved += new CloudRegistrationEventHandler(OnApplication2Leaved);
                //peer2.UserMessageReceived += new UserMessageReceivedEventHandler(OnUserMessage2Received);
                //peer2.RegisterInCloud();

            Thread.Sleep(1000);

            //peer1.SendData(new byte[100]);
            //peer1.SendData(new byte[200]);
            //peer1.SendData(new byte[300]);
            //peer1.SendData(new byte[100000]);

            Thread.Sleep(1000);
            peer1.Dispose();
            //peer2.Dispose();

            Console.WriteLine("..");
            Console.ReadLine();
        }
开发者ID:leon737,项目名称:Peer-2-Peer-Library,代码行数:34,代码来源:Program.cs


示例5: AssignNewKey

        public void AssignNewKey()
        {
            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                rsa.PersistKeyInCsp = false;
                //in memory
                publicKey = rsa.ExportParameters(false);
                privateKey = rsa.ExportParameters(true);
                return;

                //to file
                File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\public.txt", rsa.ToXmlString(false));
                File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\private.txt", rsa.ToXmlString(true));
            }

            //To key container, stored for windows user
            const int providerRsaFull = 1;
            CspParameters cspParams = new CspParameters(providerRsaFull);
            cspParams.KeyContainerName = "TomsContainer";
            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
            var rsa2 = new RSACryptoServiceProvider(cspParams);
            rsa2.PersistKeyInCsp = true;

            // SHOULD THEN DELETE KEY
        }
开发者ID:tomasking,项目名称:CryptographyDemo,代码行数:26,代码来源:AsymmetricEncryption.cs


示例6: GenerateKeys

        /// <summary>
        /// Generate keys into specified files.
        /// </summary>
        /// <param name="publicKeyFileName">Name of the file that will contain public key</param>
        /// <param name="privateKeyFileName">Name of the file that will contain private key</param>
        public void GenerateKeys(out byte[] publicKey, out byte[] privateKey)
        {
            // Variables
            CspParameters cspParams = null;
            RSACryptoServiceProvider rsaProvider = null;

            try
            {
                // Create a new key pair on target CSP
                cspParams = new CspParameters()
                {
                    ProviderType = 1,                          // PROV_RSA_FULL
                    Flags = CspProviderFlags.UseArchivableKey, // can be exported
                    KeyNumber = (int)KeyNumber.Exchange        // can be safely stored and exchanged
                };

                rsaProvider = new RSACryptoServiceProvider(cspParams);
                rsaProvider.PersistKeyInCsp = false;

                // Export public key only
                publicKey = rsaProvider.ExportCspBlob(false);
                privateKey = rsaProvider.ExportCspBlob(true);
            }
            catch (Exception ex)
            {
                Debug.Fail(string.Format("Exception occured while generating keys: {0}", ex.Message));
                publicKey = null;
                privateKey = null;
            }
            finally
            {
                if (rsaProvider != null) rsaProvider.PersistKeyInCsp = false;
            }
        }
开发者ID:fluxit,项目名称:SpaceEngineers,代码行数:39,代码来源:MyRSA.cs


示例7: ProcessRequest

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            CspParameters csp = new CspParameters();
            csp.Flags = CspProviderFlags.UseMachineKeyStore;

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
            RSAParameters para = rsa.ExportParameters(true);
            StringBuilder model = new StringBuilder();
            for (int i = 0; i < para.Modulus.Length; i++)
            {
                model.Append(para.Modulus[i].ToString("X2"));
            }

            StringBuilder exponent = new StringBuilder();
            for (int i = 0; i <para.Exponent.Length; i ++)
            {
                exponent.Append(para.Exponent[i].ToString("X2"));
            }

            XElement list = new XElement("list");
            XElement pri = new XElement("private", new XAttribute("key", rsa.ToXmlString(true)));
            XElement pub = new XElement("public", new XAttribute("model", model.ToString()),new XAttribute("exponent",exponent.ToString()));
            list.Add(pri);
            list.Add(pub);
            context.Response.Write(list.ToString());
        }
开发者ID:vancourt,项目名称:BaseGunnyII,代码行数:27,代码来源:KeyGenerator.ashx.cs


示例8: CryptKeys

 public CryptKeys()
 {
     Container = "ShareXmod";
     cp = new CspParameters();
     cp.KeyContainerName = Container;
     GenerateKey();
 }
开发者ID:dmitriydel,项目名称:sharexmod,代码行数:7,代码来源:CryptKeys.cs


示例9: Encryptor

        /// <summary>
        ///     Public constructor.
        /// </summary>
        public Encryptor()
        {
            string pass = Esapi.SecurityConfiguration.MasterPassword;
            byte[] salt = Esapi.SecurityConfiguration.MasterSalt;

            try
            {
                // Set up encryption and decryption
                using (SymmetricAlgorithm symmetricAlgorithm = SymmetricAlgorithm.Create(this.encryptAlgorithm))
                {
                    using (Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(pass, salt))
                    {
                        this.secretKey = rfc2898.GetBytes(symmetricAlgorithm.KeySize / 8);
                    }
                    // TODO: Hardcoded value 13 is the code for DSA
                    this.asymmetricKeyPair = new CspParameters(13);

                    // The asymmetric key will be stored in the key container using the name ESAPI.
                    this.asymmetricKeyPair.KeyContainerName = "ESAPI";
                }
            }
            catch (Exception e)
            {
                throw new EncryptionException(EM.Encryptor_EncryptionFailure, EM.Encryptor_EncryptorCreateFailed, e);
            }
        }
开发者ID:jstemerdink,项目名称:owasp-esapi-dotnet,代码行数:29,代码来源:Encryptor.cs


示例10: RSADeleteKeyInCSP

        public static void RSADeleteKeyInCSP(string ContainerName)
        {
            try
            {
                // Create a new instance of CspParameters.  Pass
                // 13 to specify a DSA container or 1 to specify
                // an RSA container.  The default is 1.
                CspParameters cspParams = new CspParameters();

                // Specify the container name using the passed variable.
                cspParams.KeyContainerName = ContainerName;

                //Create a new instance of RSACryptoServiceProvider.
                //Pass the CspParameters class to use the
                //key in the container.
                RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(cspParams);

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

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

                //Indicate that the key was persisted.
                Console.WriteLine("The RSA key was deleted from the container, \"{0}\".", ContainerName);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

            }
        }
开发者ID:277594531,项目名称:RSACSPSample,代码行数:32,代码来源:Program.cs


示例11: DecryptRSA

        public static byte[] DecryptRSA(byte[] data, byte[] key)
        {
            var csp     = new CspParameters();
            csp.Flags   = CspProviderFlags.UseMachineKeyStore;

            using (var rsa  = new RSACryptoServiceProvider(_dwSize, csp))
            using (var ms   = new MemoryStream())
            {
                //Create seed, create RSA blob, replace logic
                rsa.ImportCspBlob(key);

                for (int i = 0; i < data.Length; i += _chunkSize)
                {
                    int amount = Math.Min(_chunkSize, data.Length - i);
                    byte[] buffer = new byte[amount];

                    Buffer.BlockCopy(data, i, buffer, 0, amount);

                    byte[] decrypted = rsa.Decrypt(buffer, false);
                    ms.Write(decrypted, 0, decrypted.Length);
                }

                return ms.ToArray();
            }
        }
开发者ID:LordBlacksun,项目名称:Allegiance-Community-Security-System,代码行数:25,代码来源:Encryption.cs


示例12: Sigcreate

        public void Sigcreate(String name)
        {
            try
            {

                CspParameters cspParams = new CspParameters();
                cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

                RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(name);

                SignXml(xmlDoc, rsaKey);

                xmlDoc.Save(name);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
开发者ID:TinyNiko,项目名称:k3yManager,代码行数:25,代码来源:Aworks.cs


示例13: Common

		private void Common (int dwKeySize, CspParameters p) 
		{
			// Microsoft RSA CSP can do between 384 and 16384 bits keypair
			LegalKeySizesValue = new KeySizes [1];
			LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
			base.KeySize = dwKeySize;

			rsa = new RSAManaged (KeySize);
			rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);

			persistKey = (p != null);
			if (p == null) {
				p = new CspParameters (PROV_RSA_FULL);
#if NET_1_1
				if (useMachineKeyStore)
					p.Flags |= CspProviderFlags.UseMachineKeyStore;
#endif
				store = new KeyPairPersistence (p);
				// no need to load - it cannot exists
			}
			else {
				store = new KeyPairPersistence (p);
				bool exists = store.Load ();
				bool required = (p.Flags & CspProviderFlags.UseExistingKey) != 0;

				if (required && !exists)
					throw new CryptographicException ("Keyset does not exist");

				if (store.KeyValue != null) {
					persisted = true;
					this.FromXmlString (store.KeyValue);
				}
			}
		}
开发者ID:kumpera,项目名称:mono,代码行数:34,代码来源:RSACryptoServiceProvider.cs


示例14: Encryption

 static Encryption()
 {
     CspParameters CSPParam = new CspParameters();
     CSPParam.Flags = CspProviderFlags.UseMachineKeyStore;
     RsaProvider = new RSACryptoServiceProvider(CSPParam);
     RsaProvider.FromXmlString(xmlKey);
 }
开发者ID:XiaoQiJun,项目名称:BPS,代码行数:7,代码来源:Encryption.cs


示例15: CreateRSACryptoServiceProvider

 private static RSACryptoServiceProvider CreateRSACryptoServiceProvider()
 {
     CspParameters RSAParams = new CspParameters();
     RSAParams.Flags = CspProviderFlags.UseMachineKeyStore;
     RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider(RSAParams);
     return publicKey;
 }
开发者ID:BryanApellanes,项目名称:Naizari,代码行数:7,代码来源:RSAKeyPair.cs


示例16: SignN3Rsa

        public string SignN3Rsa(string data)
        {
            var cspParams = new CspParameters {KeyContainerName = "XML_DSIG_RSA_KEY"};
            var key = new RSACryptoServiceProvider(cspParams);
            var cspBlob = key.ExportCspBlob(false);
            var base64Blob = Convert.ToBase64String(cspBlob);

            var rsaFormatter = new RSAPKCS1SignatureFormatter(key);
            rsaFormatter.SetHashAlgorithm("MD5");

            var hash = Md5Helper.GetMd5Hash(data);
            var base64Hash = Convert.ToBase64String(hash);
            var sign = rsaFormatter.CreateSignature(hash);
            var base64Sign = Convert.ToBase64String(sign);

            var signData = new SignData
                           {
                               data = data,
                               public_key = base64Blob,
                               hash = base64Hash,
                               sign = base64Sign
                           };

            return new SerializationHelper<SignData>().Serialize(signData);
        }
开发者ID:nbIxMaN,项目名称:RestTest,代码行数:25,代码来源:SignatureHelper.cs


示例17: GetPrivateKey

        //
        // Returns the private key referenced by a store certificate. Note that despite the return type being declared "CspParameters",
        // the key can actually be a CNG key. To distinguish, examine the ProviderType property. If it is 0, this key is a CNG key with
        // the various properties of CspParameters being "repurposed" into storing CNG info. 
        // 
        // This is a behavior this method inherits directly from the Crypt32 CRYPT_KEY_PROV_INFO semantics.
        //
        // It would have been nice not to let this ugliness escape out of this helper method. But X509Certificate2.ToString() calls this 
        // method too so we cannot just change it without breaking its output.
        // 
        private CspParameters GetPrivateKey()
        {
            int cbData = 0;
            if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbData))
            {
                int dwErrorCode = Marshal.GetLastWin32Error();
                if (dwErrorCode == ErrorCode.CRYPT_E_NOT_FOUND)
                    return null;
                throw new CryptographicException(dwErrorCode);
            }

            unsafe
            {
                byte[] privateKey = new byte[cbData];
                fixed (byte* pPrivateKey = privateKey)
                {
                    if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, privateKey, ref cbData))
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    CRYPT_KEY_PROV_INFO* pKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pPrivateKey;

                    CspParameters cspParameters = new CspParameters();
                    cspParameters.ProviderName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszProvName));
                    cspParameters.KeyContainerName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszContainerName));
                    cspParameters.ProviderType = pKeyProvInfo->dwProvType;
                    cspParameters.KeyNumber = pKeyProvInfo->dwKeySpec;
                    cspParameters.Flags = (CspProviderFlags)((pKeyProvInfo->dwFlags & CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) == CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET ? CspProviderFlags.UseMachineKeyStore : 0);
                    return cspParameters;
                }
            }
        }
开发者ID:nelsonsar,项目名称:corefx,代码行数:40,代码来源:CertificatePal.PrivateKey.cs


示例18: CryptKeys

 public CryptKeys()
 {
     Container = Application.ProductName;
     cp = new CspParameters();
     cp.KeyContainerName = Container;
     GenerateKey();
 }
开发者ID:modulexcite,项目名称:ZScreen_Google_Code,代码行数:7,代码来源:CryptKeys.cs


示例19: GrabarClaveCompleta

		private void GrabarClaveCompleta(CspParameters cp, RSACryptoServiceProvider rsa)
		{
			StreamWriter s = new StreamWriter(cp.KeyContainerName + ".pubpriv.rsa");
			rsa.PersistKeyInCsp = false;
			s.WriteLine(rsa.ToXmlString(true));
			s.Close();
		}
开发者ID:pjeconde,项目名称:CedForecast,代码行数:7,代码来源:Cripto.cs


示例20: sign

        void sign()
        {
            try
            {
                // Create a new CspParameters object to specify 
                // a key container.
                CspParameters cspParams = new CspParameters();
                cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

                // Create a new RSA signing key and save it in the container. 
                RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

                // Create a new XML document.
                XmlDocument xmlDoc = new XmlDocument();

                // Load an XML file into the XmlDocument object.
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load("test.xml");

                // Sign the XML document. 
                SignXml(xmlDoc, rsaKey);

                Console.WriteLine("XML file signed.");

                // Save the document.
                xmlDoc.Save("test.xml");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
开发者ID:duyisu,项目名称:MissionPlanner,代码行数:32,代码来源:SignXML.cs



注:本文中的System.Security.Cryptography.CspParameters类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Cryptography.DESCryptoServiceProvider类代码示例发布时间:2022-05-26
下一篇:
C# Cryptography.CryptoStream类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap