Exemplo n.º 1
0
        public override void Run()
        {
            RSACryptoServiceProvider rsa = null;
            try
            {
                var cp = new CspParameters();
                cp.KeyContainerName = _containerName;
                cp.Flags = CspProviderFlags.UseMachineKeyStore;

                rsa = new RSACryptoServiceProvider(cp);
                rsa.FromXmlString(File.ReadAllText(_keyFile));
                rsa.PersistKeyInCsp = true;
                rsa.Clear();
            }
            catch (Exception)
            {
                if (rsa != null)
                {
                    rsa.PersistKeyInCsp = false;
                    rsa.Clear();
                }

                throw;
            }
        }
Exemplo n.º 2
0
        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);

            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Generate the keys (public and private)
 /// </summary>
 /// <param name="keyPubPri">Public and private key</param>
 /// <param name="keyPub">Public key</param>
 public static void GenerateKeys(out string keyPubPri, out string keyPub)
 {
     System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(1024);
     keyPubPri = rsa.ToXmlString(true);
     keyPub    = rsa.ToXmlString(false);
     rsa.Clear();
 }
	public RSACryptoServiceProviderTest () 
	{
		sha1OID = CryptoConfig.MapNameToOID ("SHA1");
		disposed = new RSACryptoServiceProvider (minKeySize);
		disposed.FromXmlString ("<RSAKeyValue><Modulus>vtXAf62+o50prNCTiVGTMzdhm4sMjK0QVDkKQLFGu2fJQCULt9NZBab14PiWfG1t</Modulus><Exponent>AQAB</Exponent><P>5y2AHOzIhTChIFzLsgZQAGfy3U8OPwFh</P><Q>01NUVJJv+hhIsnbFiSi24FLRrfr/qYuN</Q><DP>HKLAOdUCyazKaK3V9Yleo448wTkntJpB</DP><DQ>AH5MTxo8arAN02TVlzliG+n1lVtlp2at</DQ><InverseQ>ZpgJwTxSYpT81sQCuVUvX0AYrvSziNIw</InverseQ><D>CStiJYBmsZvincAj5qw5w3M8yGmE/9ls4yv7wenozzC4kZshpI2MuON0d2Z8f4aB</D></RSAKeyValue>");
		disposed.Clear ();
	}
Exemplo n.º 5
0
 /// <summary>
 /// ������˽Կ
 /// </summary>
 /// <param name="publicKey"></param>
 /// <param name="privatekey"></param>
 public void CreateKey(out string publicKey, out string privateKey)
 {
     RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
     publicKey = crypt.ToXmlString(false);
     privateKey = crypt.ToXmlString(true);
     crypt.Clear();
 }
 private static RSACryptoServiceProvider GenKeys(int keySize)
 {
     var parameters = new CspParameters();
     RSACryptoServiceProvider provider;
     parameters.Flags = CspProviderFlags.NoPrompt | CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey;
     parameters.KeyNumber = (int)KeyNumber.Exchange;
     parameters.KeyContainerName = System.Reflection.Assembly.GetEntryAssembly().FullName;
     try
     {
         //RSAHelper: Attempting to open existing key container
         provider = new RSACryptoServiceProvider(parameters);
         var pa = provider.ExportParameters(false);
         if (pa.Modulus.Length * 8 == keySize) return provider;
         //Found existing key, but not of the correct size
         provider.PersistKeyInCsp = false;
         provider.Clear();
         provider.Dispose();
         GenerateRsaKeys(parameters, keySize, out provider);
     }
     catch
     {
         //No existing Key Container was found in the machine keystore
         GenerateRsaKeys(parameters, keySize, out provider);
     }
     finally
     {
         GC.Collect();
         GC.WaitForPendingFinalizers();
     }
     return provider;
 }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            string KeyContainerName = "MyKeyContainer";
            string clearText = "This is the data we want to encrypt!";
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = KeyContainerName;

            RSAParameters publicKey;
            RSAParameters privateKey;

            using(var rsa = new RSACryptoServiceProvider(cspParams))
            {
                rsa.PersistKeyInCsp = true;
                publicKey = rsa.ExportParameters(false);
                privateKey = rsa.ExportParameters(true);

                rsa.Clear();
            }

            byte[] encrypted = EncryptUsingRSAParam(clearText, publicKey);
            string decrypted = DecryptUsingRSAParam(encrypted, privateKey);

            Console.WriteLine("Asymmetric RSA - Using RSA Params");
            Console.WriteLine("Encrypted:{0}", Convert.ToBase64String(encrypted));
            Console.WriteLine("Decrypted:{0}", decrypted);

            Console.WriteLine("Asymmetric RSA - Using Persistent Key Container");
            encrypted = EncryptUsingContainer(clearText, KeyContainerName);
            decrypted = DecryptUsingContainer(encrypted, KeyContainerName);

            Console.WriteLine("Encrypted:{0}", Convert.ToBase64String(encrypted));
            Console.WriteLine("Decrypted:{0}", decrypted);

            Console.ReadLine();
        }
