예제 #1
0
        public static void DecryptSavedAnswerUnusualExponent()
        {
            byte[] cipherBytes =
            {
                0x55, 0x64, 0x05, 0xF7, 0xBF, 0x99, 0xD8, 0x07,
                0xD0, 0xAC, 0x1B, 0x1B, 0x60, 0x92, 0x57, 0x95,
                0x5D, 0xA4, 0x5B, 0x55, 0x0E, 0x12, 0x90, 0x24,
                0x86, 0x35, 0xEE, 0x6D, 0xB3, 0x46, 0x3A, 0xB0,
                0x3D, 0x67, 0xCF, 0xB3, 0xFA, 0x61, 0xBB, 0x90,
                0x6D, 0x6D, 0xF8, 0x90, 0x5D, 0x67, 0xD1, 0x8F,
                0x99, 0x6C, 0x31, 0xA2, 0x2C, 0x8E, 0x99, 0x7E,
                0x75, 0xC5, 0x26, 0x71, 0xD1, 0xB0, 0xA5, 0x41,
                0x67, 0x19, 0xF7, 0x40, 0x04, 0xBE, 0xB2, 0xC0,
                0x97, 0xFB, 0xF6, 0xD4, 0xEF, 0x48, 0x5B, 0x93,
                0x81, 0xF8, 0xE1, 0x6A, 0x0E, 0xA0, 0x74, 0x6B,
                0x99, 0xC6, 0x23, 0xF5, 0x02, 0xDE, 0x47, 0x49,
                0x1E, 0x9D, 0xAE, 0x55, 0x20, 0xB5, 0xDE, 0xA0,
                0x04, 0x32, 0x37, 0x4B, 0x24, 0xE4, 0x64, 0x1B,
                0x1B, 0x4B, 0xC0, 0xC7, 0x30, 0x08, 0xA6, 0xAE,
                0x50, 0x86, 0x08, 0x34, 0x70, 0xE5, 0xB0, 0x3B,
            };

            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.UnusualExponentParameters);
                output = rsa.Decrypt(cipherBytes, true);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
예제 #2
0
        public static void DecryptSavedAnswer()
        {
            byte[] cipherBytes =
            {
                0x35, 0x6F, 0x8F, 0x2C, 0x4D, 0x1A, 0xAC, 0x6D,
                0xE7, 0x52, 0xA5, 0xDF, 0x26, 0x54, 0xA6, 0x34,
                0xF5, 0xBB, 0x14, 0x26, 0x1C, 0xE4, 0xDC, 0xA2,
                0xD8, 0x4D, 0x8F, 0x1C, 0x55, 0xD4, 0xC7, 0xA7,
                0xF2, 0x3C, 0x99, 0x77, 0x9F, 0xE4, 0xB7, 0x34,
                0xA6, 0x28, 0xB2, 0xC4, 0xFB, 0x6F, 0x85, 0xCA,
                0x19, 0x21, 0xCA, 0xC1, 0xA7, 0x8D, 0xAE, 0x95,
                0xAB, 0x9B, 0xA9, 0x88, 0x5B, 0x44, 0xC6, 0x9B,
                0x44, 0x26, 0x71, 0x5D, 0x02, 0x3F, 0x43, 0x42,
                0xEF, 0x4E, 0xEE, 0x09, 0x87, 0xEF, 0xCD, 0xCF,
                0xF9, 0x88, 0x99, 0xE8, 0x49, 0xF7, 0x8F, 0x9B,
                0x59, 0x68, 0x20, 0xF3, 0xA7, 0xB2, 0x94, 0xA4,
                0x23, 0x70, 0x83, 0xD9, 0xAC, 0xE7, 0x5E, 0xEE,
                0xE9, 0x7B, 0xE4, 0x4F, 0x73, 0x2E, 0x9B, 0xD8,
                0x2A, 0x75, 0xFB, 0x6C, 0xB9, 0x39, 0x6D, 0x72,
                0x8A, 0x9C, 0xCD, 0x58, 0x1A, 0x27, 0x79, 0x97,
            };

            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.RSA1024Params);
                output = rsa.Decrypt(cipherBytes, true);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
예제 #3
0
 private static byte[] Decrypt(string privateKeyXml, byte[] encryptedBytes, RsaKeyLengths rsaKeyLength)
 {
     using (var RSA = new RSACryptoServiceProvider((int) rsaKeyLength))
     {
         RSA.FromXmlString(privateKeyXml);
         byte[] bytes = RSA.Decrypt(encryptedBytes, DoOAEPPadding);
         return bytes;
     }
 }
