コード例 #1
0
        /*キーコンテナ削除*/
        public static void DeleteKeys(string containerName)
        {
            //CspParametersオブジェクトの作成
            System.Security.Cryptography.CspParameters cp =
                new System.Security.Cryptography.CspParameters();
            //キーコンテナ名を指定する
            cp.KeyContainerName = containerName;
            //CspParametersを指定してRSACryptoServiceProviderオブジェクトを作成
            System.Security.Cryptography.RSACryptoServiceProvider rsa =
                new System.Security.Cryptography.RSACryptoServiceProvider(cp);

            //キーコンテナを削除
            rsa.PersistKeyInCsp = false;
            rsa.Clear();
        }
コード例 #2
0
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="byteArr_UTF8Content">加密内容</param>
        /// <param name="publickey">公钥(可空)</param>
        /// <returns>加密内容</returns>
        public static byte[] Encrypt(byte[] byteArr_UTF8Content, string publickey = "")
        {
            if (publickey.IsNullOrEmpty())
            {
                publickey = sPublicKey;
            }

            System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
            rsa.FromXmlString(publickey);

            int keySize    = rsa.KeySize / 8;
            int bufferSize = keySize - 11;

            byte[] buffer = new byte[bufferSize];

            byte[] r = null;
            using (System.IO.MemoryStream msInput = new System.IO.MemoryStream(byteArr_UTF8Content))
            {
                using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream())
                {
                    int readLen = msInput.Read(buffer, 0, bufferSize);
                    while (readLen > 0)
                    {
                        byte[] dataToEncrypt = new byte[readLen];
                        Array.Copy
                        (
                            sourceArray: buffer,
                            sourceIndex: 0,
                            destinationArray: dataToEncrypt,
                            destinationIndex: 0,
                            length: readLen
                        );

                        byte[] encrypted = rsa.Encrypt(rgb: dataToEncrypt, fOAEP: false);
                        msOutput.Write(encrypted, 0, encrypted.Length);
                        readLen = msInput.Read(buffer, 0, bufferSize);
                    }

                    r = msOutput.ToArray(); // 获得全部加密结果
                    rsa.Clear();
                }
            }

            return(r);
        }