Exemplo n.º 8
0
 /// <summary>
 /// Decrypts a string using RSA
 /// </summary>
 /// <param name="Input">Input string (should be small as anything over 128 bytes can not be decrypted)</param>
 /// <param name="Key">Key to use for decryption</param>
 /// <returns>A decrypted string</returns>
 public static string Decrypt(string Input, string Key)
 {
     RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
     RSA.FromXmlString(Key);
     byte[] InputArray = Convert.FromBase64String(Input);
     byte[] EncryptedBytes = RSA.Decrypt(InputArray, true);
     RSA.Clear();
     return Encoding.UTF8.GetString(EncryptedBytes);
 }
Exemplo n.º 9
0
 public static void Delete()
 {
     var cp = new CspParameters();
     cp.KeyContainerName = KeyContainerName;
     cp.Flags = CspProviderFlags.UseMachineKeyStore;
     var rsa = new RSACryptoServiceProvider(cp);
     rsa.PersistKeyInCsp = false; // Delete the key entry in the container.
     rsa.Clear();
 }
 /// <summary>
 /// 生成密钥
 /// </summary>
 public RSAKey GenerateRSAKey()
 {
     RSAKey RSAKEY = new RSAKey();
     RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
     RSAKEY.PrivateKey = RSA.ToXmlString(true);    //生成私钥
     RSAKEY.PublicKey = RSA.ToXmlString(false);    //生成公钥
     RSA.Clear();
     return RSAKEY;
 }
Exemplo n.º 11
0
		/// <summary>
		/// 得到私匙和公匙的信息,string[0]是私匙的信息,string[1]是公匙的信息
		/// </summary>
		/// <returns></returns>
		public static string[] GetKeyInfo()
		{
			string[] key=new string[2];
			RSACryptoServiceProvider crypt=new RSACryptoServiceProvider();
			key[0]=crypt.ToXmlString(true);
			key[1]=crypt.ToXmlString(false);
			crypt.Clear();  
			return key;
		}
Exemplo n.º 12
0
 /// <summary>
 /// Encrypts a string using RSA
 /// </summary>
 /// <param name="Input">Input string (should be small as anything over 128 bytes can not be decrypted)</param>
 /// <param name="Key">Key to use for encryption</param>
 /// <returns>An encrypted string (64bit string)</returns>
 public static string Encrypt(string Input, string Key)
 {
     RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
     RSA.FromXmlString(Key);
     ASCIIEncoding Encoding = new ASCIIEncoding();
     byte[] InputArray = Encoding.GetBytes(Input);
     byte[] EncryptedBytes = RSA.Encrypt(InputArray, true);
     RSA.Clear();
     return Convert.ToBase64String(EncryptedBytes);
 }
	public void FixtureSetUp () 
	{
		sha1OID = CryptoConfig.MapNameToOID ("SHA1");
		disposed = new RSACryptoServiceProvider (minKeySize);
		disposed.FromXmlString ("<RSAKeyValue><Modulus>vtXAf62+o50prNCTiVGTMzdhm4sMjK0QVDkKQLFGu2fJQCULt9NZBab14PiWfG1t</Modulus><Exponent>AQAB</Exponent><P>5y2AHOzIhTChIFzLsgZQAGfy3U8OPwFh</P><Q>01NUVJJv+hhIsnbFiSi24FLRrfr/qYuN</Q><DP>HKLAOdUCyazKaK3V9Yleo448wTkntJpB</DP><DQ>AH5MTxo8arAN02TVlzliG+n1lVtlp2at</DQ><InverseQ>ZpgJwTxSYpT81sQCuVUvX0AYrvSziNIw</InverseQ><D>CStiJYBmsZvincAj5qw5w3M8yGmE/9ls4yv7wenozzC4kZshpI2MuON0d2Z8f4aB</D></RSAKeyValue>");
		// FX 2.0 beta 1 bug - we must use the key before clearing it
		// http://lab.msdn.microsoft.com/ProductFeedback/viewfeedback.aspx?feedbackid=1bc807eb-c4ca-4c2d-8499-9f0470b71a29
		int ks = disposed.KeySize;
		disposed.Clear ();
	}