예제 #4
0
    /// <summary>
    ///     A string extension method that decrypt a string.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="key">The key.</param>
    /// <returns>The decrypted string.</returns>
    /// <example>
    ///     <code>
    ///           using Microsoft.VisualStudio.TestTools.UnitTesting;
    ///           using Z.ExtensionMethods;
    ///           
    ///           namespace ExtensionMethods.Examples
    ///           {
    ///               [TestClass]
    ///               public class System_String_DecryptRSA
    ///               {
    ///                   [TestMethod]
    ///                   public void DecryptRSA()
    ///                   {
    ///                       // Type
    ///                       string @this = &quot;7E-24-A5-CF-8E-7A-83-52-90-CA-81-6F-26-04-7C-E6-F4-25-47-26-A9-55-04-83-32-78-1A-C0-E4-5D-90-66-A6-E1-58-59-A8-48-E1-20-21-B9-FE-84-31-53-52-9B-45-E1-B2-93-71-92-DA-29-5B-99-D1-41-19-9C-3E-13-4B-2B-BC-08-94-31-A4-F9-B9-0A-04-2F-C6-78-B1-47-27-11-2C-E6-AF-BF-A8-F2-F3-F6-4E-CB-EB-79-5E-80-C6-A1-0A-D7-7C-F1-16-0E-41-14-4E-76-7E-9E-DD-61-BF-11-5E-62-79-2D-C4-11-D2-F6-3D-7F-DD-87-C4-4E&quot;;
    ///           
    ///                       // Examples
    ///                       string value = @this.DecryptRSA(&quot;Buzz&quot;); // return &quot;Fizz&quot;;
    ///           
    ///                       // Unit Test
    ///                       Assert.AreEqual(&quot;Fizz&quot;, value);
    ///                   }
    ///               }
    ///           }
    ///     </code>
    /// </example>
    public static string DecryptRSA(this string @this, string key) {
        var cspp = new CspParameters {KeyContainerName = key};
        var rsa = new RSACryptoServiceProvider(cspp) {PersistKeyInCsp = true};
        string[] decryptArray = @this.Split(new[] {"-"}, StringSplitOptions.None);
        byte[] decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, NumberStyles.HexNumber))));
        byte[] bytes = rsa.Decrypt(decryptByteArray, true);

        return Encoding.UTF8.GetString(bytes);
    }
예제 #5
0
    public static void Main(String[] args) {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RijndaelManaged aes = new RijndaelManaged();
        aes.KeySize = 128; //  192;
        aes.Key = new byte[] {0xC7, 0x42, 0xD1, 0x37, 0x4B, 0xAC, 0xFE, 0x94,
                              0x9D, 0x59, 0x79, 0x92, 0x71, 0x48, 0xD6, 0x8E};
//                              ,1,2,3,4,5,6,7,8};

        byte[] aesKey = aes.Key;
        if (args.Length > 0) {
            FileStream fs = new FileStream(args[0], FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            String xmlString = sr.ReadToEnd();
            rsa.FromXmlString(xmlString);
        } else {
            FileStream fs = new FileStream("rsa.xml", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(rsa.ToXmlString(true));
            sw.Close();
        }
        Console.WriteLine("RSA Key is:\n"+rsa.ToXmlString(true));

        Console.WriteLine("AES Key is:");
        PrintByteArray(aesKey);
        byte[] encryptedKey1 = rsa.Encrypt(aesKey, true);
        Console.WriteLine("Encrypted AES Key is:");
        PrintByteArray(encryptedKey1);
        byte[] decryptedKey1 = rsa.Decrypt(encryptedKey1, true);
        Console.WriteLine("Decrypted AES Key is:");
        PrintByteArray(decryptedKey1);

        byte[] encryptedKey2 = rsa.Encrypt(aesKey, false);
        Console.WriteLine("Encrypted2 AES Key is:");
        PrintByteArray(encryptedKey2);
        byte[] decryptedKey2 = rsa.Decrypt(encryptedKey2, false);
        Console.WriteLine("Decrypted AES Key is:");
        PrintByteArray(decryptedKey2);

    }
예제 #6
0
 /// <summary>
 /// 字符串解密
 /// </summary>
 /// <param name="encryptString">密文</param>
 /// <param name="privateKey">私钥</param>
 /// <returns>遇到解密失败将会返回原字符串</returns>
 public static string DecryptString(string encryptString, string privateKey)
 {
     string source = string.Empty;
     try
     {
         RSACryptoServiceProvider.UseMachineKeyStore = true;
         RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
         rsaProvider.FromXmlString(FromBase64Key(privateKey));
         byte[] data = rsaProvider.Decrypt(HexStringToBytes(encryptString), false);
         source = System.Text.Encoding.ASCII.GetString(data);
     }
     catch { }
     return source;
 }
예제 #7
0
 public static string RSADecrypt(string encryptedString)
 {
     CspParameters param = new CspParameters();
     param.KeyContainerName = "PowerGridIndia";
     using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
     {
         int len = encryptedString.Length;
         encryptedString = encryptedString.Replace(" ", "+");
         byte[] encryptdata = Convert.FromBase64String(encryptedString);
         byte[] decryptdata = rsa.Decrypt(encryptdata, false);
         string plaindata = System.Text.Encoding.Default.GetString(decryptdata);
         return plaindata;
     }
 }
예제 #8
0
        public static void RsaCryptRoundtrip()
        {
            byte[] crypt;
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                crypt = rsa.Encrypt(TestData.HelloBytes, true);
                output = rsa.Decrypt(crypt, true);
            }

            Assert.NotEqual(crypt, output);
            Assert.Equal(TestData.HelloBytes, output);
        }
예제 #9
0
        public static void RsaDecryptAfterExport()
        {
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true);

                // Export the key, this should not clear/destroy the key.
                RSAParameters ignored = rsa.ExportParameters(true);
                output = rsa.Decrypt(crypt, true);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
예제 #10
0
    private static string Decrypt(byte[] encData)
    {
        var prvParams = "";

        using (var reader = new StreamReader(new FileStream("1.pub", FileMode.Open)))
        {
            prvParams = reader.ReadToEnd();
        }

        using (var rsa = new RSACryptoServiceProvider())
        {
            rsa.FromXmlString(prvParams);

            return ByteConverter.GetString(rsa.Decrypt(encData, false));
        }
    }
예제 #11
0
    public static byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo)
    {
        try
        {
            byte[] decryptedData;

            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.ImportParameters(RSAKeyInfo);
                decryptedData = RSA.Decrypt(DataToDecrypt,false);
            }
            return decryptedData;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.ToString());

            return null;
        }
    }
예제 #12
0
 public bool CheckLicense(byte[] license)
 {
     try {
         var rsaPrivate = new RSACryptoServiceProvider();
         rsaPrivate.FromXmlString(PRI_XML);
         byte[]   decryptedRSA   = rsaPrivate.Decrypt(license, false);
         string   originalResult = Encoding.Default.GetString(decryptedRSA);
         string[] result         = originalResult.Split('|');
         if (result.Length == 4)
         {
             if (result[3] != ENC_MSG)
             {
                 return(false);
             }
             this.LicenseTaker = result[0];
             this.PurchaseInfo = result[1];
             this.LicenseCount = result[2];
             return(true);
         }
     } catch {
         this.PurchaseInfo = "License not valid!";
     }
     return(false);
 }
예제 #13
0
        protected override bool HandshakeActive(SendCall Send, ReceiveCall Receive)
        {
            if (!Send(Encoding.ASCII.GetBytes(KEXCrypto.ToXmlString(false))))
            {
                return(false);
            }
            if (!Receive(out byte[] data, out EndPoint source))
            {
                return(false);
            }

            DataCrypto.Key = KEXCrypto.Decrypt(data, RSAEncryptionPadding.Pkcs1);
            if (!Send(DataCrypto.IV))
            {
                return(false);
            }

            if (!Receive(out data, out source))
            {
                return(false);
            }

            return(DecryptSecret(data));
        }
예제 #14
0
        public void DecyrptFile(string FilePath, int keysize)
        {
            byte[] decryped;
            string beriKljuc = null;

            SaveFileDialog dialog = new SaveFileDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                beriKljuc = File.ReadAllText(dialog.FileName);
            }



            using (var rsadecyrpt = new RSACryptoServiceProvider(keysize))
            {
                rsa.FromXmlString(beriKljuc);
                byte[] beri = File.ReadAllBytes(FilePath);

                decryped = rsa.Decrypt(beri, false);
            }

            File.WriteAllBytes(FilePath, decryped);
        }
예제 #15
0
        private void ExtractButtonClick(object sender, EventArgs e)
        {
            try
            {
                var dataToEncrypt = File.ReadAllBytes(@"D:\TEST\test.txt");

                byte[] encryptedData;
                using (var rsa1 = new RSACryptoServiceProvider(1024))
                {
                    var justPublicKey1 = this.GetStringFromFile(@"D:\TEST\GpiPublicKey.bin");
                    rsa1.FromXmlString(justPublicKey1);
                    encryptedData = rsa1.Encrypt(dataToEncrypt, false);
                }

                using (var rsa2 = new RSACryptoServiceProvider(1024))
                {
                    var publicAndPrivateKeys2 = this.GetStringFromFile(@"D:\TEST\GpiKeyPair.bin");
                    rsa2.FromXmlString(publicAndPrivateKeys2);
                    var decryptedData = rsa2.Decrypt(encryptedData, false);

                    var byteConverter = new ASCIIEncoding();
                    this.InfoListBox.Items.Add($"Decrypted plaintext: {byteConverter.GetString(decryptedData)}");

                    var signedBytes = File.ReadAllBytes(@"D:\TEST\Test.sig");
                    var result      = rsa2.VerifyData(decryptedData, CryptoConfig.MapNameToOID("SHA512"), signedBytes);
                    this.InfoListBox.Items.Add(rsa2.CspKeyContainerInfo.UniqueKeyContainerName);
                    this.InfoListBox.Items.Add(BitConverter.ToString(decryptedData).Replace("-", string.Empty));
                    this.InfoListBox.Items.Add(BitConverter.ToString(signedBytes).Replace("-", string.Empty));
                    this.InfoListBox.Items.Add(result);
                }
            }
            catch (Exception ex)
            {
                this.InfoListBox.Items.Add(ex.Message);
            }
        }
예제 #16
0
        public bool Decrypt(byte[] ToDecrypt, out byte[] decrypted)
        {
            bool flag;

            decrypted = null;
            if (string.IsNullOrEmpty(m_privateKey))
            {
                return(false);
            }
            try
            {
                using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider())
                {
                    provider.FromXmlString(m_privateKey);
                    decrypted = provider.Decrypt(ToDecrypt, false);
                    flag      = true;
                }
            }
            catch
            {
                flag = false;
            }
            return(flag);
        }
        public static void EncryptASymmetricKeyWithRSA()
        {
            var rsa = new RSACryptoServiceProvider(2048);

            byte[] blob = rsa.ExportCspBlob(false);

            var publicKey = new RSACryptoServiceProvider();

            publicKey.ImportCspBlob(blob);

            var aes = new AesCryptoServiceProvider();

            aes.KeySize = 256;

            // Now I will encrypt the key for a certain recipient using their public key.
            // This encryptedKey I can send at the other party that I want to communicate with securely.
            byte[] encryptedKey = publicKey.Encrypt(aes.Key, true);

            // The other party now will use their private key to decrypt the encryptedKey.
            // So now the decryptedKey here should be equal to aes.Key which was encrypted earlier.
            byte[] decryptedKey = rsa.Decrypt(encryptedKey, true);

            //Enumerable.SequenceEqual(decryptedKey, aes.Key).Should().BeTrue();
        }