Exemplo n.º 14
0
        /// <summary>
        /// 
        /// </summary>
        void CifrarElemento()
        {
            // Create an XmlDocument object.
            XmlDocument xmlDoc = new XmlDocument();

            // Load an XML file into the XmlDocument object.
            try
            {
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load("ConfigurationManager.xml");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            // Create a new CspParameters object to specify
            // a key container.
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "XML_ENC_RSA_KEY";

            // Create a new RSA key and save it in the container.  This key will encrypt
            // a symmetric key, which will then be encryped in the XML document.
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

            try
            {
                // Encrypt the "creditcard" element.
                Encrypt(xmlDoc, "Groups", "EncryptedElement1", rsaKey, "rsaKey");


                // Save the XML document.
                xmlDoc.Save("ConfigurationManager.xml");

                
     

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // Clear the RSA key.
                rsaKey.Clear();
            }


         



        }
Exemplo n.º 15
0
        public static void Create()
        {
            var cp = new CspParameters();
            cp.KeyContainerName = KeyContainerName;
            cp.Flags = CspProviderFlags.UseMachineKeyStore;

            var rsa = new RSACryptoServiceProvider(cp);
            rsa.FromXmlString(XmlKey);
            rsa.PersistKeyInCsp = true;
            rsa.Clear();
        }
 /// <summary>
 /// Encrypts a string using RSA
 /// </summary>
 /// <param name="Input">Input string (should be small as anything over 128 bytes can not be decrypted)</param>
 /// <param name="Key">Key to use for encryption</param>
 /// <param name="EncodingUsing">Encoding that the input string uses (defaults to UTF8)</param>
 /// <returns>An encrypted string (64bit string)</returns>
 public static string Encrypt(string Input, string Key, Encoding EncodingUsing = null)
 {
     Input.ThrowIfNullOrEmpty("Input");
     Key.ThrowIfNullOrEmpty("Key");
     using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
     {
         RSA.FromXmlString(Key);
         byte[] EncryptedBytes = RSA.Encrypt(Input.ToByteArray(EncodingUsing), true);
         RSA.Clear();
         return EncryptedBytes.ToBase64String();
     }
 }
Exemplo n.º 17
0
 /// <summary>
 ///     Encrypts a string using RSA
 /// </summary>
 /// <param name="input">Input string (should be small as anything over 128 bytes can not be decrypted)</param>
 /// <param name="key">Key to use for encryption</param>
 /// <param name="encodingUsing">Encoding that the input string uses (defaults to UTF8)</param>
 /// <returns>An encrypted string (64bit string)</returns>
 public static string Encrypt(string input, string key, Encoding encodingUsing = null)
 {
     Guard.NotEmpty(input, "input");
     Guard.NotEmpty(key, "key");
     using (var rsa = new RSACryptoServiceProvider())
     {
         rsa.FromXmlString(key);
         byte[] encryptedBytes = rsa.Encrypt(input.ToByteArray(encodingUsing), true);
         rsa.Clear();
         return encryptedBytes.ToBase64String();
     }
 }
Exemplo n.º 18
0
 /// <summary>
 /// Decrypts a string using RSA
 /// </summary>
 /// <param name="Input">Input string (should be small as anything over 128 bytes can not be decrypted)</param>
 /// <param name="Key">Key to use for decryption</param>
 /// <param name="EncodingUsing">Encoding that the result should use (defaults to UTF8)</param>
 /// <returns>A decrypted string</returns>
 public static string Decrypt(string Input, string Key, Encoding EncodingUsing = null)
 {
     Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Key), "Key");
     Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Input), "Input");
     using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
     {
         RSA.FromXmlString(Key);
         byte[] EncryptedBytes = RSA.Decrypt(Input.FromBase64(), true);
         RSA.Clear();
         return EncryptedBytes.ToString(EncodingUsing);
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Computes a hash value of the string, and signs the resulting hash value with the RSA private key supplied.
        /// </summary>
        /// <param name="plaintext">The plaintext.</param>
        /// <param name="rsaKey">The RSA private key.</param>
        /// <returns>The base64 encoded signed hash string.</returns>
        public static string RSASign(this string plaintext, RSAParameters rsaKey)
        {
            if (string.IsNullOrEmpty(plaintext))
                throw new ArgumentNullException("plaintext", "Cannot sign an empty string.");

            byte[] plainTextBuffer = UTF8Encoding.UTF8.GetBytes(plaintext);
            var rsaProvider = new RSACryptoServiceProvider();
            rsaProvider.ImportParameters(rsaKey);
            byte[] signedHashBuffer = rsaProvider.SignData(plainTextBuffer, new SHA1CryptoServiceProvider());
            rsaProvider.Clear();
            return Convert.ToBase64String(signedHashBuffer);
        }
Exemplo n.º 20
0
        static string DecryptUsingRSAParam(byte[] encryptedData, RSAParameters rsaKeyInfo)
        {
            using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaKeyInfo);
                byte[] decryptedData = rsa.Decrypt(encryptedData, true);
                string decryptedValue = Encoding.Default.GetString(decryptedData);

                rsa.Clear();
                return decryptedValue;
            }
        }