예제 #18
0
        /// <summary>
        /// SHA1加密字符串 (不可解密)
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>加密后的字符串</returns>
        //public string SHA1(string source)
        //{
        //    return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");
        //}
        /// <summary>
        /// MD5加密字符串 (不可解密)
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>加密后的字符串</returns>
        //public string MD5(string source)
        //{
        //    return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5"); ;
        //}
        #endregion

        #region RSA


        #region rsa解密
        /// <summary>
        /// rsa解密
        /// </summary>
        /// <param name="s">加密后字符串字符串</param>
        /// <param name="key">加密key</param>
        /// <returns></returns>
        public static string RSADecrypt(string s, string key = strKeys)
        {
            string result = null;

            if (string.IsNullOrEmpty(s))
            {
                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.");
            }
            CspParameters cspp = new CspParameters();

            cspp.KeyContainerName = key;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);

            rsa.PersistKeyInCsp = true;
            string[] decryptArray     = s.Split(new string[] { "-" }, StringSplitOptions.None);
            byte[]   decryptByteArray = Array.ConvertAll <string, byte>(decryptArray, (a => Convert.ToByte(byte.Parse(a, System.Globalization.NumberStyles.HexNumber))));
            byte[]   bytes            = rsa.Decrypt(decryptByteArray, true);
            result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
            return(result);
        }
예제 #19
0
	public static string Encrypt(string toEncrypt)
	{
		RSACryptoServiceProvider CSPRSA = null;
		string result;
		try
		{
			CSPRSA = new RSACryptoServiceProvider();
			CSPRSA.FromXmlString(SAFSecurityKeys.loadKeysFromFile());
			byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
			result = Convert.ToBase64String(CSPRSA.Decrypt(toEncryptArray, false));
		}
		catch
		{
			result = null;
		}
		finally
		{
			if (CSPRSA != null)
			{
				CSPRSA.Clear();
			}
		}
		return result;
	}
예제 #20
0
        public static void ASymmetricKeyEncryptionDecryption(byte[] data)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                byte[] encrypted = rsa.Encrypt(data, true);

                foreach (byte b in encrypted)
                {
                    Console.Write(b + " ");
                }
                byte[] decrypted = rsa.Decrypt(encrypted, true);

                Console.WriteLine("\n........................");
                foreach (byte b in decrypted)
                {
                    Console.Write(b + " ");
                }


                File.WriteAllText("PublicKeyOnly.xml", rsa.ToXmlString(false));
                File.WriteAllText("PublicPrivate.xml", rsa.ToXmlString(true));
                rsa.ToString();
            }
        }
예제 #21
0
        public string Decryption(string strText)
        {
            var base64Encrypted = strText;

            using (var rsa = new RSACryptoServiceProvider(512))
            {
                try
                {
                    var P = new RSAParameters()
                    {
                        D        = b64_dBytes,
                        DP       = b64_dpBytes,
                        DQ       = b64_dqBytes,
                        Exponent = b64_exponent,
                        InverseQ = b64_inverseqBytes,
                        Modulus  = b64_modulusBytes,
                        P        = b64_pBytes,
                        Q        = b64_qBytes
                    };
                    rsa.ImportParameters(P);

                    var resultBytes    = Convert.FromBase64String(base64Encrypted);
                    var decryptedBytes = rsa.Decrypt(resultBytes, false);
                    var decryptedData  = Encoding.UTF8.GetString(decryptedBytes);
                    return(decryptedData.ToString());
                }
                catch (Exception)
                {
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
            return(null);
        }
예제 #22
0
        /// <summary>
        /// Decrypts the passed in string value using RSA
        /// </summary>
        /// <param name="decryptValue"><see cref="System.String"/> value to decrypt</param>
        /// <param name="publicKey"><see cref="System.String"/> registry key name that contains the public key</param>
        /// <returns></returns>
        public static string DecryptStringUsingRegistryKey(this string decryptValue, string privateKey)
        {
            // This is the variable that will be returned to the user
            string decryptedValue = string.Empty;

            // Make sure user supplied a value for the registry key
            if (string.IsNullOrEmpty(privateKey))
            {
                throw new ArgumentNullException("You must provide the name of the registry key for the public key");
            }

            // Create the CspParameters object which is used to create the RSA provider
            // without it generating a new private/public key.
            // Parameter value of 1 indicates RSA provider type - 13 would indicate DSA provider
            CspParameters csp = new CspParameters(1);

            // Registry key name containing the RSA private/public key
            csp.KeyContainerName = privateKey;

            // Supply the provider name
            csp.ProviderName = "Microsoft Strong Cryptographic Provider";

            //Create new RSA object passing our key info
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);

            // Before decryption we must convert this ugly string into a byte array
            byte[] valueToDecrypt = Convert.FromBase64String(decryptValue);

            // Decrypt the passed in string value - Again the false value has to do with padding
            byte[] plainTextValue = rsa.Decrypt(valueToDecrypt, false);

            // Extract our decrypted byte array into a string value to return to our user
            decryptedValue = System.Text.Encoding.UTF8.GetString(plainTextValue);

            return(decryptedValue);
        }
예제 #23
0
 private byte[] DecryptData(byte[] encryptedData, RSAParameters rsaKeyInfo, bool doOAEPPadding)
 {
     byte[] text = null;
     try
     {
         using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
         {
             //Import the RSA Key information. This needs to include the private key information.
             rsa.ImportParameters(rsaKeyInfo);
             //Decrypt the passed byte array and specify OAEP padding.
             //OAEP padding is only available on Microsoft Windows XP or later.
             text = rsa.Decrypt(encryptedData, doOAEPPadding);
         }
     }
     catch (CryptographicException)
     {
         throw;
     }
     catch (Exception)
     {
         throw;
     }
     return(text);
 }
예제 #24
0
        private void decryptFile(string keyPath, string filePath, string outputPath)
        {
            rsa.FromXmlString(File.ReadAllText(keyPath));

            FileStream fsInput  = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            FileStream fsOutput = new FileStream(outputPath, FileMode.Create, FileAccess.Write);

            fsOutput.SetLength(0);

            byte[] bin, encryptedData;
            long   rdlen  = 0;
            long   totlen = fsInput.Length;
            int    len;

            int maxByte = rsa.KeySize / 8;

            progressBarControl1.Properties.Step        = 1;
            progressBarControl1.Properties.PercentView = true;
            progressBarControl1.Properties.Maximum     = (int)(totlen + maxByte - 1) / maxByte;
            progressBarControl1.Properties.Minimum     = 0;

            while (rdlen < totlen)
            {
                bin = new byte[maxByte];
                len = fsInput.Read(bin, 0, maxByte);

                encryptedData = rsa.Decrypt(bin, false);
                fsOutput.Write(encryptedData, 0, encryptedData.Length);
                rdlen += len;
                progressBarControl1.PerformStep();
                progressBarControl1.Update();
            }

            fsOutput.Close();
            fsInput.Close();
        }
예제 #25
0
        /// <summary>
        /// 解密
        /// </summary>
        public static string Decrypt(string privateKey, string content)
        {
            if (string.IsNullOrEmpty(privateKey) || string.IsNullOrEmpty(content))
            {
                return(null);
            }

            byte[] bt = null;
            try
            {
                RSACryptoServiceProvider rsa = RSA.CreateRsaProviderFromPrivateKey(privateKey);
                bt = rsa.Decrypt(Convert.FromBase64String(content), false);
            }
            catch (Exception)
            {
                return(null);
            }

            if (bt != null && bt.Length > 0)
            {
                return(Encoding.UTF8.GetString(bt));
            }
            return(null);
        }
예제 #26
0
        /// <summary>
        /// Gets the decrypted password using the RSA private key which can be found in the
        /// PEM file for the key pair.
        /// </summary>
        /// <param name="rsaPrivateKey">The RSA private key from the PEM file</param>
        /// <returns>The decrypted password</returns>
        public string GetDecryptedPassword(string rsaPrivateKey)
        {
            RSAParameters rsaParams;

            try
            {
                rsaParams = new PemReader(new StringReader(rsaPrivateKey.Trim())).ReadPrivatekey();
            }
            catch (Exception e)
            {
                throw new AmazonEC2Exception("Invalid RSA Private Key", e);
            }

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(rsaParams);

            byte[] encryptedBytes = Convert.FromBase64String(this.PasswordData);
            var    decryptedBytes = rsa.Decrypt(encryptedBytes, false);

            string decrypted = Encoding.UTF8.GetString(decryptedBytes);

            return(decrypted);
        }
예제 #27
0
        public static void Encrypt()
        {
            string plainText = "This is my super secret data";

            Console.WriteLine($"Plain text: {plainText}");

            ASCIIEncoding converter = new ASCIIEncoding();

            byte[] plaintBytes = converter.GetBytes(plainText);

            DumbBytes("Plain bytes: ", plaintBytes);

            byte[] encryptedBytes, decryptedBytes;
            RSACryptoServiceProvider rsaEncrypt = new RSACryptoServiceProvider();

            //get keys out of the encryptor
            string publicKey = rsaEncrypt.ToXmlString(includePrivateParameters: false);

            Console.WriteLine($"Public key: {publicKey}");
            string privateKey = rsaEncrypt.ToXmlString(includePrivateParameters: true);

            Console.WriteLine($"Private key: {privateKey}");

            rsaEncrypt.FromXmlString(privateKey);

            encryptedBytes = rsaEncrypt.Encrypt(plaintBytes, fOAEP: false);
            DumbBytes("Encrypted bytes: ", encryptedBytes);

            RSACryptoServiceProvider rsaDecrypt = new RSACryptoServiceProvider();

            rsaDecrypt.FromXmlString(privateKey);

            decryptedBytes = rsaDecrypt.Decrypt(encryptedBytes, fOAEP: false);
            DumbBytes("Decrypted bytes: ", decryptedBytes);
            Console.WriteLine($"Decrypted string: {converter.GetString(decryptedBytes)}");
        }
예제 #28
0
        public byte[] _DecryptByPriKey(byte[] inputBytes, RSACryptoServiceProvider key)
        {
            int bufferSize = key.KeySize / 8;
            var buffer     = new byte[bufferSize];

            using (MemoryStream inputStream = new MemoryStream(inputBytes),
                   outputStream = new MemoryStream())
            {
                while (true)
                {
                    int readSize = inputStream.Read(buffer, 0, bufferSize);
                    if (readSize <= 0)
                    {
                        break;
                    }

                    var temp = new byte[readSize];
                    Array.Copy(buffer, 0, temp, 0, readSize);
                    var rawBytes = key.Decrypt(temp, false);
                    outputStream.Write(rawBytes, 0, rawBytes.Length);
                }
                return(outputStream.ToArray());
            }
        }
예제 #29
0
        public string Decrypt(string strText)
        {
            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    var base64Encrypted = strText;

                    // server decrypting data with private key
                    rsa.FromXmlString(privateKey);

                    var resultBytes    = Convert.FromBase64String(base64Encrypted);
                    var decryptedBytes = rsa.Decrypt(resultBytes, false);
                    var decryptedData  = Encoding.UTF8.GetString(decryptedBytes);
                    return(decryptedData);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }
예제 #30
0
        public static string DecryptString(string inputString, int dwKeySize, string xmlString)
        {
            // TODO: Add Proper Exception Handlers
            RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize);

            rsaCryptoServiceProvider.FromXmlString(xmlString);
            int         base64BlockSize = ((dwKeySize / 8) % 3 != 0) ? (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
            int         iterations      = inputString.Length / base64BlockSize;
            List <byte> arrayList       = new List <byte>();

            for (int i = 0; i < iterations; i++)
            {
                byte[] encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i, base64BlockSize));
                // Be aware the RSACryptoServiceProvider reverses the order of
                // encrypted bytes after encryption and before decryption.
                // If you do not require compatibility with Microsoft Cryptographic
                // API (CAPI) and/or other vendors.
                // Comment out the next line and the corresponding one in the
                // EncryptString function.
                Array.Reverse(encryptedBytes);
                arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true));
            }
            return(Encoding.UTF8.GetString(arrayList.ToArray()));
        }