Exemplo n.º 21
0
        static byte[] EncryptUsingRSAParam(string value, RSAParameters rsaKeyInfo)
        {
            using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaKeyInfo);
                byte[] encodedData = Encoding.Default.GetBytes(value);
                byte[] encryptedData = rsa.Encrypt(encodedData, true);

                rsa.Clear();
                return encryptedData;
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Encrypts a string using RSA
 /// </summary>
 /// <param name="Input">
 /// Input byte array (should be small as anything over 128 bytes can not be decrypted)
 /// </param>
 /// <param name="Key">Key to use for encryption</param>
 /// <returns>An encrypted byte array (64bit string)</returns>
 public override byte[] Encrypt(byte[] Input, string Key)
 {
     Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Key), "Key");
     Contract.Requires<ArgumentNullException>(Input != null, "Input");
     using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
     {
         RSA.FromXmlString(Key);
         byte[] EncryptedBytes = RSA.Encrypt(Input, true);
         RSA.Clear();
         return EncryptedBytes;
     }
 }
Exemplo n.º 23
0
        public static void Main(string[] args)
        {
            try
            {
                new TAppSettingsManager(false);
                CspParameters cp = new CspParameters();
                cp.KeyContainerName = "OpenPetraServerKeyContainer";

                // first make sure, we really get a new key
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cp);
                RSA.PersistKeyInCsp = false;
                RSA.Clear();

                // now create the new key
                RSACryptoServiceProvider RSANew = new RSACryptoServiceProvider(cp);

                string PublicKeyFile = TAppSettingsManager.GetValue("PublicKeyFile", "", false);

                if (PublicKeyFile.Length > 0)
                {
                    StreamWriter sw = new StreamWriter(PublicKeyFile);
                    sw.WriteLine(RSANew.ToXmlString(false));
                    sw.Close();
                    Console.WriteLine("public key has been written to " + PublicKeyFile);
                }
                else
                {
                    Console.WriteLine("public key only: ");
                    Console.WriteLine(RSANew.ToXmlString(false));
                }

                string PrivateKeyFile = TAppSettingsManager.GetValue("PrivateKeyFile", "", false);

                if (PrivateKeyFile.Length > 0)
                {
                    StreamWriter sw = new StreamWriter(PrivateKeyFile);
                    sw.WriteLine(RSANew.ToXmlString(true));
                    sw.Close();
                    Console.WriteLine("private key has been written to " + PrivateKeyFile);
                }
                else
                {
                    Console.WriteLine("Private key with public key: ");
                    Console.WriteLine(RSANew.ToXmlString(true));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("error: " + e.Message);
                Console.WriteLine("error: " + e.StackTrace);
            }
        }