예제 #31
0
        public static byte[] RSADecrypt(byte[] privateKey, byte[] dataToDecrypt)
        {
            // helper to RSA decrypt a given blob

            // PROV_RSA_AES == 24
            var cspParameters = new CspParameters(24);

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

                    var 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 :(

                    var 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]);
        }
예제 #32
0
        public byte[] ReadAllBytes(Stream stream)
        {
            // tested by?
            Console.WriteLine("enter ReadAllBytes " + new { stream });

            var m = new MemoryStream();

            var data       = new byte[EncryptedDataChunkSize];
            var datalength = stream.Read(data, 0, data.Length);

            while (datalength > 0)
            {
                var rgb = new byte[datalength];

                Array.Copy(data, rgb, datalength);
                var clear = rsa.Decrypt(rgb, fOAEP: fOAEP);

                m.Write(clear, 0, clear.Length);

                datalength = stream.Read(data, 0, data.Length);
            }

            return(m.ToArray());
        }
예제 #33
0
        static void Main(string[] args)
        {
            CspParameters csp = new CspParameters();

            csp.KeyContainerName = "mykey";
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
            var cipher = rsa.Encrypt(Encoding.UTF8.GetBytes("Hello World"), true);

            Console.WriteLine(Encoding.UTF8.GetString(cipher));
            Console.WriteLine(Encoding.UTF8.GetString(rsa.Decrypt(cipher, true)));
            var stream    = File.Open(@"C:\hello.txt", FileMode.Open, FileAccess.Read);
            var signature = rsa.SignData(stream,
                                         SHA256.Create());

            stream.Close();
            byte[] fileContent = new byte[1024];
            File.Open(@"c:\hello.txt", FileMode.Open, FileAccess.Read).Read(fileContent, 0, 1024);
            byte[] hash   = SHA256.Create().ComputeHash(fileContent);
            bool   result = rsa.VerifyData(hash,
                                           SHA256.Create(), signature
                                           );

            Console.WriteLine(result);
        }
예제 #34
0
        static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(8192))
                {
                    //Import the RSA Key information. This needs
                    //to include the private key information.
                    RSA.ImportParameters(RSAKeyInfo);
                    byte[] bytes = new byte[1024];
                    for (int i = 0; i < 1024; i++)
                    {
                        bytes[i] = DataToDecrypt[i];
                    }
                    //Decrypt the passed byte array and specify OAEP padding.
                    //OAEP padding is only available on Microsoft Windows XP or
                    //later.
                    //Console.WriteLine("Big data {0}",Convert.ToBase64String(DataToDecrypt));
                    //Console.WriteLine("Small data {0}",Convert.ToBase64String(DataToDecrypt));


                    decryptedData = RSA.Decrypt(bytes, DoOAEPPadding);
                }
                return(decryptedData);
            }
            //Catch and display a CryptographicException
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.ToString());

                return(null);
            }
        }
예제 #35
0
 /// <summary>
 /// Decripta tramite chiave RSA
 /// </summary>
 /// <param name="key"></param>
 /// <param name="encData"></param>
 /// <returns></returns>
 public static byte[] RSA_Decrypt(RSACryptoServiceProvider key, byte[] encData)
 {
     return(key.Decrypt(encData, true));
 }
예제 #36
0
 /// <summary>
 /// Decripta un testo codificato ed in base 64 e ritorna un buffer
 /// </summary>
 /// <param name="key"></param>
 /// <param name="encData64"></param>
 /// <returns></returns>
 public static byte[] RSA_Decrypt_B64(RSACryptoServiceProvider key, string encData64)
 {
     return(key.Decrypt(Convert.FromBase64String(encData64), true));
 }
 public byte[] Decrypt(byte[] value)
 {
     return(_provider.Decrypt(value, RSAEncryptionPadding.Pkcs1));
 }
예제 #38
0
        private bool DecryptFile(string inFile, string csppName)
        {
            cspp.KeyContainerName = csppName;
            rsa = new RSACryptoServiceProvider(cspp);
            try
            {
                string infile2 = inFile;
                inFile = EncrFolder + inFile;
                FileStream inFs = new FileStream(inFile, FileMode.Open);
                inFile = infile2;

                if (inFs.Length == 0)
                {
                    MessageBox.Show("File is empty");
                }
                else
                {
                    RijndaelManaged rjndl = new RijndaelManaged();
                    rjndl.KeySize   = 256;
                    rjndl.BlockSize = 128;
                    rjndl.Mode      = CipherMode.CBC;

                    byte[] LenK  = new byte[4];
                    byte[] LenIV = new byte[4];

                    string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";

                    using (inFs)
                    {
                        inFs.Seek(0, SeekOrigin.Begin);
                        inFs.Seek(0, SeekOrigin.Begin);
                        inFs.Read(LenK, 0, 3);
                        inFs.Seek(4, SeekOrigin.Begin);
                        inFs.Read(LenIV, 0, 3);

                        int    lenK         = BitConverter.ToInt32(LenK, 0);
                        int    lenIV        = BitConverter.ToInt32(LenIV, 0);
                        int    startC       = lenK + lenIV + 8;
                        int    lenC         = (int)inFs.Length - startC;
                        byte[] KeyEncrypted = new byte[lenK];
                        byte[] IV           = new byte[lenIV];

                        inFs.Seek(8, SeekOrigin.Begin);
                        inFs.Read(KeyEncrypted, 0, lenK);
                        inFs.Seek(8 + lenK, SeekOrigin.Begin);
                        inFs.Read(IV, 0, lenIV);
                        Directory.CreateDirectory(DecrFolder);

                        byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

                        ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV);

                        using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                        {
                            int    count          = 0;
                            int    offset         = 0;
                            int    blockSizeBytes = rjndl.BlockSize / 8;
                            byte[] data           = new byte[blockSizeBytes];

                            inFs.Seek(startC, SeekOrigin.Begin);
                            using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                            {
                                do
                                {
                                    count   = inFs.Read(data, 0, blockSizeBytes);
                                    offset += count;
                                    outStreamDecrypted.Write(data, 0, count);
                                }while (count > 0);

                                outStreamDecrypted.FlushFinalBlock();
                                outStreamDecrypted.Close();
                            }
                            outFs.Close();
                        }
                        inFs.Close();
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return(false);
            }
        }
예제 #39
0
 public byte[] Decrypt(byte[] bytes, bool fOAEP)
 {
     return(algorithm.Decrypt(bytes, fOAEP));
 }
예제 #40
0
파일: RSA.cs 프로젝트: 329277920/SnailCore
 /// <summary>
 /// 私钥解密
 /// </summary>
 /// <param name="encryptdata">已加密的字节数组</param>
 /// <param name="xmlPublicKey">待加密的字节数组</param>
 /// <returns>返回加密的字节数组</returns>
 public static byte[] DecryptByPrivateKey(byte[] encryptdata, string xmlPrivateKey)
 {
     System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
     rsa.FromXmlString(xmlPrivateKey);
     return(rsa.Decrypt(encryptdata, false));
 }
예제 #41
0
 public static byte[] Decrypt(byte[] encryptedBytes, RSAParameters privateKey, RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048)
 {
     using (var rsa = new RSACryptoServiceProvider((int)rsaKeyLength))
     {
         rsa.ImportParameters(privateKey);
         byte[] bytes = rsa.Decrypt(encryptedBytes, DoOAEPPadding);
         return bytes;
     }
 }
예제 #42
0
파일: CryptUtils.cs 프로젝트: vebin/soa
        public static string Decrypt(string privateKey, string data, RsaKeyLengths length = RsaKeyLengths.Bit2048)
        {
            var dwKeySize = (int)length;
            // TODO: Add Proper Exception Handlers
            var rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize);
            rsaCryptoServiceProvider.FromXmlString(privateKey);

            int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ?
              (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;

            int iterations = data.Length / base64BlockSize;

            var arrayList = new ArrayList();
            for (int i = 0; i < iterations; i++)
            {
                byte[] encryptedBytes = Convert.FromBase64String(
                     data.Substring(base64BlockSize * i, base64BlockSize));
                // Be aware the RSACryptoServiceProvider reverses the order of 
                // encrypted bytes after encryption and before decryption.
                // If you do not require compatibility with Microsoft Cryptographic 
                // API (CAPI) and/or other vendors.
                // Comment out the next line and the corresponding one in the 
                // EncryptString function.
                Array.Reverse(encryptedBytes);
                arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true));
            }

            return Encoding.Unicode.GetString(arrayList.ToArray(typeof(byte)) as byte[]);
        }
예제 #43
0
            public static byte[] RSADecrypt(byte[] dataToDecrypt, RSAParameters pars, bool padding)
            {
                try
                {
                    byte[] encryptedData;
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSA.ImportParameters(pars);
                        encryptedData = RSA.Decrypt(dataToDecrypt, padding);
                    }
                    return encryptedData;
                }
                catch (Exception)
                {

                    return null;

                }
            }
예제 #44
0
 public static byte[] Decrypt(byte[] encryptedBytes, string privateKeyXml, RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048)
 {
     using (var rsa = new RSACryptoServiceProvider((int)rsaKeyLength))
     {
         rsa.FromXmlString(privateKeyXml);
         byte[] bytes = rsa.Decrypt(encryptedBytes, DoOAEPPadding);
         return bytes;
     }
 }
예제 #45
0
    public static void StartClient()
    {
        // Data buffer for incoming data.
        byte[] bytes;

        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // This example uses port 11000 on the local computer.
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}",
                    sender.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.
                //   byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

                // Send the data through the socket.
                // int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.

                string data = null;
                bytes = new byte[16000];
                while (true)
                {
                    int bytesCount = sender.Receive(bytes);

                    //answer = bytes;
                    data = Encoding.ASCII.GetString(bytes);
                    if (data.IndexOf("{Key}") > -1)
                    {
                        byte[] answer = new byte[256];
                        for (int i = 0; i < 256; i++)
                            answer[i] = bytes[i + 5];
                        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                        rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
                        keyAES = rsa.Decrypt(answer, false);
                        byte[] buff = Encoding.UTF8.GetBytes("Ключ был успешно получен!");
                        sender.Send(buff);
                        Console.Write("Сессионный ключ был успешно получен\n");
                        data = null;
                        bytesCount = sender.Receive(bytes);

                        //answer = bytes;
                        data = Encoding.ASCII.GetString(bytes);

                    }
                    if (data!=null)
                    {

                        byte[] encMes = new byte[bytesCount];
                        Array.Copy(bytes, 0, encMes, 0, bytesCount);
                        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                        aes.KeySize = 256;
                        aes.Key = keyAES;
                        //aes.Padding = PaddingMode.Zeros;
                        byte[] iv = new byte[16];
                        aes.IV = iv;
                        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                        // Create the streams used for decryption.
                        string plaintext;
                        using (MemoryStream msDecrypt = new MemoryStream(encMes))
                        {
                            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                            {
                                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                                {

                                    // Read the decrypted bytes from the decrypting stream
                                    // and place them in a string.
                                    plaintext = srDecrypt.ReadToEnd();
                                    File.WriteAllText("c:\\result", plaintext);
                                    Console.WriteLine("Расшифрованный принятый файл : {0}", plaintext);
                                }
                            }
                        }
                        break;
                    }
                }

                Console.Read();
                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }

            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