Exemplo n.º 24
0
        //RSA
        public static byte[] RSAEnc(byte[] data, byte[] key)
        {
            var keyParser = new AsnKeyParser(key);
            var publicKey = keyParser.ParseRSAPublicKey();

            var csp = new CspParameters {ProviderType = 1, KeyNumber = 1};

            var rsa = new RSACryptoServiceProvider(csp) {PersistKeyInCsp = false};
            rsa.ImportParameters(publicKey);
            byte[] enc = rsa.Encrypt(data, false);
            rsa.Clear();
            return enc;
        }
Exemplo n.º 25
0
        static string DecryptUsingContainer(byte[] encryptedData, string containerName)
        {
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = containerName;
            using(var rsa = new RSACryptoServiceProvider(cspParams))
            {
                byte[] decryptedData = rsa.Decrypt(encryptedData, true);
                string decryptedValue = Encoding.Default.GetString(decryptedData);

                rsa.Clear();
                return decryptedValue;
            }
        }
Exemplo n.º 26
0
        static byte[] EncryptUsingContainer(string value, string containerName)
        {
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = containerName;
            using(var rsa = new RSACryptoServiceProvider(cspParams))
            {
                byte[] encodedData = System.Text.Encoding.Default.GetBytes(value);
                byte[] encryptedData = rsa.Encrypt(encodedData, true);

                rsa.Clear();
                return encryptedData;
            }
        }
Exemplo n.º 27
0
        public static void DeleteKeyFromContainer(string ContainerName)
        {
            CspParameters csp = new CspParameters();
            csp.KeyContainerName = ContainerName;

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);

            rsa.PersistKeyInCsp = false;

            rsa.Clear();

            Console.WriteLine("Key deleted");
        }
 private static void Clear(string keyName)
 {
     var csp = new CspParameters
     {
         KeyContainerName = keyName,
         Flags = CspProviderFlags.UseMachineKeyStore
     };
     using (var provider = new RSACryptoServiceProvider(csp))
     {
         provider.PersistKeyInCsp = false;
         provider.Clear();
     }
 }
Exemplo n.º 29
0
        public override void Run()
        {
            var cp = new CspParameters();
            if(_containerName != null)
                cp.KeyContainerName = _containerName;
            cp.Flags = CspProviderFlags.UseMachineKeyStore;

            var rsa = new RSACryptoServiceProvider(_keySize, cp);
            if (_keyFile != null)
                File.WriteAllText(_keyFile, rsa.ToXmlString(true));
            rsa.PersistKeyInCsp = (_containerName != null);
            rsa.Clear();
        }