예제 #46
0
        public static void UnusualExponentCryptRoundtrip()
        {
            byte[] crypt;
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.UnusualExponentParameters);

                crypt = rsa.Encrypt(TestData.HelloBytes, true);
                output = rsa.Decrypt(crypt, true);
            }

            Assert.NotEqual(crypt, output);
            Assert.Equal(TestData.HelloBytes, output);
        }
예제 #47
0
        public static void LargeKeyCryptRoundtrip()
        {
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                try
                {
                    rsa.ImportParameters(TestData.RSA16384Params);
                }
                catch (CryptographicException)
                {
                    // The key is pretty big, perhaps it was refused.
                    return;
                }

                byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true);

                Assert.Equal(rsa.KeySize, crypt.Length * 8);

                output = rsa.Decrypt(crypt, true);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
예제 #48
0
 /// <summary>
 /// Decripta un testo codificato ed in base 64 e ritorna un testo nell'encoding specificato
 /// </summary>
 /// <param name="key"></param>
 /// <param name="encData64"></param>
 /// <param name="enc"></param>
 /// <returns></returns>
 public static string RSA_Decrypt_B64_Text(RSACryptoServiceProvider key, string encData64, Encoding enc)
 {
     return(enc.GetString(key.Decrypt(Convert.FromBase64String(encData64), true)));
 }
예제 #49
0
    public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo,bool DoOAEPPadding)
    {
        try
        {
            //Create a new instance of RSACryptoServiceProvider.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            //Import the RSA Key information. This needs
            //to include the private key information.
            RSA.ImportParameters(RSAKeyInfo);

            //Decrypt the passed byte array and specify OAEP padding.
            //OAEP padding is only available on Microsoft Windows XP or
            //later.
            return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
        }
            //Catch and display a CryptographicException
            //to the console.
        catch(CryptographicException e)
        {
            Console.WriteLine(e.ToString());

            return null;
        }
    }
예제 #50
0
        /// <summary>
        /// Кнопка расшифровать
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDecrypt_Click(object sender, EventArgs e)
        {
            // Если установлен флажок "Доп. защиты", то расшифроваем зашифрованный AES ключ с помощью доп. ключа RSA
            try
            {
                if (checkBoxTwoKeys.Checked)
                {
                    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
                    {
                        rsa.FromXmlString(textBoxRsaKey.Text);

                        textBoxKey.Text = BitConverter.ToString(rsa.Decrypt(FromHex(textBoxKey.Text), false));
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Невозможно расшифровать основной ключ с помощью дополнительного.", "Неверные ключи.", MessageBoxButtons.OK);
                return;
            }

            // Считывание ключа
            string key = string.Empty;
            string iv  = string.Empty;

            try
            {
                key = textBoxKey.Text.Substring(0, 95);
                iv  = textBoxKey.Text.Substring(96, 47);
            }
            catch (Exception)
            {
                MessageBox.Show("Неверный ключ!", "Ошибка!", MessageBoxButtons.OK);
                return;
            }


            // Переносим все выбранные папки treeView в список
            var selectedFolders = GetAllFilesPathFrom(Descendants(treeView.Nodes)
                                                      .Where(n => n.Checked && n.Tag != null)
                                                      .Select(n => n.Tag.ToString())
                                                      .ToArray()).ToArray();

            var listPaths = GetAllFilesPathFrom(GetAllItemsFrom(listViewFiles.Items)
                                                .Select(n => n.Text)
                                                .ToArray()).ToArray();

            string[] allPaths = selectedFolders.Union(listPaths).ToArray();

            listViewFiles.Clear();

            // добавляем файлы в listView
            foreach (var path in allPaths)
            {
                listViewFiles.Items.Add(path.ToString());
            }

            // Проверка элементов
            if (listViewFiles.Items.Count <= 0)
            {
                MessageBox.Show("Пожалуйста, выберите файлы для дешифрования", "Не выбраны файлы", MessageBoxButtons.OK);
                return;
            }

            // Убираем все подсветы
            UncolorItems();

            // Начальные логи
            logBar.Text              = "Logs: Decrypt started...";
            progressBar.Value        = 0;
            highestPercentageReached = 0;

            if (backgroundCrypter.IsBusy == false && backgroundDecrypter.IsBusy == false)
            {
                CrypterPack decryptPack = new CrypterPack();
                decryptPack.key   = key;
                decryptPack.iv    = iv;
                decryptPack.paths = allPaths;

                backgroundDecrypter.RunWorkerAsync(decryptPack);

                CrypterStarted(true);
            }
            else
            {
                MessageBox.Show("Процесс уже запущен.", "Невозможно запустить второй раз", MessageBoxButtons.OK);
            }
        }
예제 #51
0
	public static byte[] decrypt(string PEMPrivateKey, byte[] data) {
		byte[] decrData = null;
		
		if ((data != null) && (PEMPrivateKey != null)) {
			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
			
			string privateKeyXml = opensslkey.DecodePEMKey(PEMPrivateKey);
			if (privateKeyXml != null) {
				rsa.FromXmlString(privateKeyXml);
				
				decrData = rsa.Decrypt(data, false);
			}
			else {
				Console.WriteLine("incorrect PEM key. " + PEMPrivateKey);
			}
		}
		
		return decrData;
	}