Exemplo n.º 30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Response.Write("test");
            Response.Write("md5 32位加密:"+MD5Helper.Get32Md5("1"));
            Response.Write("<br/>");
            Response.Write("RSA加密算法!!#####@@~~");

            RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
            string publickey = crypt.ToXmlString(false);//公钥
            string privatekey = crypt.ToXmlString(true);//私钥

            crypt.Clear();

            StreamWriter one = new StreamWriter(Server.MapPath("a.txt"), true, UTF8Encoding.UTF8);
            one.Write(publickey);
            StreamWriter two = new StreamWriter(Server.MapPath("b.txt"), true, UTF8Encoding.UTF8);
            two.Write(privatekey);
            one.Flush();
            two.Flush();
            one.Close();
            two.Close();

            //=================================
            StreamReader sr = new StreamReader(Server.MapPath("a.txt"), UTF8Encoding.UTF8);
            string readpublickey = sr.ReadToEnd(); //包含 RSA 密钥信息的 XML 字符串。
            sr.Close();
            UTF8Encoding enc = new UTF8Encoding();
            byte[] bytes = enc.GetBytes("Just2");
            RSACryptoServiceProvider crypt2 = new RSACryptoServiceProvider();
            crypt2.FromXmlString(readpublickey);
            bytes = crypt2.Encrypt(bytes, false);
            string encryttext = Convert.ToBase64String(bytes);
            string abb = Server.UrlEncode(encryttext);
            Response.Write("<br/>");
            Response.Write("密文为:" + abb);

            //=================================
            StreamReader sr3 = new StreamReader(Server.MapPath("b.txt"), UTF8Encoding.UTF8);
            string readprivatekey = sr3.ReadToEnd();
            sr3.Close();
            RSACryptoServiceProvider crypt3 = new RSACryptoServiceProvider();
            UTF8Encoding enc3 = new UTF8Encoding();
            string sss = "BCOyV%2bmK7u8Gp26JZ2qeEXzZM8ColhiYMa1e992ojU6dPTWWIFVqLAb60%2b5Yt4rl7aw%2f8ZJltZck4ftKkSc%2fXYQZP7OM2wmQn6U6QeYF84Hi1jhT4abYoXAMRyxPfR7Y69pjJLxU4WNG3cXh%2bR3maeb24FSTxtltY2mGDc3xaho%3d";
            byte[] bytes3 = Convert.FromBase64String(@Server.UrlDecode(sss));
            crypt3.FromXmlString(readprivatekey);
            byte[] decryptbyte = crypt3.Decrypt(bytes, false);
            string decrypttext = enc.GetString(decryptbyte);
            Response.Write("<br/>");
            Response.Write("明文为:" + decrypttext);
        }
        protected void BtnChangePassword_Click(object sender, EventArgs e)
        {
            string keyPair = Session[PRIVATE_KEY] as string;
            if (keyPair == null)
            {
                throw new ApplicationException("セッションに保存したプライベートキーがみつかりません");
            }

            // RSA暗号化された暗号文の取得
            byte[] encryptedNewPass = LoginUtils.StringToByteArray(ENCRYPTED_NEW_PASS.Value);

            // RSAを復号する
            byte[] decryptedNewPass;
            using (var rsa = new RSACryptoServiceProvider())
            {
                try
                {
                    rsa.FromXmlString(keyPair);

                    decryptedNewPass = rsa.Decrypt(encryptedNewPass, false);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                    rsa.Clear();
                }
            }

            string newPassword = new string(System.Text.Encoding.UTF8.GetChars(decryptedNewPass));

            MembershipUser user = Membership.GetUser();
            if (user == null)
            {
                Message.Text = "ログインしていません";
                Message.ForeColor = Color.Red;
                return;
            }

            string curPassword = user.GetPassword();
            if (!user.ChangePassword(curPassword, newPassword))
            {
                Message.Text = "パスワードを変更できません";
                Message.ForeColor = Color.Red;
                return;
            }

            Message.Text = "パスワードを変更しました";
            Message.ForeColor = Color.Blue;
            return;
        }
Exemplo n.º 32
0
        /// <summary>
        /// 指定されたキーコンテナを削除する
        /// </summary>
        /// <param name="containerName">キーコンテナ名</param>
        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();
        }
Exemplo n.º 33
0
        public static byte[] RSADecrypt(byte[] privateKey, byte[] dataToDecrypt)
        {
            // helper to RSA decrypt a given blob

            // PROV_RSA_AES == 24
            var cspParameters = new System.Security.Cryptography.CspParameters(24);

            using (var rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters))
            {
                try
                {
                    rsaProvider.PersistKeyInCsp = false;
                    rsaProvider.ImportCspBlob(privateKey);

                    byte[] dataToDecryptRev = new byte[256];

                    Buffer.BlockCopy(dataToDecrypt, 0, dataToDecryptRev, 0, dataToDecrypt.Length); // ... Array.Copy? naw... :(

                    Array.Reverse(dataToDecryptRev);                                               // ... don't ask me how long it took to realize this :(

                    byte[] dec = rsaProvider.Decrypt(dataToDecryptRev, false);                     // no padding
                    return(dec);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error decryption domain key: {0}", e.Message);
                }
                finally
                {
                    rsaProvider.PersistKeyInCsp = false;
                    rsaProvider.Clear();
                }
            }

            return(new byte[0]);
        }