public void TestSignFlagJson()
        {
            Func<byte[], byte[]> sigFunc = (x) =>
            {
                using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(JwsUnitTests.GetRsaParamsForRfc7515Example_A_2_1());
                    using (var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                    {
                        return rsa.SignData(x, sha256);
                    }
                }
            };

            object protectedSample = new // From the RFC example
            {
                alg = "RS256"
            };
            object headerSample = new // From the RFC example
            {
                kid = "2010-12-29"
            };
            string payloadSample = // From the RFC example
                    "{\"iss\":\"joe\",\r\n" +
                    " \"exp\":1300819380,\r\n" +
                    " \"http://example.com/is_root\":true}";

            var wsRegex = new Regex("\\s+");
            var sigExpected = // Derived from the RFC example in A.6.4
                    wsRegex.Replace(@"{
                        ""payload"":""eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"",
                        ""protected"":""eyJhbGciOiJSUzI1NiJ9"",
                        ""header"":{""kid"":""2010-12-29""},
                        ""signature"":
                            ""cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZ
                            mh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjb
                            KBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHl
                            b1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZES
                            c6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AX
                            LIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw""
                    }", "");
            var sigActual = wsRegex.Replace(JwsHelper.SignFlatJson(
                    sigFunc, payloadSample, protectedSample, headerSample), "");
            Assert.AreEqual(sigExpected, sigActual);
        }
Esempio n. 2
0
		public void init(int key_size)
		{
			//    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
			//    keyGen.initialize(key_size, new SecureRandom());
			//    KeyPair pair = keyGen.generateKeyPair();
			//
			//    PublicKey pubKey=pair.getPublic();
			//    PrivateKey prvKey=pair.getPrivate();

			System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(key_size);
			RSAKeyInfo = rsa.ExportParameters(true);

			//    d=((RSAPrivateKey)prvKey).getPrivateExponent().toByteArray();
			//    e=((RSAPublicKey)pubKey).getPublicExponent().toByteArray();
			//    n=((RSAKey)prvKey).getModulus().toByteArray();
			//
			//    c=((RSAPrivateCrtKey)prvKey).getCrtCoefficient().toByteArray();
			//    ep=((RSAPrivateCrtKey)prvKey).getPrimeExponentP().toByteArray();
			//    eq=((RSAPrivateCrtKey)prvKey).getPrimeExponentQ().toByteArray();
			//    p=((RSAPrivateCrtKey)prvKey).getPrimeP().toByteArray();
			//    q=((RSAPrivateCrtKey)prvKey).getPrimeQ().toByteArray();

			d= RSAKeyInfo.D ;
			e=RSAKeyInfo.Exponent ;
			n=RSAKeyInfo.Modulus ;

			c=RSAKeyInfo.InverseQ ;
			ep=RSAKeyInfo.DP ;
			eq=RSAKeyInfo.DQ ;
			p=RSAKeyInfo.P ;
			q=RSAKeyInfo.Q ;
		}
Esempio n. 3
0
        /// <summary>
        /// 公開鍵と秘密鍵を作成して返す
        /// </summary>
        /// <param name="publicKey">作成された公開鍵(XML形式)</param>
        /// <param name="privateKey">作成された秘密鍵(XML形式)</param>
        public static void CreateKeys(out string publicKey, out string privateKey)
        {
            //RSACryptoServiceProviderオブジェクトの作成
            System.Security.Cryptography.RSACryptoServiceProvider rsa =
                new System.Security.Cryptography.RSACryptoServiceProvider();

            //公開鍵をXML形式で取得
            publicKey = rsa.ToXmlString(false);
            //秘密鍵をXML形式で取得
            privateKey = rsa.ToXmlString(true);
        }
        private void GenerateKeyPairButton_Click(object sender, EventArgs e)
        {
            SaveDialog.FileName = "DeveloperKeyPair.key";
            SaveDialog.DefaultExt = "key";
            SaveDialog.Filter = ToolsHub.JustXmlKeysFilter;
            if (SaveDialog.ShowDialog() == DialogResult.OK)
            {
                string TargetKeyFilename = SaveDialog.FileName;

                // Generate a new 2048 bit RSA key and save it to disk
                System.Security.Cryptography.RSACryptoServiceProvider KeyPair = new System.Security.Cryptography.RSACryptoServiceProvider(2048);
                File.WriteAllText(TargetKeyFilename, KeyPair.ToXmlString(true));

                KeyPairFilenameBox.Text = TargetKeyFilename;
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 秘密鍵を使って文字列を復号化する
        /// </summary>
        /// <param name="str">Encryptメソッドにより暗号化された文字列</param>
        /// <param name="privateKey">復号化に必要な秘密鍵(XML形式)</param>
        /// <returns>復号化された文字列</returns>
        public static string Decrypt(string str, string privateKey)
        {
            //RSACryptoServiceProviderオブジェクトの作成
            System.Security.Cryptography.RSACryptoServiceProvider rsa =
                new System.Security.Cryptography.RSACryptoServiceProvider();

            //秘密鍵を指定
            rsa.FromXmlString(privateKey);

            //復号化する文字列をバイト配列に
            byte[] data = System.Convert.FromBase64String(str);
            //復号化する
            byte[] decryptedData = rsa.Decrypt(data, false);

            //結果を文字列に変換
            return System.Text.Encoding.UTF8.GetString(decryptedData);
        }
Esempio n. 6
0
        /// <summary>
        /// 公開鍵を使って文字列を暗号化する
        /// </summary>
        /// <param name="str">暗号化する文字列</param>
        /// <param name="publicKey">暗号化に使用する公開鍵(XML形式)</param>
        /// <returns>暗号化された文字列</returns>
        public static string Encrypt(string str, string publicKey)
        {
            //RSACryptoServiceProviderオブジェクトの作成
            System.Security.Cryptography.RSACryptoServiceProvider rsa =
                new System.Security.Cryptography.RSACryptoServiceProvider();

            //公開鍵を指定
            rsa.FromXmlString(publicKey);

            //暗号化する文字列をバイト配列に
            byte[] data = System.Text.Encoding.UTF8.GetBytes(str);
            //暗号化する
            //(XP以降の場合のみ2項目にTrueを指定し、OAEPパディングを使用できる)
            byte[] encryptedData = rsa.Encrypt(data, false);

            //Base64で結果を文字列に変換
            return System.Convert.ToBase64String(encryptedData);
        }
Esempio n. 7
0
        /// <summary>
        /// 启动服务器,开始监听客户端请求。
        /// </summary>
        public void Start() {
            if (IsStarted) return;

            if (RSAOpenAESMode != RSAOpenAESMode.Disallow)
                rsa = new System.Security.Cryptography.RSACryptoServiceProvider(2048);

            // 创建一个信号量,用来防止超过最大连接数
            maxConnectionLimiter = new Semaphore(MaxCountOfConnection, MaxCountOfConnection);
            maxCountOfConcurrentDataProccesserLimiter = new Semaphore(MaxCountOfConcurrentDataProccesser, MaxCountOfConcurrentDataProccesser);

            // create the socket which listens for incoming connections
            listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // bind it to the endPoint
            listenSocket.Bind(ListenEndPoint);

            listenSocket.Listen(Backlog);

            StartAccept();
        }
Esempio n. 8
0
        public bool verify(byte[] sig)
        {
            cs.Close();
            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
            RSA.ImportParameters(RSAKeyInfo);
            System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
            RSADeformatter.SetHashAlgorithm("SHA1");


            long i = 0;
            long j = 0;

            byte[] tmp;

            //Util.Dump("c:\\sig.bin", sig);

            if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
            {
                long i1 = (sig[i++] << 24) & 0xff000000;
                long i2 = (sig[i++] << 16) & 0x00ff0000;
                long i3 = (sig[i++] << 8) & 0x0000ff00;
                long i4 = (sig[i++]) & 0x000000ff;
                j = i1 | i2 | i3 | i4;

                i += j;

                i1 = (sig[i++] << 24) & 0xff000000;
                i2 = (sig[i++] << 16) & 0x00ff0000;
                i3 = (sig[i++] << 8) & 0x0000ff00;
                i4 = (sig[i++]) & 0x000000ff;
                j  = i1 | i2 | i3 | i4;

                tmp = new byte[j];
                Array.Copy(sig, i, tmp, 0, j); sig = tmp;
            }
            //System.out.println("j="+j+" "+Integer.toHexString(sig[0]&0xff));
            //return signature.verify(sig);
            bool verify = RSADeformatter.VerifySignature(sha1, sig);

            return(verify);
        }
Esempio n. 9
0
        public static string Decrypt(string stringToDecrypt, string key)
        {
            string result = null;

            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.");
            }

            try
            {
                System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
                cspp.KeyContainerName = key;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
                rsa.PersistKeyInCsp = true;

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


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

                result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                // no need for further processing
            }

            return(result);
        }
        public static UserInfo DecryptIzendaAuthenticationMessage(string encryptedMessage)
        {
            string rsaPrivateKey = "";

            try
            {
                string framework = Assembly
                                   .GetEntryAssembly()?
                                   .GetCustomAttribute <System.Runtime.Versioning.TargetFrameworkAttribute>()?
                                   .FrameworkName;
                if (framework.Contains("core", StringComparison.OrdinalIgnoreCase))
                {
                    IConfigurationRoot cb = new ConfigurationBuilder()
                                            .AddJsonFile("appsettings.json", optional: false)
                                            .Build();
                    rsaPrivateKey = cb.GetValue <string>("AppSettings:Settings:rsaPrivateKey");
                }
                else
                {
                    rsaPrivateKey = ConfigurationManager.AppSettings["RSAPrivateKey"];
                }
            }
            catch {
                throw new Exception("Configuration / RSA key can't be found");
            }
            var cipher = new System.Security.Cryptography.RSACryptoServiceProvider();

            //Decrypt using RSA private key in PEM format.
            var rsaParam = ConvertPemToXmlFormat(rsaPrivateKey);

            cipher.ImportParameters(rsaParam);
            //End

            var resultBytes    = Convert.FromBase64String(encryptedMessage);
            var decryptedBytes = cipher.Decrypt(resultBytes, false);
            var decryptedData  = System.Text.Encoding.UTF8.GetString(decryptedBytes);

            var result = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfo>(decryptedData);

            return(result);
        }
        public void RSAParametersJsonSerialization()
        {
            // Arrange
            CryptographyFactory f = new CryptographyFactory();

            System.Security.Cryptography.RSAParameters rsaParameters;
            using (System.Security.Cryptography.RSACryptoServiceProvider csp = new System.Security.Cryptography.RSACryptoServiceProvider())
            {
                rsaParameters = csp.ExportParameters(true);
            }

            // Act
            System.Text.Json.JsonSerializerOptions opts = new System.Text.Json.JsonSerializerOptions();
            opts.WriteIndented = true;
            string json = System.Text.Json.JsonSerializer.Serialize(rsaParameters.ToDictionary(), opts);

            Console.WriteLine(json);

            // Assert
            Assert.NotNull(json);
        }
        public static UserInfo DecryptIzendaAuthenticationMessage(string encryptedMessage)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();

            var rsaPrivateKey = configuration.GetValue <string>("AppSettings:Settings:rsaPrivateKey");
            var cipher        = new System.Security.Cryptography.RSACryptoServiceProvider();

            //Decrypt using RSA private key in PEM format.
            var rsaParam = ConvertPemToXmlFormat(rsaPrivateKey);

            cipher.ImportParameters(rsaParam);
            //End

            var resultBytes    = Convert.FromBase64String(encryptedMessage);
            var decryptedBytes = cipher.Decrypt(resultBytes, false);
            var decryptedData  = System.Text.Encoding.UTF8.GetString(decryptedBytes);

            var result = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfo>(decryptedData);

            return(result);
        }
Esempio n. 13
0
 public bool CheckBlockSignature()
 {
     try
     {
         foreach (var PublicKey in Blockchain.PublicKeys)
         {
             System.Security.Cryptography.RSACryptoServiceProvider RSAalg = new System.Security.Cryptography.RSACryptoServiceProvider();
             RSAalg.ImportCspBlob(Convert.FromBase64String(PublicKey));
             if (RSAalg.VerifyHash(CalculateChecksumBytes(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"), ChecksumBytes))
             {
                 ;
             }
             return(true);
         }
         return(false);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         return(false);
     }
 }
Esempio n. 14
0
        public void SetSeal(string TheXML)
        {
            string OriginalChain = GetOriginalChain(TheXML, xsltOriginalChain);


            byte[] SHA1hash = GetSHA1(OriginalChain);

            string PassKey = "ocsisol12";

            System.Security.SecureString secPassPhrase = new System.Security.SecureString();
            foreach (char passChar in PassKey.ToCharArray())
            {
                secPassPhrase.AppendChar(passChar);
            }

            System.Security.Cryptography.RSACryptoServiceProvider privateKey = LoadPrivateKeyFromFile(keyFile, secPassPhrase);

            string seal = GetSeal(SHA1hash, privateKey);


            CFDIComprobante.sello = seal;
        }
Esempio n. 15
0
        /// <summary>
        /// Encryptes a string using the supplied key. Encoding is done using RSA encryption.
        /// </summary>
        /// <param name="stringToEncrypt">String that must be encrypted.</param>
        /// <param name="key">Encryptionkey.</param>
        /// <returns>A string representing a byte array separated by a minus sign.</returns>
        /// <exception cref="ArgumentException">Occurs when stringToEncrypt or key is null or empty.</exception>
        public static string Encrypt(this string stringToEncrypt, string key)
        {
            if (string.IsNullOrEmpty(stringToEncrypt))
            {
                throw new ArgumentException("An empty string value cannot be encrypted.");
            }

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

            System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
            cspp.KeyContainerName = key;

            System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
            rsa.PersistKeyInCsp = true;

            byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);

            return(BitConverter.ToString(bytes));
        }
        private static async System.Threading.Tasks.Task <ResultType> TaskMain(Fee.Crypt.OnCryptTask_CallBackInterface a_callback_interface, byte[] a_binary, string a_key, Fee.TaskW.CancelToken a_cancel)
                #endif
        {
            ResultType t_ret;

            {
                t_ret.binary      = null;
                t_ret.errorstring = null;
            }

            try{
                using (System.Security.Cryptography.RSACryptoServiceProvider t_rsa = new System.Security.Cryptography.RSACryptoServiceProvider()){
                    t_rsa.FromXmlString(a_key);
                    t_ret.binary = t_rsa.Decrypt(a_binary, false);
                }
            }catch (System.Exception t_exception) {
                t_ret.binary      = null;
                t_ret.errorstring = "Task_DecryptPrivateKey : " + t_exception.Message;
            }

            if (a_cancel.IsCancellationRequested() == true)
            {
                t_ret.binary      = null;
                t_ret.errorstring = "Task_DecryptPrivateKey : Cancel";

                a_cancel.ThrowIfCancellationRequested();
            }

            if (t_ret.binary == null)
            {
                if (t_ret.errorstring == null)
                {
                    t_ret.errorstring = "Task_DecryptPrivateKey : null";
                }
            }

            return(t_ret);
        }
Esempio n. 17
0
        public static void Test_BlockchainWithDocumentsSigned()
        {
            // Blockchain with the content having double signature

            var rsa1             = new System.Security.Cryptography.RSACryptoServiceProvider();
            var publicKey1Base64 = Convert.ToBase64String(rsa1.ExportCspBlob(false));

            var rsa2             = new System.Security.Cryptography.RSACryptoServiceProvider();
            var publicKey2Base64 = Convert.ToBase64String(rsa2.ExportCspBlob(false));

            var  blocks = new Blockchain("Webmaster", "Phrases", Blockchain.BlockchainType.Binary, Blockchain.BlockSynchronization.AddInLocalAndSync, true);
            var  test   = blocks.Validate();
            bool isValid;

            var block1    = new Blockchain.Block(blocks, "Hi my friends, I have a message for you");
            var signature = rsa1.SignHash(block1.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));

            isValid   = block1.AddBodySignature(publicKey1Base64, signature, false); // Add first signature
            signature = rsa2.SignHash(block1.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            isValid   = block1.AddBodySignature(publicKey2Base64, signature, true);  // Add second signature and closing the block

            var block2 = new Blockchain.Block(blocks, "This is a message number 2, signed");

            signature = rsa1.SignHash(block2.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            isValid   = block2.AddBodySignature(publicKey1Base64, signature, false); // Add first signature
            signature = rsa2.SignHash(block2.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            isValid   = block2.AddBodySignature(publicKey2Base64, signature, true);

            var block3 = new Blockchain.Block(blocks, "In the last block I added the last message");

            signature = rsa1.SignHash(block3.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            isValid   = block3.AddBodySignature(publicKey1Base64, signature, false); // Add first signature
            signature = rsa2.SignHash(block3.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            isValid   = block3.AddBodySignature(publicKey2Base64, signature, true);  // Add second signature and closing the block

            var blockError = blocks.Validate();                                      // 0 = no error
            var lastBlock  = blocks.GetLastBlock();
        }
Esempio n. 18
0
		public Keys RsaNewKeys(int keySize)
		{
			Keys keys = new Keys();
			// Generate a public/private key pair.
			System.Security.Cryptography.RSACryptoServiceProvider rsa;
			rsa = new System.Security.Cryptography.RSACryptoServiceProvider(keySize);
			//-----------------------------------------------------
			//Save the public key information to an RSAParameters structure.
			System.Security.Cryptography.RSAParameters publicKeyInfo;
			publicKeyInfo = rsa.ExportParameters(false);
			string publicXml = rsa.ToXmlString(false);
			keys.Public = System.Convert.ToBase64String(rsa.ExportCspBlob(false));
			//-----------------------------------------------------
			//Save the public and private key information to an RSAParameters structure.
			System.Security.Cryptography.RSAParameters privateKeyInfo;
			privateKeyInfo = rsa.ExportParameters(true);
			string privateXml = rsa.ToXmlString(true);
			keys.Private = System.Convert.ToBase64String(rsa.ExportCspBlob(true));
			//-----------------------------------------------------
			//System.Security.Cryptography.X509Certificates.PublicKey pubKey;
			//System.Security.Cryptography.X509Certificates.PublicKey pvtKey;
			return keys;
		}
Esempio n. 19
0
        public static string EncryptString(string inputString, int dwKeySize, string xmlString)
        {
            var rsaCryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(dwKeySize);

            rsaCryptoServiceProvider.FromXmlString(xmlString);
            int keySize = dwKeySize / 8;

            byte[]        bytes         = Encoding.UTF32.GetBytes(inputString);
            int           maxLength     = keySize - 42;
            int           dataLength    = bytes.Length;
            int           iterations    = dataLength / maxLength;
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i <= iterations; i++)
            {
                byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
                Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
                byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true);
                Array.Reverse(encryptedBytes);
                stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
            }
            return(stringBuilder.ToString());
        }
Esempio n. 20
0
        public static void Test_BlockchainWithDocumentsSigned()
        {
            // Blockchain with the content having double signature

            System.Security.Cryptography.RSACryptoServiceProvider RSA1 = new System.Security.Cryptography.RSACryptoServiceProvider();
            var PublicKey1Base64 = Convert.ToBase64String(RSA1.ExportCspBlob(false));

            System.Security.Cryptography.RSACryptoServiceProvider RSA2 = new System.Security.Cryptography.RSACryptoServiceProvider();
            var PublicKey2Base64 = Convert.ToBase64String(RSA2.ExportCspBlob(false));

            Blockchain Blocks = new Blockchain("Webmaster", "Phrases", Blockchain.BlockchainType.Binary, true);
            var        Test   = Blocks.Validate();

            byte[] Signature;
            bool   IsValid;

            Blockchain.Block Block1 = new Blockchain.Block(Blocks, "Hi my friends, I have a message for you");
            Signature = RSA1.SignHash(Block1.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            IsValid   = Block1.AddBodySignature(PublicKey1Base64, Signature, false); // Add first signature
            Signature = RSA2.SignHash(Block1.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            IsValid   = Block1.AddBodySignature(PublicKey2Base64, Signature, true);  // Add second signature and closing the block

            Blockchain.Block Block2 = new Blockchain.Block(Blocks, "This is a message number 2, signed");
            Signature = RSA1.SignHash(Block2.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            IsValid   = Block2.AddBodySignature(PublicKey1Base64, Signature, false); // Add first signature
            Signature = RSA2.SignHash(Block2.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            IsValid   = Block2.AddBodySignature(PublicKey2Base64, Signature, true);

            Blockchain.Block Block3 = new Blockchain.Block(Blocks, "In the last block I added the last message");
            Signature = RSA1.SignHash(Block3.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            IsValid   = Block3.AddBodySignature(PublicKey1Base64, Signature, false); // Add first signature
            Signature = RSA2.SignHash(Block3.HashBody(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"));
            IsValid   = Block3.AddBodySignature(PublicKey2Base64, Signature, true);  // Add second signature and closing the block

            int BlockError = Blocks.Validate();                                      // 0 = no error
            var LastBlock  = Blocks.GetLastBlock();
        }
Esempio n. 21
0
        public static string JwtToken(this System.Security.Cryptography.RSACryptoServiceProvider rsaProvider,
                                      string issuer, Uri scope,
                                      IEnumerable <Claim> claims,
                                      DateTime issued, TimeSpan duration,
                                      string algorithm,
                                      IEnumerable <KeyValuePair <string, string> > tokenHeaders = default)
        {
            var securityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsaProvider);

            var signature = new Microsoft.IdentityModel.Tokens.SigningCredentials(
                securityKey, algorithm);
            var expires = (issued + duration);
            var token   = new JwtSecurityToken(issuer, scope.AbsoluteUri, claims, issued, expires, signature);

            foreach (var kvp in tokenHeaders.NullToEmpty())
            {
                token.Header.Add(kvp.Key, kvp.Value);
            }

            var handler = new JwtSecurityTokenHandler();
            var jwt     = handler.WriteToken(token);

            return(jwt);
        }
Esempio n. 22
0
        private string Encrypt(string text)
        {
            // Use OAEP padding (PKCS#1 v2).
            var doOaepPadding = true;
            // ------------------------------------------------
            // RSA Keys
            // ------------------------------------------------
            var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
            //Get the xml params returned form getPublicKey which contains the public key information
            var xmlParams = publicKeyTextBox.Text;

            // Import parameters from XML string.
            rsa.FromXmlString(xmlParams);

            // Export RSA key to RSAParameters and include:
            //    false - Only public key required for encryption.
            // Export parameters and include only Public Key (Modulus + Exponent)
            // required for encryption.
            var rsaParamsPublic = rsa.ExportParameters(false);

            // ------------------------------------------------
            // Encrypt
            // ------------------------------------------------
            var decryptedBytes = System.Text.Encoding.UTF8.GetBytes(text);

            // Create a new instance of RSACryptoServiceProvider.
            rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
            // Import the RSA Key information.
            rsa.ImportParameters(rsaParamsPublic);
            // Encrypt byte array.
            var encryptedBytes = rsa.Encrypt(decryptedBytes, doOaepPadding);
            // Convert bytes to base64 string.
            var encryptedString = System.Convert.ToBase64String(encryptedBytes);

            return(encryptedString);
        }
Esempio n. 23
0
        public void GetSealTest()
        {
            var          cfdiController = new CFDIv33(_MockRepository, _moqSatProvider);
            ICertificate certificate    = _MockRepository.GetCertificate("20001000000200000258");
            string       OriginalChain  = "||3.3|12|12123|2017-06-29T12:00:00|03|20001000000300022815|12312|MXN|14281.92|I|PUE|99100|LAN7008173R5|mi empresa|622|AAA010101AAA|Arlie Cassarubias|G03|01010101|1|1|ZZ|NA|cargo nuevo|12312|12312.000000||";

            byte[] SHA256Hash = cfdiController.GetSHA256(OriginalChain);

            string PassKey = certificate.Pwd;

            System.Security.SecureString secPassPhrase = new System.Security.SecureString();
            foreach (char passChar in PassKey.ToCharArray())
            {
                secPassPhrase.AppendChar(passChar);
            }

            System.Security.Cryptography.RSACryptoServiceProvider privateKey = cfdiController.LoadPrivateKeyFromString(secPassPhrase, certificate.KeyFile);

            var expected = "EeIJKNsieBkYpeEFN/2IUOxJcGjs5TNBEvbHpWwu+61OUevVbUARMTBjNC+OKnTFIReUUy6pVKxAQ6p3x24jj6kTnI205/Chca23VAeaJeG8QKfYY32LaKtdaJmDTMxm/79lrLKQfRda4s7abMNCqcXQu+0lk56d5gOc5IiCwSMcc0/DuDYhQ/WaF9vux5M19vPOcN8wyUuiRtaDS3YzLIGRk45BjMaQGhOZ1mk5+wQP9eFaaMfOXVnzlk2fWJtqnb7/B3dIlvFin6Bn6AVhtLkFMrC0plAZJsAVv589/rPiApAEdNCeSvySnJwTZg0ZlQ7c+PGGL7V/dJcYFH1Mrw==";

            var sello = cfdiController.GetSeal(SHA256Hash, privateKey);

            Assert.AreEqual(sello, expected);
        }
        public static UserInfo DecryptIzendaAuthenticationMessage(string encryptedMessage)
        {
            var rsaPrivateKey = ConfigurationManager.AppSettings["RSAPrivateKey"];
            var cipher        = new System.Security.Cryptography.RSACryptoServiceProvider();

            //Decrypt using RSA private key in PEM format.
            var rsaParam = ConvertPemToXmlFormat(rsaPrivateKey);

            cipher.ImportParameters(rsaParam);
            //End

            ////Decrypt using RSA private key in XML format
            //rsaPrivateKey = "<RSAKeyValue><Modulus>zFZQcdI6f2yIg4m8fn+UnlGPa8Klf01ZIIPH1S2YFKmJpPIRGas04b2RGp+HqV5jmB4w7ClroK9kotuWKg1ySqaMOtg+n5cL/lbgx3j3LYFFsX9TZTwi+MBUpO9fBwBWs2Qly/fVziv4FY0p3YXBJOs/vZZNR5lwhw/dysF6LvU=</Modulus><Exponent>AQAB</Exponent><P>9XAmacVdbLsZOJdq11GvXnVpoeWmEI/52oLQ/3wUpBnDekNvspOMtle8G/7dKR3mm+qenkruTFxnDpfVV53G4w==</P><Q>1SFhB7AFT+/ehxDLgwdWEdBFRdkQzEbzNmk1lKgvZf8amipAw4n7DEjSoyqIXqXXr5DdyqSUDARylWnfzADCRw==</Q><DP>Bcsm7Po+sVFdUAuq9vgzpowo+Sxdlih/4luSKWW5awI8rgcnfNSkzq0VgKesesr85ZNNOTlVlLHdsOd+nrnXtw==</DP><DQ>RUqr3C77GykWRP1N3RS2g+Ydj37p+jAbBJaiB+nCNzwALx0Ln0ct6qmGaev7GCJ9BCRqJ2bohxuvESqxywZ4Iw==</DQ><InverseQ>zjfxF1xREc1TNjbFVUX0Bv+MaUZlqEszLH60WChxL7ArVka5DNbPsY889UMvWuM0/zymfIUlJcxHbMU9dmbuOg==</InverseQ><D>CevO8BfS+0jbv/c6DbJIFv/CxOqoemvY/fkoBLO4BJjOtBGEvwhPAv7fQrmoLpMEpuggW/cO4LhjXHzo55XLjLoRjBBbiPbZayaAeptP9oYMyBNwBp9d49taawXm7nxiOC8sszkzJ0gKFeN+plTQruDm+HspaGBmUHdCMlJ9zak=</D></RSAKeyValue>";
            //cipher.FromXmlString(rsaPrivateKey);
            ////End Decrypt using RSA private key in XML format

            var resultBytes    = Convert.FromBase64String(encryptedMessage);
            var decryptedBytes = cipher.Decrypt(resultBytes, false);
            var decryptedData  = System.Text.Encoding.UTF8.GetString(decryptedBytes);

            var result = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfo>(decryptedData);

            return(result);
        }
Esempio n. 25
0
        /// <summary>
        /// 请求服务器进行加密。如果加密失败,连接将被断开,且抛出异常。
        /// </summary>
        public void RequestEncryption() {
            try {
                // 请求服务器 RSA 公钥
                var ret = Send(new byte[] { (byte)InternalCalls.RequestRSAPublicKey }, 0, 1, block: true, extraFlags: MessageFlags.InternalCalls);
                var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                rsa.PersistKeyInCsp = false;

                var keyxml = Encoding.UTF8.GetString(ret.Value.Array, ret.Value.Offset, ret.Value.Count);
                rsa.FromXmlString(keyxml);

                // 随机产生一个 AES 密钥和 IV,并发送给服务器
                var aesKeyAndIV = RandomHelper.NextStrongRandomByteArray(32, false);

                // 将 AES 密钥信息通过 RSA 加密
                var keyEncrypted = new byte[] { (byte)InternalCalls.SendAESKeysViaRSA }.Concat(rsa.Encrypt(aesKeyAndIV, true)).ToArray();

                ret = Send(keyEncrypted, 0, keyEncrypted.Length, block: true, extraFlags: MessageFlags.InternalCalls);

                // 判断返回值是否成功
                if (ret.HasValue && ret.Value.Count == 1 && ret.Value.Array[ret.Value.Offset] == 0) {
                    AesKey = aesKeyAndIV.Take(16).ToArray();
                    AesIV = aesKeyAndIV.Skip(16).ToArray();
                    IsEncrypted = true;
                    return;
                }

                closeSocket();
                throw new Exception("请求加密失败");
            }
            catch (Exception ex) {
                throw new Exception("请求加密失败", ex);
            }
        }
Esempio n. 26
0
        public void TestRfc7515Example_A_2_1()
        {
            string protectedSample = // From the RFC example
                    "{\"alg\":\"RS256\"}";
            byte[] protectedBytesExpected = // From the RFC example
            {
                123, 34, 97, 108, 103, 34, 58, 34, 82, 83, 50, 53, 54, 34, 125
            };
            byte[] protectedBytesActual = Encoding.UTF8.GetBytes(protectedSample);
            CollectionAssert.AreEqual(protectedBytesExpected, protectedBytesActual);

            string protectedB64uExpected = "eyJhbGciOiJSUzI1NiJ9"; // From the RFC example
            string protectedB64uActual = JOSE.JwsHelper.Base64UrlEncode(protectedBytesActual);
            Assert.AreEqual(protectedB64uExpected, protectedB64uActual);

            string payloadSample = // From the RFC example
                    "{\"iss\":\"joe\",\r\n" +
                    " \"exp\":1300819380,\r\n" +
                    " \"http://example.com/is_root\":true}";
            byte[] payloadBytesActual = Encoding.UTF8.GetBytes(payloadSample);
            string payloadB64uActual = JOSE.JwsHelper.Base64UrlEncode(payloadBytesActual);
            string signingInput = $"{protectedB64uActual}.{payloadB64uActual}";

            byte[] signingBytesExpected = // From the RFC example
            {
                101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73,
                49, 78, 105, 74, 57, 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105,
                74, 113, 98, 50, 85, 105, 76, 65, 48, 75, 73, 67, 74, 108, 101, 72,
                65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107, 122, 79, 68,
                65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76,
                121, 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118,
                98, 83, 57, 112, 99, 49, 57, 121, 98, 50, 57, 48, 73, 106, 112, 48,
                99, 110, 86, 108, 102, 81
            };
            byte[] signingBytesActual = Encoding.ASCII.GetBytes(signingInput);
            CollectionAssert.AreEqual(signingBytesExpected, signingBytesActual);


            byte[] sigExpected = // From the RFC example
            {
                112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69,
                243, 65, 6, 174, 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125,
                131, 101, 109, 66, 10, 253, 60, 150, 238, 221, 115, 162, 102, 62, 81,
                102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, 16, 115, 249, 69,
                229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219,
                61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7,
                16, 141, 178, 129, 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31,
                190, 127, 249, 217, 46, 10, 231, 111, 36, 242, 91, 51, 187, 230, 244,
                74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, 142, 212, 1,
                48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129,
                253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239,
                177, 139, 93, 163, 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202,
                173, 21, 145, 18, 115, 160, 95, 35, 185, 232, 56, 250, 175, 132, 157,
                105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, 212, 14, 96, 69,
                34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202,
                234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90,
                193, 167, 72, 160, 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238,
                251, 71
            };
            byte[] sigActual = null;
            using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
            {
                rsa.ImportParameters(GetRsaParamsForRfc7515Example_A_2_1());
                using (var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                {
                    sigActual = rsa.SignData(signingBytesExpected, sha256);
                }
            }
            CollectionAssert.AreEqual(sigExpected, sigActual);

            string sigB64uExpected = // From the RFC example
                    "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7" +
                    "AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4" +
                    "BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K" +
                    "0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqv" +
                    "hJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrB" +
                    "p0igcN_IoypGlUPQGe77Rw";
            string sigB64uActual = JOSE.JwsHelper.Base64UrlEncode(sigActual);
            Assert.AreEqual(sigB64uExpected, sigB64uActual);
        }
Esempio n. 27
0
 /// <summary>
 /// RSA加密算法
 /// </summary>
 /// <param name="Source">要加密的字符串</param>
 /// <returns>加密后的结果字符串</returns>
 public static byte[] RSA_Encode(string Source)
 {
     System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider();
     provider.FromXmlString("<RSAKeyValue><Modulus>pZGIiC3CxVYpTJ4dLylSy2TLXW+R9EyRZ39ekSosvRKf7iPuz4oPlHqjssh4Glbj/vTUIMFzHFC/9zC56GggNLfZBjh6fc3adq5cXGKlU74kAyM2z7gdYlUHtLT/GwDp4YcQKeSb9GjcvsXbUp0mrzI/axzueLIqK+R07rnv3yc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
     return provider.Encrypt(System.Text.Encoding.UTF8.GetBytes(Source), true);
 }
        public byte[] sign()
        {
            //    byte[] sig=signature.sign();
            //    return sig;
            cs.Close();
            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
            RSA.ImportParameters(RSAKeyInfo);
            System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
            RSAFormatter.SetHashAlgorithm("SHA1");

            byte[] sig = RSAFormatter.CreateSignature( sha1 );
            return  sig;
        }
Esempio n. 29
0
        public void generatekeys()
        {
            System.Security.Cryptography.CspParameters cspParams = null;
            System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null;

            string publicKey = "";
            string privateKey = "";

            try
            {
                cspParams = new System.Security.Cryptography.CspParameters();
                cspParams.ProviderType = 1;
                cspParams.Flags = System.Security.Cryptography.CspProviderFlags.UseArchivableKey;
                cspParams.KeyNumber = (int)System.Security.Cryptography.KeyNumber.Exchange;
                rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams);

                publicKey = rsaProvider.ToXmlString(false);
                privateKey = rsaProvider.ToXmlString(true);

                log("Public Key");
                log(publicKey);
                log("");
                log("Private Key");
                log(privateKey);

                tabControlCode.SelectedIndex = 2;
            }
            catch (Exception ex)
            {

            }
        }
Esempio n. 30
0
        public bool verify(byte[] sig)
        {
            cs.Close();
            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
            RSA.ImportParameters(RSAKeyInfo);
            System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
            RSADeformatter.SetHashAlgorithm("SHA1");

            int i=0;
            int j=0;
            byte[] tmp;

            if(sig[0]==0 && sig[1]==0 && sig[2]==0)
            {
                j=(int)((sig[i++]<<24)&0xff000000)|(byte)((sig[i++]<<16)&0x00ff0000)|(byte)
                    ((sig[i++]<<8)&0x0000ff00)|(byte)((sig[i++])&0x000000ff);
                i+=j;
                j=(int)((sig[i++]<<24)&0xff000000)|(byte)((sig[i++]<<16)&0x00ff0000)|(byte)
                    ((sig[i++]<<8)&0x0000ff00)|(byte)((sig[i++])&0x000000ff);
                tmp=new byte[j];
                Array.Copy(sig, i, tmp, 0, j); sig=tmp;
            }
            //System.out.println("j="+j+" "+Integer.toHexString(sig[0]&0xff));
            //return signature.verify(sig);
            return RSADeformatter.VerifySignature(sha1, sig);
        }
Esempio n. 31
0
        /// <summary>
        /// Loads the private key from a PFX file in the certificate store.
        /// </summary>
        public X509Certificate2 LoadPrivateKey(string thumbprint, string subjectName, System.Security.SecureString password)
        {
            if (m_certificateSubdir == null || !m_certificateSubdir.Exists)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(thumbprint) && string.IsNullOrEmpty(subjectName))
            {
                return(null);
            }

            foreach (FileInfo file in m_certificateSubdir.GetFiles("*.der"))
            {
                try
                {
                    X509Certificate2 certificate = new X509Certificate2(file.FullName);

                    if (!String.IsNullOrEmpty(thumbprint))
                    {
                        if (!string.Equals(certificate.Thumbprint, thumbprint, StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }
                    }

                    if (!String.IsNullOrEmpty(subjectName))
                    {
                        if (!Utils.CompareDistinguishedName(subjectName, certificate.Subject))
                        {
                            if (subjectName.Contains("=") || !certificate.Subject.Contains("CN=" + subjectName))
                            {
                                continue;
                            }
                        }
                    }

                    string fileRoot = file.Name.Substring(0, file.Name.Length - file.Extension.Length);

                    StringBuilder filePath = new StringBuilder();
                    filePath.Append(m_privateKeySubdir.FullName);
                    filePath.Append("\\");
                    filePath.Append(fileRoot);

                    FileInfo privateKeyFile = new FileInfo(filePath.ToString() + ".pfx");

                    certificate = new X509Certificate2(
                        privateKeyFile.FullName,
                        (password == null)?new System.Security.SecureString():password,
                        X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

                    System.Security.Cryptography.RSACryptoServiceProvider rsa = certificate.PrivateKey as System.Security.Cryptography.RSACryptoServiceProvider;

                    if (rsa != null && rsa.CspKeyContainerInfo.Exportable)
                    {
                        int    inputBlockSize = rsa.KeySize / 8 - 42;
                        byte[] bytes1         = rsa.Encrypt(new byte[inputBlockSize], true);
                        byte[] bytes2         = rsa.Decrypt(bytes1, true);

                        if (bytes2 != null)
                        {
                            // Utils.Trace(1, "RSA: {0}", certificate.Thumbprint);
                            return(certificate);
                        }
                    }

                    return(certificate);
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Could not load private key certificate from file: {0}", file.Name);
                }
            }

            return(null);
        }
        /// <summary>
        /// Returns all of the key containers.
        /// </summary>
        private static string[] GetContainerNames()
        {
            const int BUFFSIZE = 25600;
            List<string> containernames = new List<string>();
            byte[] pbData = new byte[BUFFSIZE];
            int pcbData = BUFFSIZE;
            int enumflags = (int)PP_ENUMCONTAINERS;  // specify container enumeration functionality
            IntPtr hProv = IntPtr.Zero;
            int dwFlags = 0;

            int gotcsp = NativeMethods.CryptAcquireContextW(ref hProv, null, null, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET);

            if (gotcsp == 0)
            {
                int error = Marshal.GetLastWin32Error();
                return null;
            }
            
            /*  ----------  Get KeyContainer Names ------------- */
            dwFlags = (int)CRYPT_FIRST;  //required initalization
            StringBuilder sb = new StringBuilder(BUFFSIZE);

            int result = 0;

            do
            {
                result = NativeMethods.CryptGetProvParam(hProv, enumflags, sb, ref pcbData, dwFlags);

                if (result == 0)
                {
                    int error = Marshal.GetLastWin32Error();

                    if (ERROR_MORE_DATA != error)
                    {
                        break;
                    }
                }

                containernames.Add(sb.ToString());

                System.Security.Cryptography.CspParameters csparms = new System.Security.Cryptography.CspParameters();
                csparms.KeyContainerName = sb.ToString();
                csparms.KeyNumber = AT_KEYEXCHANGE;
                csparms.Flags = System.Security.Cryptography.CspProviderFlags.UseMachineKeyStore;

                System.Security.Cryptography.RSACryptoServiceProvider key = new System.Security.Cryptography.RSACryptoServiceProvider(csparms);

                dwFlags = CRYPT_NEXT;
            }
            while (true);

            if (hProv != IntPtr.Zero)
            {
                NativeMethods.CryptReleaseContext(hProv, 0);
            }

            return null;
        }
Esempio n. 33
0
        private string GetFileHash()
        {
            if (SelectPackageFile.ShowDialog(this) == DialogResult.OK)
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                rsa.FromXmlString(m_privateKey);

                System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
                using (System.IO.FileStream fs = new System.IO.FileStream(SelectPackageFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                    return Convert.ToBase64String(rsa.SignHash(sha.ComputeHash(fs), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1")));
            }

            return null;
        }
Esempio n. 34
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            UpdateList lst = new UpdateList();
            List<Update> updates = new List<Update>();
            foreach (Update u in listBox1.Items)
                updates.Add(u);
            lst.Updates = updates.ToArray();
            lst.SignedHash = "";

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

            System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                sr.Serialize(ms, lst);
                ms.Position = 0;
                lst.SignedHash = Convert.ToBase64String(rsa.SignData(ms, System.Security.Cryptography.SHA1.Create()));
            }

            using (System.IO.FileStream fs = new System.IO.FileStream(UpdateFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                sr.Serialize(fs, lst);
        }
Esempio n. 35
0
 public RsaKey()
 {
     iKey = new System.Security.Cryptography.RSACryptoServiceProvider(kKeySizeBits);
     iKeyInfo = iKey.ExportParameters(true);
 }
Esempio n. 36
0
 public override byte[] GetBody()
 {
     MemoryStream stream = new MemoryStream();
     BinaryWriter writer = new BinaryWriter(stream);
     byte[] mashed = Mash(name, additionalNonce);
     writer.Write(mashed.Length);
     writer.Write(mashed, 0, mashed.Length);
     System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
     rsa.ImportCspBlob(publicKeyData);
     MemoryStream combiner = new MemoryStream();
     combiner.Write(startNonce, 0, startNonce.Length);
     combiner.Write(nonce, 0, nonce.Length);
     combiner.Write(passwordHash, 0, passwordHash.Length);
     combiner.Write(additionalNonce, 0, additionalNonce.Length);
     byte[] toSend = rsa.Encrypt(combiner.ToArray(), false);
     writer.Write(toSend.Length);
     writer.Write(toSend, 0, toSend.Length);
     writer.Flush();
     return stream.ToArray();
 }
Esempio n. 37
0
        //***************************************************************************
        // Event Handlers
        //
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.bmp == null)
            {
                return;
            }

            #region Old Write Method
            //// The color code of the very first pixel gives of the cypher "seed".
            //int seed = bmp.GetPixel(0, 0).ToArgb();
            //Color cPwReq = bmp.GetPixel(1, 0);
            //int cPwReqR = cPwReq.R, cPwReqG = cPwReq.G, cPwReqB = cPwReq.B;
            //byte[] rsaBlob = null;
            //using (frmPw frm = new frmPw())
            //    if (frm.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(frm.Password))
            //    {
            //        seed = (seed.ToString() + frm.Password).GetHashCode();
            //        rsaBlob = System.Text.Encoding.UTF8.GetBytes(seed.ToString());
            //        if (cPwReqR % 2 != 0)
            //            if (cPwReqR < 255) cPwReqR++; else cPwReqR--;
            //        if (cPwReqG % 2 != 0)
            //            if (cPwReqG < 255) cPwReqG++; else cPwReqG--;
            //        if (cPwReqB % 2 != 0)
            //            if (cPwReqB < 255) cPwReqB++; else cPwReqB--;
            //    }

            //cPwReq = Color.FromArgb(cPwReq.A, cPwReqR, cPwReqG, cPwReqB);
            //bmp.SetPixel(1, 0, cPwReq);

            //Dictionary<string, string> cypher = this.GetCypher(seed, false);
            //string encryptString = this.textBox1.Text;

            //if (this.chkEncrypt.Checked && rsaBlob != null)
            //{
            //    System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
            //    rsa.ImportCspBlob(rsa.Encrypt(rsaBlob, true));
            //    byte[] rsaData = rsa.Encrypt(System.Text.Encoding.UTF8.GetBytes(encryptString), true);
            //    encryptString = Convert.ToBase64String(rsaData);

            //    Color cRsa = bmp.GetPixel(2, 0);
            //    int cRsaR = cRsa.R, cRsaG = cRsa.G, cRsaB = cRsa.B;
            //    if (cRsaR % 2 != 0)
            //        if (cRsaR < 255) cRsaR++; else cRsaR--;
            //    if (cRsaG % 2 != 0)
            //        if (cRsaG < 255) cRsaG++; else cRsaG--;
            //    if (cRsaB % 2 != 0)
            //        if (cRsaB < 255) cRsaB++; else cRsaB--;
            //    bmp.SetPixel(2, 0, Color.FromArgb(cRsa.A, cRsaR, cRsaG, cRsaB));
            //}
            //encryptString = identString + encryptString;

            //// Now, we're ready to embed the text as a cypher.
            //int x = 2, y = 0;
            //for (int charPos = 0; charPos < encryptString.Length; charPos++)
            //{
            //    // First, get the character at the current position of the secret string.
            //    string curChar = encryptString.Substring(charPos, 1);

            //    // Now determine the character's cypher code.
            //    string cypherCode = string.Empty;

            //    try
            //    { cypherCode = cypher[curChar]; }
            //    catch
            //    // If we don't have that character in our cypher, just ignore it.
            //    {
            //        MessageBox.Show(this, "Unable to find cypher value for character: " + curChar, "Error");
            //        return;
            //    }

            //    // Then, we set the pixels' bits to match the cypher code.
            //    for (int i = 0; i < cypherCode.Length; i += 3)
            //    {
            //        if (x++ > bmp.Width)
            //        { x = 0; y++; }
            //        if (y > bmp.Height)
            //            throw new Exception("The image is too small to contain the selected text.");

            //        // Now, get the pixel at the current position.
            //        Color cpxl = bmp.GetPixel(x, y);
            //        int r = Convert.ToInt32(cpxl.R),
            //            g = Convert.ToInt32(cpxl.G),
            //            b = Convert.ToInt32(cpxl.B);

            //        if (cypherCode.Substring(i, 1) != (r % 2).ToString())
            //            if (r < 255) r++; else r--;
            //        if (cypherCode.Substring(i + 1, 1) != (g % 2).ToString())
            //            if (g < 255) g++; else g--;
            //        if (i + 2 < cypherCode.Length)
            //        {
            //            if (cypherCode.Substring(i + 2, 1) != (b % 2).ToString())
            //                if (b < 255) b++; else b--;
            //        }
            //        else
            //            // For the "ninth" byte in the two pixels, we define whether
            //            //   or not this is the last character with an odd number
            //            //   informing the program to stop parsing.
            //            if (charPos < encryptString.Length - 1)
            //            {
            //                if ((b % 2) != 0)
            //                { if (b < 255)b++; else b--; }
            //            }
            //            else
            //            {
            //                if ((b % 2) != 1)
            //                { if (b < 255)b++; else b--; }
            //            }

            //        // Once we have the correct color values, we need to save them
            //        //   back into the image.
            //        Color nClr = Color.FromArgb(cpxl.A, r, g, b);
            //        bmp.SetPixel(x, y, nClr);
            //    }
            //}
            #endregion

            string outputFn = null;
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.AddExtension = true;
                dlg.DefaultExt   = ".bmp";
                dlg.Filter       = "Image Files|*.bmp;*.jpg;*gif;*.png;*.jpeg;*.tiff|All Files|*.*";
                dlg.FilterIndex  = 0;
                dlg.Title        = "Select Image File";
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    outputFn = dlg.FileName;
                }
                else
                {
                    return;
                }
            }
            // The color code of the very first pixel gives of the cypher "seed".
            int    seed = bmp.GetPixel(0, 0).ToArgb();
            Color  cPwReq = bmp.GetPixel(1, 0);
            int    cPwReqR = cPwReq.R, cPwReqG = cPwReq.G, cPwReqB = cPwReq.B;
            byte[] rsaBlob = null;
            using (frmPw frm = new frmPw())
                if (frm.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(frm.Password))
                {
                    seed    = (seed.ToString() + frm.Password).GetHashCode();
                    rsaBlob = System.Text.Encoding.UTF8.GetBytes(seed.ToString());
                    if (cPwReqR % 2 != 0)
                    {
                        if (cPwReqR < 255)
                        {
                            cPwReqR++;
                        }
                        else
                        {
                            cPwReqR--;
                        }
                    }
                    if (cPwReqG % 2 != 0)
                    {
                        if (cPwReqG < 255)
                        {
                            cPwReqG++;
                        }
                        else
                        {
                            cPwReqG--;
                        }
                    }
                    if (cPwReqB % 2 != 0)
                    {
                        if (cPwReqB < 255)
                        {
                            cPwReqB++;
                        }
                        else
                        {
                            cPwReqB--;
                        }
                    }
                }

            cPwReq = Color.FromArgb(cPwReq.A, cPwReqR, cPwReqG, cPwReqB);
            bmp.SetPixel(1, 0, cPwReq);

            Dictionary <string, string> cypher = this.GetCypher(seed, false);
            string encryptString = this.textBox1.Text;

            if (this.chkEncrypt.Checked && rsaBlob != null)
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                //rsa.ImportCspBlob(rsa.Encrypt(rsaBlob, true));
                byte[] rsaData = rsa.Encrypt(System.Text.Encoding.UTF8.GetBytes(encryptString), true);
                encryptString = Convert.ToBase64String(rsaData);

                Color cRsa = bmp.GetPixel(2, 0);
                int   cRsaR = cRsa.R, cRsaG = cRsa.G, cRsaB = cRsa.B;
                if (cRsaR % 2 != 0)
                {
                    if (cRsaR < 255)
                    {
                        cRsaR++;
                    }
                    else
                    {
                        cRsaR--;
                    }
                }
                if (cRsaG % 2 != 0)
                {
                    if (cRsaG < 255)
                    {
                        cRsaG++;
                    }
                    else
                    {
                        cRsaG--;
                    }
                }
                if (cRsaB % 2 != 0)
                {
                    if (cRsaB < 255)
                    {
                        cRsaB++;
                    }
                    else
                    {
                        cRsaB--;
                    }
                }
                bmp.SetPixel(2, 0, Color.FromArgb(cRsa.A, cRsaR, cRsaG, cRsaB));
            }
            encryptString = identString + encryptString;

            // Now, we're ready to embed the text as a cypher.
            int x = 2, y = 0;
            for (int charPos = 0; charPos < encryptString.Length; charPos++)
            {
                // First, get the character at the current position of the secret string.
                string curChar = encryptString.Substring(charPos, 1);

                // Now determine the character's cypher code.
                string cypherCode = string.Empty;

                try
                { cypherCode = cypher[curChar]; }
                catch
                // If we don't have that character in our cypher, just ignore it.
                {
                    MessageBox.Show(this, "Unable to find cypher value for character: " + curChar, "Error");
                    return;
                }

                // Then, we set the pixels' bits to match the cypher code.
                for (int i = 0; i < cypherCode.Length; i += 3)
                {
                    if (++x >= bmp.Width)
                    {
                        x = 0; ++y;
                    }
                    if (y >= bmp.Height)
                    {
                        throw new Exception("The image is too small to contain the selected text.");
                    }

                    // Now, get the pixel at the current position.
                    Color cpxl = bmp.GetPixel(x, y);
                    int   r    = Convert.ToInt32(cpxl.R),
                          g    = Convert.ToInt32(cpxl.G),
                          b    = Convert.ToInt32(cpxl.B);

                    if (cypherCode.Substring(i, 1) != (r % 2).ToString())
                    {
                        if (r < 255)
                        {
                            r++;
                        }
                        else
                        {
                            r--;
                        }
                    }
                    if (cypherCode.Substring(i + 1, 1) != (g % 2).ToString())
                    {
                        if (g < 255)
                        {
                            g++;
                        }
                        else
                        {
                            g--;
                        }
                    }
                    if (i + 2 < cypherCode.Length)
                    {
                        if (cypherCode.Substring(i + 2, 1) != (b % 2).ToString())
                        {
                            if (b < 255)
                            {
                                b++;
                            }
                            else
                            {
                                b--;
                            }
                        }
                    }
                    else
                    // For the "ninth" byte in the two pixels, we define whether
                    //   or not this is the last character with an odd number
                    //   informing the program to stop parsing.
                    if (charPos < encryptString.Length - 1)
                    {
                        if ((b % 2) != 0)
                        {
                            if (b < 255)
                            {
                                b++;
                            }
                            else
                            {
                                b--;
                            }
                        }
                    }
                    else
                    {
                        if ((b % 2) != 1)
                        {
                            if (b < 255)
                            {
                                b++;
                            }
                            else
                            {
                                b--;
                            }
                        }
                    }

                    // Once we have the correct color values, we need to save them
                    //   back into the image.
                    Color nClr = Color.FromArgb(cpxl.A, r, g, b);
                    bmp.SetPixel(x, y, nClr);
                }
            }
            bmp.Save(outputFn, System.Drawing.Imaging.ImageFormat.Bmp);
        }
Esempio n. 38
0
        protected virtual System.IdentityModel.Tokens.SecurityToken VerifySignature(string signingInput, string signature, string algorithm, System.IdentityModel.Tokens.SecurityToken signingToken)
        {
            Utility.VerifyNonNullArgument("signingToken", signingToken);
            bool flag = false;

            System.IdentityModel.Tokens.SecurityToken result = null;
            if (string.Equals(algorithm, "RS256", System.StringComparison.Ordinal))
            {
                System.IdentityModel.Tokens.X509SecurityToken x509SecurityToken = signingToken as System.IdentityModel.Tokens.X509SecurityToken;
                if (x509SecurityToken == null)
                {
                    throw new System.IdentityModel.Tokens.SecurityTokenException("Unsupported issuer token type for asymmetric signature.");
                }
                System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = x509SecurityToken.Certificate.PublicKey.Key as System.Security.Cryptography.RSACryptoServiceProvider;
                if (rSACryptoServiceProvider == null)
                {
                    throw new System.IdentityModel.Tokens.SecurityTokenException("Unsupported asymmetric signing algorithm.");
                }
                using (X509AsymmetricSignatureProvider x509AsymmetricSignatureProvider = new X509AsymmetricSignatureProvider(rSACryptoServiceProvider))
                {
                    flag = x509AsymmetricSignatureProvider.Verify(Base64UrlEncoder.TextEncoding.GetBytes(signingInput), Base64UrlEncoder.DecodeBytes(signature));
                    if (flag)
                    {
                        result = signingToken;
                    }
                    goto IL_133;
                }
            }
            if (string.Equals(algorithm, "HS256", System.StringComparison.Ordinal))
            {
                byte[] bytes      = Base64UrlEncoder.TextEncoding.GetBytes(signingInput);
                byte[] signature2 = Base64UrlEncoder.DecodeBytes(signature);
                using (System.Collections.Generic.IEnumerator <System.IdentityModel.Tokens.SecurityKey> enumerator = signingToken.SecurityKeys.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        System.IdentityModel.Tokens.SecurityKey          current = enumerator.Current;
                        System.IdentityModel.Tokens.SymmetricSecurityKey symmetricSecurityKey = current as System.IdentityModel.Tokens.SymmetricSecurityKey;
                        if (symmetricSecurityKey != null)
                        {
                            using (SymmetricSignatureProvider symmetricSignatureProvider = new SymmetricSignatureProvider(symmetricSecurityKey))
                            {
                                flag = symmetricSignatureProvider.Verify(bytes, signature2);
                                if (flag)
                                {
                                    result = new BinarySecretSecurityToken(symmetricSecurityKey.GetSymmetricKey());
                                    break;
                                }
                            }
                        }
                    }
                    goto IL_133;
                }
            }
            throw new System.IdentityModel.Tokens.SecurityTokenException("Unsupported signing algorithm.");
IL_133:
            if (!flag)
            {
                throw new System.IdentityModel.Tokens.SecurityTokenException("Invalid issuer or signature.");
            }
            return(result);
        }
Esempio n. 39
0
        private void btnParse_Click(object sender, EventArgs e)
        {
            if (this.bmp == null)
            {
                MessageBox.Show(this, "Please select an image first.", "Does not compute...", MessageBoxButtons.OK);
                this.cmdSelectSrc_Click(sender, e);
                return;
            }

            bool  done   = false;
            int   seed   = bmp.GetPixel(0, 0).ToArgb();
            Color cPwReq = bmp.GetPixel(1, 0);

            byte[] rsaBlob = null;
            if (cPwReq.R % 2 == 0 && cPwReq.G % 2 == 0 && cPwReq.B % 2 == 0)
            {
                using (frmPw frm = new frmPw())
                    if (frm.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(frm.Password))
                    {
                        seed = (seed.ToString() + frm.Password.ToString()).GetHashCode();
                        //rsaBlob = System.Text.Encoding.UTF8.GetBytes(seed.ToString());
                    }
            }

            Dictionary <string, string> cypher = this.GetCypher(seed, true);

            int           x = 3, y = 0;
            StringBuilder identCheck = new StringBuilder();

            #region Old Read Method
            //for (int i = 0; i < identString.Length; i++)
            //{
            //    if (x++ > bmp.Width)
            //    { x = 0; y++; }
            //    Color cPxl1 = bmp.GetPixel(x, y);
            //    int r1 = Convert.ToInt32(cPxl1.R),
            //        g1 = Convert.ToInt32(cPxl1.G),
            //        b1 = Convert.ToInt32(cPxl1.B);

            //    if (x++ > bmp.Width)
            //    { x = 0; y++; }
            //    Color cPxl2 = bmp.GetPixel(x, y);
            //    int r2 = Convert.ToInt32(cPxl2.R),
            //        g2 = Convert.ToInt32(cPxl2.G),
            //        b2 = Convert.ToInt32(cPxl2.B);

            //    if (x++ > bmp.Width)
            //    { x = 0; y++; }
            //    Color cPxl3 = bmp.GetPixel(x, y);
            //    int r3 = Convert.ToInt32(cPxl3.R),
            //        g3 = Convert.ToInt32(cPxl3.G),
            //        b3 = Convert.ToInt32(cPxl3.B);

            //    int c1 = (r1 % 2),
            //        c2 = (g1 % 2),
            //        c3 = (b1 % 2),
            //        c4 = (r2 % 2),
            //        c5 = (g2 % 2),
            //        c6 = (b2 % 2),
            //        c7 = (r3 % 2),
            //        c8 = (g3 % 2),
            //        c9 = (b3 % 2);

            //    string cypherCode = GetCypherCode(c1, c2, c3, c4, c5, c6, c7, c8);
            //    try
            //    { identCheck.Append(cypher[cypherCode]); }
            //    catch
            //    { break; }
            //}
            #endregion

            string msgText = null;
            using (System.IO.FileStream fs = new System.IO.FileStream(this._imgFn, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                //int identBufferLen = (identString.Length * 9) + x;
                //byte[] fsBuffer = new byte[identBufferLen];
                //fs.Read(fsBuffer, 0, fsBuffer.Length);
                //for (int i = x; i < fsBuffer.Length; i += 9)
                //{
                //    if (i > fsBuffer.Length)
                //        throw new Exception("Key check exceeded buffer length.");

                //    int[] vals = new int[8];
                //    for (int j = 0; j < 8; j++)
                //        vals[j] = (fsBuffer[i] % 2);

                //    string cypherCode = GetCypherCode(vals);
                //    try
                //    { identCheck.Append(cypher[cypherCode]); }
                //    catch
                //    { break; }
                //    x += 9;
                //}

                for (int i = x; i < identString.Length + 3; i++)
                {
                    Color cPxl1 = bmp.GetPixel(x, y);
                    int   r1    = Convert.ToInt32(cPxl1.R),
                          g1    = Convert.ToInt32(cPxl1.G),
                          b1    = Convert.ToInt32(cPxl1.B);

                    if (x++ > bmp.Width)
                    {
                        x = 0; y++;
                    }
                    Color cPxl2 = bmp.GetPixel(x, y);
                    int   r2    = Convert.ToInt32(cPxl2.R),
                          g2    = Convert.ToInt32(cPxl2.G),
                          b2    = Convert.ToInt32(cPxl2.B);

                    if (x++ > bmp.Width)
                    {
                        x = 0; y++;
                    }
                    Color cPxl3 = bmp.GetPixel(x, y);
                    int   r3    = Convert.ToInt32(cPxl3.R),
                          g3    = Convert.ToInt32(cPxl3.G),
                          b3    = Convert.ToInt32(cPxl3.B);

                    int c1 = (r1 % 2),
                        c2 = (g1 % 2),
                        c3 = (b1 % 2),
                        c4 = (r2 % 2),
                        c5 = (g2 % 2),
                        c6 = (b2 % 2),
                        c7 = (r3 % 2),
                        c8 = (g3 % 2),
                        c9 = (b3 % 2);

                    // Determine the bits "code value" and find the matching character in the cypher.
                    string cypherCode = GetCypherCode(c1, c2, c3, c4, c5, c6, c7, c8);
                    identCheck.Append(cypher[cypherCode]);
                }

                if (identCheck.ToString() != identString)
                {
                    MessageBox.Show(this, "No message detected.", "Sorry");
                    return;
                }

                StringBuilder sbMsg = new StringBuilder();
                x = identString.Length + 2; y = 0;
                while (!done)
                {
                    // Every three pixels contains 8 "bits" of cypher code, and the
                    //   9th byte tells us if we're done (by being an odd number).

                    if (x++ > bmp.Width)
                    {
                        x = 0; y++;
                    }
                    Color cPxl1 = bmp.GetPixel(x, y);
                    int   r1    = Convert.ToInt32(cPxl1.R),
                          g1    = Convert.ToInt32(cPxl1.G),
                          b1    = Convert.ToInt32(cPxl1.B);

                    if (x++ > bmp.Width)
                    {
                        x = 0; y++;
                    }
                    Color cPxl2 = bmp.GetPixel(x, y);
                    int   r2    = Convert.ToInt32(cPxl2.R),
                          g2    = Convert.ToInt32(cPxl2.G),
                          b2    = Convert.ToInt32(cPxl2.B);

                    if (x++ > bmp.Width)
                    {
                        x = 0; y++;
                    }
                    Color cPxl3 = bmp.GetPixel(x, y);
                    int   r3    = Convert.ToInt32(cPxl3.R),
                          g3    = Convert.ToInt32(cPxl3.G),
                          b3    = Convert.ToInt32(cPxl3.B);

                    int c1 = (r1 % 2),
                        c2 = (g1 % 2),
                        c3 = (b1 % 2),
                        c4 = (r2 % 2),
                        c5 = (g2 % 2),
                        c6 = (b2 % 2),
                        c7 = (r3 % 2),
                        c8 = (g3 % 2),
                        c9 = (b3 % 2);

                    // Determine the bits "code value" and find the matching character in the cypher.
                    string cypherCode = GetCypherCode(c1, c2, c3, c4, c5, c6, c7, c8);
                    sbMsg.Append(cypher[cypherCode]);

                    // Then decide if we should keep processing based on whether the 6th bit
                    //   was divisible by 2.
                    if (c9 != 0)
                    {
                        done = true;
                        break;
                    }
                    x += 9;

                    #region New read method is wrong.  Deals with pixels as though they were one byte each and starts are wrong position.
                    //byte[] fsBufferMsg = new byte[9];
                    //fs.Read(fsBufferMsg, x, fsBufferMsg.Length);

                    //int[] vals = new int[9];
                    //for (int j = 0; j < 9; j++)
                    //    vals[j] = (fsBufferMsg[j] % 2);

                    //string cypherCode = GetCypherCode(vals);
                    //sbMsg.Append(cypher[cypherCode]);

                    //// then decide if we should keep processing based on whether the
                    ////   9th byte was divisible by 2.
                    //if (vals[8] != 0)
                    //{
                    //    done = true;
                    //    break;
                    //}
                    //x += 9;
                    #endregion
                }
                msgText = sbMsg.ToString();
            }
            Color cRsa = bmp.GetPixel(2, 0);
            if (cRsa.R % 2 == 0 && cRsa.G % 2 == 0 && cRsa.B % 2 == 0 && rsaBlob != null)
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                //rsa.ImportCspBlob(rsa.Encrypt(rsaBlob, true));
                byte[] rsaData = rsa.Decrypt(Convert.FromBase64String(msgText), true);
                msgText = System.Text.Encoding.UTF8.GetString(rsaData);
            }

            MessageBox.Show(this, "Image Says:\n\n" + msgText, "Message");
        }
        public async Task ValidLocallySignedAccessToken_FromX509Certificate()
        {
#if NETSTANDARD
            const string sPfx = @"
MIIGMQIBAzCCBfcGCSqGSIb3DQEHAaCCBegEggXkMIIF4DCCAt8GCSqGSIb3DQEHBqCCAtAwggLM
AgEAMIICxQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQImgNbotR3pnACAggAgIICmMHYqn7R
91hqe5gpwTGxNHaDmrvaLWfBq17xyVIdboPxzSAX4MoNasJplZgCzlN4vMwsY9CG3aY/AV5b4qF3
GRlkR5Ou3xJ84WJUkKkjVcql7hXZ8Zl8hyMKfQgW7SYpmJK/I4qYPqz5wg2ivZ4YbH4KA+VL9eaX
XR5KKdePWt+P9T3oFD1GYAjdPRTL/phSflvv01v2vkmx6In5hS10w2LjxyOJQtiHocOyEe7XAtor
bjsPi9jzMQmW5OESh9c+LDgEHCQQrccc0kG9j+GYJ65b7qORGq9OzBarVgiK+QGrC6aZhGgXZjMD
2K/efd4igVN/QqbpMHB+BDkZKQDRiEc4ezDqZ1VRP8T6VrYP/C+vhvPjZLgIacsxzxZ3f497OkOQ
pnrdpvBC6vPUxzsBpSTMcYlUGObWu+PNuwbOsQabps55c/jb67g/POKmkAqnJMFPXY45tT0/FrHX
hVK3rsSXQBwxy9/qzzPN+nBF7VlgvSoVzrF384t5Slf2ehwYTw3sgJoUudZ4c12kyE+uLdrOVl3Q
BHKDLfy1hRgxMQS/c3uNKkSgXAH3lk9SqMZ9dBzUoY2hZ45YogsP0dQDvzs3AQEdhGW0ZoGEQjC/
QcTTvp7lg/M9gRoBUp/DegGjf2p0N1OlPhj4m63Q2XEm65AvOkA5xxs5RTZKgcU28BJjkgEUpVNt
1rnp0sBsMABmtZ4FXP1YNcKCBdNkIYw67DOO5MRfAGqaDqosT3CL9EOGna61KLQEmtOS33NAx49y
ZtCeh/N91jnC+AMjjhhqwzRtrXJ6g/MLxEmmIFvNYcEipeYHfPynhuVywVVH/tj0SqmnDP4cQd4t
HvFQL5frBq963Wl0ToPVAC+koMvsplAr0dvJLVfNceIwggL5BgkqhkiG9w0BBwGgggLqBIIC5jCC
AuIwggLeBgsqhkiG9w0BDAoBAqCCAqYwggKiMBwGCiqGSIb3DQEMAQMwDgQINLkrmjjeasQCAggA
BIICgIc2PtM3mraGPkm8MqvJOEj64fTocAnAHzGVJ8BhwBXkQI++2d9eAGlSB7pO0JioT7uMBwCL
i3zVQ6bvDw2tbgVD3Pmc/qY0TpIySptODk6X1Y9fI1Bwrvgi+6cx7PIdFUrypnL/djNTtVIkIfFk
TO48YTlT6Gsn+z2Pe6asI0PSDoLgmw2yPauN7Xz1KkAg0KHDT+vMlSLaAYWF8k3+/jFNgPVUpaMM
t/DzuJti0R5+eVnpAPkMTJhncumvMdBYzg2Wx0URHzU4+24hSXE8/xMBN3pVsj11T7Eu5jPazIKR
qB5a5dn/ICVx/JHzz5dFonHilIvyiMfNE7VKTTerisEhCSdUgqq+sIhlPAlLTBCoyUgcGiCi7dKW
GAT47PJ4rvJsGHSUcaNORF71W1GqQQ5iTsJK5rPmGpMUmGwjsemmWmgp00BeMtmqO19B1yRrjDZO
atDYISR3UkmeI0A9VlXAspZ2ngmbuWvW0M8nrzwvDLIfgJ8rsFwexIVecFO58j2YSKBmVEykUvSd
x+PH3gr8IWAd/Ct0VNLF1Jk2ktOXx1pnM9GWUl8rbvTvM5lNevArHpWp+7vY6JlkM+trdaSE66Lr
cvvI+faKAnj4QtkmkbKPF0qLFsDssFv7AI0l7/65PhRZwJ12WpZEOKsqkUyAUbQI16Cva6cuY38y
XZ++x67rU4ldumq0YKOJPdPbAtptwMdCn7lepDaxT8mwv4SIZSd37hAP8UNvmRdRWL4dYx3m8Y+l
4hnClZt+GbKmMgXu/o4ua37kOlCV1T0VqmuRzpOwnct8HBvtVS6TuScExeiEkNBA4KwSIY04ZSm+
Sell3vQywF3jry7v/FMgPhoxJTAjBgkqhkiG9w0BCRUxFgQU+7ZMLd/K3gq6I9wxj3LcCb2tf5Uw
MTAhMAkGBSsOAwIaBQAEFOM/amdwLHU0WBmyCw96Za0+5Z+PBAgvp7LF+Qwu+AICCAA=";

            var x509Cert = new X509Certificate2(Convert.FromBase64String(sPfx));
#else
            const string sPrivateKey = @"
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQoMIfUT93VMvb5
4U5dsJLXD1D6z4o/VuVlNUaf5xH01qAv8Egpxe6f5frLB/p1eNyDjNIZ3QitD6aN
9Vfh4ifg6txBuBJtIMfSDvRJITNZ2SjKJREbflZuBk0HINKYQk2H+3TIzUbE/pN4
Cu6Mids5L/oVOnRWIe3bEC+PHR7ZAgMBAAECgYBI1qrwb+2ukeFeK59lcMnQRLVD
l3RLv9ohOy80E7h38RbJgzhR5NnK5ck1AduC7vXjqihIVf6g4F+ghmq4knI94KPQ
2fOyQGVV6jVeRVqMusx7tP9V1H26yABiK6TPklcCsWwADFmexfOxfIgbBGSmlbAd
N2/ad1Xog1xDebrbEQJBAO+2qSIDX1ahfxUyvvcMaix6Mrh/OYKb5aH1Y/7MfAav
lpbQavQHNvak2147aPNxy0ZvWdJ2HVA7hUMkgysYWSUCQQDAZalkZMSrve+Onh55
U+w5xjLklhh8PhYxx8plT8ae9VG75dGvWSz/W81B3ILg2lrNU6o08NKBJdZsJYmc
BeKlAkBtJh3zF9gEaTqlW1rqwKNjpyyLJ5r3JqczzLmAXnmmzbLi7vmULejP+5bL
XH/YQZtOcgtTMmb8jm2Kegijyc1lAkANGt+e5v4+dIGMxVhuCzlb9hQhXdftHo2E
dodivzxYN32Jvu25c+mMu0QP6GVBy53Dvp8pW/36rgkc9LGa3wvBAkEA7dGAl95T
UeNFVfuzkYNtQppcSgrx1oTcpTHoNgcvk8AgBf4yDdJJyo0IUONmgJCVffc1aTWn
nf/8cW9YC+0icQ==";
            const string sCert = @"
MIICNDCCAZ2gAwIBAgIJAKl3qU1+NsuuMA0GCSqGSIb3DQEBCwUAMDMxCzAJBgNV
BAYTAkdCMRMwEQYDVQQIDApTb21lLVN0YXRlMQ8wDQYDVQQKDAZHb29nbGUwHhcN
MTYwODEwMTQwOTQ2WhcNNDMxMjI3MTQwOTQ2WjAzMQswCQYDVQQGEwJHQjETMBEG
A1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGR29vZ2xlMIGfMA0GCSqGSIb3DQEB
AQUAA4GNADCBiQKBgQC0KDCH1E/d1TL2+eFOXbCS1w9Q+s+KP1blZTVGn+cR9Nag
L/BIKcXun+X6ywf6dXjcg4zSGd0IrQ+mjfVX4eIn4OrcQbgSbSDH0g70SSEzWdko
yiURG35WbgZNByDSmEJNh/t0yM1GxP6TeArujInbOS/6FTp0ViHt2xAvjx0e2QID
AQABo1AwTjAdBgNVHQ4EFgQUMqzJi099PA8ML5CV1OSiHgiTGoUwHwYDVR0jBBgw
FoAUMqzJi099PA8ML5CV1OSiHgiTGoUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
AQsFAAOBgQBQ9cMInb2rEcg8TTYq8MjDEegHWLUI9Dq/IvP/FHyKDczza4eX8m+G
3buutN74pX2/GHRgqvqEvvUUuAQUnZ36k6KjTNxfzNLiSXDPNeYmy6PWsUZy4Rye
/Van/ePiXdipTKMiUyl7V6dTjkE5p/e372wNVXUpcxOMmYdWmzSMvg==";

            var privateParams = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(sPrivateKey));
            var x509Cert = new X509Certificate2(Convert.FromBase64String(sCert));
            var rsaParameters = DotNetUtilities.ToRSAParameters(privateParams);
            var privateKey = new System.Security.Cryptography.RSACryptoServiceProvider();
            privateKey.ImportParameters(rsaParameters);
            x509Cert.PrivateKey = privateKey;
#endif
            Assert.That(x509Cert.HasPrivateKey);

            var initializer = new ServiceAccountCredential.Initializer("some-id")
            {
                Clock = new MockClock { UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc) }
            };
            var cred = new ServiceAccountCredential(initializer.FromCertificate(x509Cert));

            Assert.That(cred.Scopes?.Any(), Is.False); // HasScopes must be false for the type of access token we want to test.

            string accessToken = await cred.GetAccessTokenForRequestAsync("http://authurl/");

            string expectedToken =
                "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzb21lLWlkIiwic3ViIjoi" +
                "c29tZS1pZCIsImF1ZCI6Imh0dHA6Ly9hdXRodXJsLyIsImV4cCI6MTQ1MTYxMDAwMCwia" +
                "WF0IjoxNDUxNjA2NDAwfQ.GfpDHgrFi4ZlGC5LuJEarLU4_eTrT5PVa-S40YtkdB2E1f3" +
                "4naYG2ItcfBEFg7Gbdkr1cIAyipuhEd2yLfPmWGwhOwVcBRNyK_J5w8RodS44mxNJwau0" +
                "jKy4x1K20ybLqcnNgzE0wag6fi5GHwdNIB0URdHDTiC88CRYdl1CIdk";
            Assert.That(accessToken, Is.EqualTo(expectedToken));
        }
Esempio n. 41
0
        /// <summary>
        /// 加密
        /// 企业付款到银行卡的公钥加密方法
        /// 公钥可以从 GetPublicKey 获取后用其它工具转换为 xml 导入到 RSACryptoServiceProvider
        /// </summary>
        /// <param name="source"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptToBase64String(this System.Security.Cryptography.RSACryptoServiceProvider source, string input)
        {
            var result = source.Encrypt(Encoding.UTF8.GetBytes(input), true);

            return(Convert.ToBase64String(result));
        }
Esempio n. 42
0
        public string encrypt(string publicKey, string plainText)
        {
            System.Security.Cryptography.CspParameters cspParams = null;
            System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null;
            byte[] plainBytes = null;
            byte[] encryptedBytes = null;

            string result = "";
            try
            {
                cspParams = new System.Security.Cryptography.CspParameters();
                cspParams.ProviderType = 1;
                rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams);

                rsaProvider.FromXmlString(publicKey);

                plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
                encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
                result = Convert.ToBase64String(encryptedBytes);
            }
            catch (Exception ex) { }
            return result;
        }
Esempio n. 43
0
        public static void CreateUpdatePackage(System.Security.Cryptography.RSACryptoServiceProvider key, string inputfolder, string outputfolder, string manifest = null)
        {
            // Read the existing manifest

            UpdateInfo remoteManifest;

            var manifestpath = manifest ?? System.IO.Path.Combine(inputfolder, UPDATE_MANIFEST_FILENAME);

            using (var s = System.IO.File.OpenRead(manifestpath))
                using (var sr = new System.IO.StreamReader(s))
                    using (var jr = new Newtonsoft.Json.JsonTextReader(sr))
                        remoteManifest = new Newtonsoft.Json.JsonSerializer().Deserialize <UpdateInfo>(jr);

            if (remoteManifest.Files == null)
            {
                remoteManifest.Files = new FileEntry[0];
            }

            if (remoteManifest.ReleaseTime.Ticks == 0)
            {
                remoteManifest.ReleaseTime = DateTime.UtcNow;
            }

            var ignoreFiles = (from n in remoteManifest.Files
                               where n.Ignore
                               select n).ToArray();

            var ignoreMap = ignoreFiles.ToDictionary(k => k.Path, k => "", Duplicati.Library.Utility.Utility.ClientFilenameStringComparer);

            remoteManifest.MD5              = null;
            remoteManifest.SHA256           = null;
            remoteManifest.Files            = null;
            remoteManifest.UncompressedSize = 0;

            var localManifest = remoteManifest.Clone();

            localManifest.RemoteURLS = null;

            inputfolder = Duplicati.Library.Utility.Utility.AppendDirSeparator(inputfolder);
            var baselen = inputfolder.Length;
            var dirsep  = System.IO.Path.DirectorySeparatorChar.ToString();

            ignoreMap.Add(UPDATE_MANIFEST_FILENAME, "");

            var md5    = System.Security.Cryptography.MD5.Create();
            var sha256 = System.Security.Cryptography.SHA256.Create();

            Func <string, string> computeMD5 = (path) =>
            {
                md5.Initialize();
                using (var fs = System.IO.File.OpenRead(path))
                    return(Convert.ToBase64String(md5.ComputeHash(fs)));
            };

            Func <string, string> computeSHA256 = (path) =>
            {
                sha256.Initialize();
                using (var fs = System.IO.File.OpenRead(path))
                    return(Convert.ToBase64String(sha256.ComputeHash(fs)));
            };

            // Build a zip
            using (var archive_temp = new Duplicati.Library.Utility.TempFile())
            {
                using (var zipfile = new Duplicati.Library.Compression.FileArchiveZip(archive_temp, new Dictionary <string, string>()))
                {
                    Func <string, string, bool> addToArchive = (path, relpath) =>
                    {
                        if (ignoreMap.ContainsKey(relpath))
                        {
                            return(false);
                        }

                        if (path.EndsWith(dirsep))
                        {
                            return(true);
                        }

                        using (var source = System.IO.File.OpenRead(path))
                            using (var target = zipfile.CreateFile(relpath,
                                                                   Duplicati.Library.Interface.CompressionHint.Compressible,
                                                                   System.IO.File.GetLastAccessTimeUtc(path)))
                            {
                                source.CopyTo(target);
                                remoteManifest.UncompressedSize += source.Length;
                            }

                        return(true);
                    };

                    // Build the update manifest
                    localManifest.Files =
                        (from fse in Duplicati.Library.Utility.Utility.EnumerateFileSystemEntries(inputfolder)
                         let relpath = fse.Substring(baselen)
                                       where addToArchive(fse, relpath)
                                       select new FileEntry()
                    {
                        Path = relpath,
                        LastWriteTime = System.IO.File.GetLastAccessTimeUtc(fse),
                        MD5 = fse.EndsWith(dirsep) ? null : computeMD5(fse),
                        SHA256 = fse.EndsWith(dirsep) ? null : computeSHA256(fse)
                    })
                        .Union(ignoreFiles).ToArray();

                    // Write a signed manifest with the files

                    using (var ms = new System.IO.MemoryStream())
                        using (var sw = new System.IO.StreamWriter(ms))
                        {
                            new Newtonsoft.Json.JsonSerializer().Serialize(sw, localManifest);
                            sw.Flush();

                            using (var ms2 = new System.IO.MemoryStream())
                            {
                                SignatureReadingStream.CreateSignedStream(ms, ms2, key);
                                ms2.Position = 0;
                                using (var sigfile = zipfile.CreateFile(UPDATE_MANIFEST_FILENAME,
                                                                        Duplicati.Library.Interface.CompressionHint.Compressible,
                                                                        DateTime.UtcNow))
                                    ms2.CopyTo(sigfile);
                            }
                        }
                }

                remoteManifest.CompressedSize = new System.IO.FileInfo(archive_temp).Length;
                remoteManifest.MD5            = computeMD5(archive_temp);
                remoteManifest.SHA256         = computeSHA256(archive_temp);

                System.IO.File.Move(archive_temp, System.IO.Path.Combine(outputfolder, "package.zip"));
            }

            // Write a signed manifest for upload

            using (var tf = new Duplicati.Library.Utility.TempFile())
            {
                using (var ms = new System.IO.MemoryStream())
                    using (var sw = new System.IO.StreamWriter(ms))
                    {
                        new Newtonsoft.Json.JsonSerializer().Serialize(sw, remoteManifest);
                        sw.Flush();

                        using (var fs = System.IO.File.Create(tf))
                            SignatureReadingStream.CreateSignedStream(ms, fs, key);
                    }

                System.IO.File.Move(tf, System.IO.Path.Combine(outputfolder, UPDATE_MANIFEST_FILENAME));
            }
        }
Esempio n. 44
0
        public static void CreateSignedStream(System.IO.Stream datastream, System.IO.Stream signedstream, System.Security.Cryptography.RSACryptoServiceProvider key)
        {
            var sha256 = System.Security.Cryptography.SHA256.Create();

            datastream.Position   = 0;
            signedstream.Position = SIGNED_HASH_SIZE;

            var buf   = new byte[8 * 1024];
            var bytes = datastream.Length;

            while (bytes > 0)
            {
                var r = datastream.Read(buf, 0, (int)Math.Min(bytes, buf.Length));
                if (r == 0)
                {
                    throw new Exception("Unexpected end-of-stream while reading content");
                }

                signedstream.Write(buf, 0, r);

                bytes -= r;
                sha256.TransformBlock(buf, 0, r, buf, 0);
            }

            sha256.TransformFinalBlock(buf, 0, 0);
            var hash = sha256.Hash;

            var OID       = System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256");
            var signature = key.SignHash(hash, OID);

            signedstream.Position = 0;
            signedstream.Write(signature, 0, signature.Length);

            signedstream.Position = 0;
            if (!VerifySignature(signedstream, key))
            {
                throw new System.IO.InvalidDataException("Unable to verify signature");
            }
        }
Esempio n. 45
0
 /// <summary>
 /// RSA-Encryption.
 /// </summary>
 public RSA2048()
 {
     csp = new System.Security.Cryptography.RSACryptoServiceProvider();
 }
        public bool verify(byte[] sig)
        {
            cs.Close();
            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
            RSA.ImportParameters(RSAKeyInfo);
            System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
            RSADeformatter.SetHashAlgorithm("SHA1");

            long i=0;
            long j=0;
            byte[] tmp;

            //Util.Dump("c:\\sig.bin", sig);

            if(sig[0]==0 && sig[1]==0 && sig[2]==0)
            {
                long i1 = (sig[i++]<<24)&0xff000000;
                long i2 = (sig[i++]<<16)&0x00ff0000;
                long i3 = (sig[i++]<<8)&0x0000ff00;
                long i4 = (sig[i++])&0x000000ff;
                j = i1 | i2 | i3 | i4;

                i+=j;

                i1 = (sig[i++]<<24)&0xff000000;
                i2 = (sig[i++]<<16)&0x00ff0000;
                i3 = (sig[i++]<<8)&0x0000ff00;
                i4 = (sig[i++])&0x000000ff;
                j = i1 | i2 | i3 | i4;

                tmp=new byte[j];
                Array.Copy(sig, i, tmp, 0, j); sig=tmp;
            }
            //System.out.println("j="+j+" "+Integer.toHexString(sig[0]&0xff));
            //return signature.verify(sig);
            bool verify = RSADeformatter.VerifySignature(sha1, sig);
            return verify;
        }
Esempio n. 47
0
        private static System.Security.Cryptography.RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

            // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
            System.IO.MemoryStream mem  = new System.IO.MemoryStream(privkey);
            System.IO.BinaryReader binr = new System.IO.BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            byte   bt       = 0;
            ushort twobytes = 0;
            int    elems    = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16(); //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                {
                    return(null);
                }
                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    return(null);
                }

                //------  all private key components are Integer sequences ----
                elems   = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ    = binr.ReadBytes(elems);

                //  System.Security.Cryptography.RSA.Create();

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                System.Security.Cryptography.RSACryptoServiceProvider RSA       = new System.Security.Cryptography.RSACryptoServiceProvider();
                System.Security.Cryptography.RSAParameters            RSAparams = new System.Security.Cryptography.RSAParameters();
                RSAparams.Modulus  = MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D        = D;
                RSAparams.P        = P;
                RSAparams.Q        = Q;
                RSAparams.DP       = DP;
                RSAparams.DQ       = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return(RSA);
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                binr.Close();
            }
        }
Esempio n. 48
0
 /// <summary>
 /// RSA解密算法
 /// </summary>
 /// <param name="Source">要解密的字符串</param>
 /// <returns>解密后的结果字符串</returns>
 public static string RSA_Decode(byte[] Source)
 {
     string str;
     System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider();
     provider.FromXmlString("<RSAKeyValue><Modulus>pZGIiC3CxVYpTJ4dLylSy2TLXW+R9EyRZ39ekSosvRKf7iPuz4oPlHqjssh4Glbj/vTUIMFzHFC/9zC56GggNLfZBjh6fc3adq5cXGKlU74kAyM2z7gdYlUHtLT/GwDp4YcQKeSb9GjcvsXbUp0mrzI/axzueLIqK+R07rnv3yc=</Modulus><Exponent>AQAB</Exponent><P>0wCnxVUMgu+Uqp3UJ18bp9Ahdad36wDMwa0tmHxZJUvBZEfcYpsxmSHLpTUBCcAIg2eJL5g/iK9LrIwDBvUZ+w==</P><Q>yOB6ZwG9TuXMRPCA9cFTKCoHEsreDZluptHEfG3HvnS1lp5xwRCHXVuh7VWOM0G2gnZ/JWwWIfcqf30UTWvTxQ==</Q><DP>BTc67nHPwVzSu/TyzZZYRKmsahAdsr1uUktJmT9ZpMZenW/5Tqavby2arxbEU81faIAir/5/c42BvV4opP9iCQ==</DP><DQ>QETR5LMBxoRvXn80Q2yfFnKb4L9XXDKC3IywuL7G8YCVuKLo8kQ/ivcOT8jXvj6ADi2rcGWsjyFtT2zNWhftoQ==</DQ><InverseQ>jwpY6fpkzwtLOABZQncXMC4h7VbYrx+sZeSrBFXAgw1WMSs9YsT6EQcDRjpGt7JAkP14nSTSIVJNd23jZURCLw==</InverseQ><D>cw6SqcfbLVV198d9EnQOFEgkRvcsn2/CMAFET27WjkHuIAiagWE4+H7NWYWUaQFvCZNMAsNMYiX/cSFMYCRUFBBgkPqaqQ3+3qCs/kKiWpDjRwX8eXrMAnWniFDEoxc229Mxl4QZrcYKVRxrCIq8wKamuoWgwN0M+3CAiLwLvNk=</D></RSAKeyValue>");
     try
     {
         str = System.Text.Encoding.UTF8.GetString(provider.Decrypt(Source, true));
     }
     catch (System.Exception)
     {
         return "";
     }
     return str;
 }
Esempio n. 49
0
        private void UpdateAdministration_Load(object sender, EventArgs e)
        {
            if (!System.IO.File.Exists("releasekey.xml"))
            {
                if (MessageBox.Show("Signature key does not exist, create it?", Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    Application.Exit();
                    return;
                }

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter("releasekey.xml", false))
                    sw.Write(rsa.ToXmlString(true));
            }

            using (System.IO.StreamReader rd = new System.IO.StreamReader("releasekey.xml"))
                m_privateKey = rd.ReadToEnd();

            List<Update> updates = new List<Update>();
            System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList));

            UpdateList lst = null;
            if (System.IO.File.Exists(UpdateFile))
                using (System.IO.FileStream fs = new System.IO.FileStream(UpdateFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                    lst = (UpdateList)sr.Deserialize(fs);

            SortedList<string, string> applicationNames = new SortedList<string,string>();
            SortedList<string, string> architectures = new SortedList<string, string>();

            if (lst != null && lst.Updates != null)
                foreach (Update u in lst.Updates)
                {
                    listBox1.Items.Add(u);
                    if (!string.IsNullOrEmpty(u.ApplicationName))
                        applicationNames[u.ApplicationName.ToLower().Trim()] = u.ApplicationName;
                    if (!string.IsNullOrEmpty(u.Architecture))
                        architectures[u.Architecture.ToLower().Trim()] = u.Architecture;
                }

            foreach (string s in architectures.Values)
                if (UpdateArchitecture.FindString(s) < 0)
                    UpdateArchitecture.Items.Add(s);

            foreach (string s in applicationNames.Values)
                if (UpdateApplication.FindString(s) < 0)
                    UpdateApplication.Items.Add(s);
        }
Esempio n. 50
0
 /// <summary>
 /// Creates a new CSP to generate a new RSA key pair.
 /// </summary>
 public void shuffle()
 {
     csp = new System.Security.Cryptography.RSACryptoServiceProvider();
 }
Esempio n. 51
0
 /// <summary>
 /// Generates a Public and a Private key pair used for asymmetrical encryption. (Item1=PublicKey, Item2=PrivateKey)
 /// </summary>
 /// <returns>A <see cref="Tuple{T1, T2}"/> containing the generated Public and Private Keys, respectively.</returns>
 public static Tuple <string, string> GeneratePublicPrivateKeys()
 {
     System.Security.Cryptography.RSACryptoServiceProvider encryptor = new System.Security.Cryptography.RSACryptoServiceProvider(DefaultRSAKeyLengthInBits);
     return(Tuple.Create(encryptor.ToXmlString(false), encryptor.ToXmlString(true)));
 }
Esempio n. 52
0
        private static System.Security.Cryptography.RSACryptoServiceProvider DecodePublicKey(byte[] x509key)
        {
            // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq    = new byte[15];
            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            System.IO.MemoryStream mem  = new System.IO.MemoryStream(x509key);
            System.IO.BinaryReader binr = new System.IO.BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            byte   bt       = 0;
            ushort twobytes = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16(); //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                seq = binr.ReadBytes(15);            //read the Sequence OID
                if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit string is 03 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8203)
                {
                    binr.ReadInt16(); //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                bt = binr.ReadByte();
                if (bt != 0x00) //expect null byte next
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16(); //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                byte lowbyte  = 0x00;
                byte highbyte = 0x00;

                if (twobytes == 0x8102)        //data read as little endian order (actual data order for Integer is 02 81)
                {
                    lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
                }
                else if (twobytes == 0x8202)
                {
                    highbyte = binr.ReadByte(); //advance 2 bytes
                    lowbyte  = binr.ReadByte();
                }
                else
                {
                    return(null);
                }
                byte[] modint  = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
                int    modsize = BitConverter.ToInt32(modint, 0);

                byte firstbyte = binr.ReadByte();
                binr.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);

                if (firstbyte == 0x00)
                {
                    //if first byte (highest order) of modulus is zero, don't include it
                    binr.ReadByte(); //skip this null byte
                    modsize -= 1;    //reduce modulus buffer size by 1
                }

                byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes

                if (binr.ReadByte() != 0x02)              //expect an Integer for the exponent data
                {
                    return(null);
                }
                int    expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
                byte[] exponent = binr.ReadBytes(expbytes);


                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                System.Security.Cryptography.RSACryptoServiceProvider RSA        = new System.Security.Cryptography.RSACryptoServiceProvider();
                System.Security.Cryptography.RSAParameters            RSAKeyInfo = new System.Security.Cryptography.RSAParameters();
                RSAKeyInfo.Modulus  = modulus;
                RSAKeyInfo.Exponent = exponent;
                RSA.ImportParameters(RSAKeyInfo);
                return(RSA);
            }
            catch (Exception)
            {
                return(null);
            }

            finally
            {
                binr.Close();
            }
        }
Esempio n. 53
0
        public bool Connect(string host, int port, string module, bool requirewrite = false)
        {
            if (port == -1)
                port = VersionrDefaultPort;
            IEnumerator<SharedNetwork.Protocol> protocols = SharedNetwork.AllowedProtocols.Cast<SharedNetwork.Protocol>().GetEnumerator();
            Retry:
            if (!protocols.MoveNext())
            {
                Printer.PrintMessage("#e#No valid protocols available.##");
                return false;
            }
            Host = host;
            Port = port;
            Module = module;
            Connected = false;
            try
            {
                Connection = new System.Net.Sockets.TcpClient();
                var connectionTask = Connection.ConnectAsync(Host, Port);
                if (!connectionTask.Wait(5000))
                {
                    throw new Exception(string.Format("Couldn't connect to target: {0}", this.VersionrURL));
                }
            }
            catch (Exception e)
            {
                Printer.PrintError(e.Message);
                return false;
            }
            if (Connection.Connected)
            {
                try
                {
                    Printer.PrintDiagnostics("Connected to server at {0}:{1}", host, port);
                    Handshake hs = Handshake.Create(protocols.Current);
                    hs.RequestedModule = Module;
                    Printer.PrintDiagnostics("Sending handshake...");
                    Connection.NoDelay = true;
                    ProtoBuf.Serializer.SerializeWithLengthPrefix<Handshake>(Connection.GetStream(), hs, ProtoBuf.PrefixStyle.Fixed32);

                    var startTransaction = ProtoBuf.Serializer.DeserializeWithLengthPrefix<Network.StartTransaction>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                    if (startTransaction == null || !startTransaction.Accepted)
                    {
                        Printer.PrintError("#b#Server rejected connection.##");
                        if (startTransaction != null && hs.VersionrProtocol != startTransaction.ServerHandshake.VersionrProtocol)
                            Printer.PrintError("## Protocol mismatch - local: {0}, remote: {1}", hs.VersionrProtocol, startTransaction.ServerHandshake.VersionrProtocol);
                        else
                        {
                            if (startTransaction == null)
                                Printer.PrintError("## Connection terminated unexpectedly.");
                            else
                                Printer.PrintError("## Rejected request.");
                            return false;
                        }
                        Printer.PrintError("#b#Attempting to retry with a lower protocol.##");
                        goto Retry;
                    }
                    Printer.PrintDiagnostics("Server domain: {0}", startTransaction.Domain);
                    if (Workspace != null && !string.IsNullOrEmpty(startTransaction.Domain) && startTransaction.Domain != Workspace.Domain.ToString())
                    {
                        Printer.PrintError("Server domain doesn't match client domain. Disconnecting.");
                        return false;
                    }

                    RemoteDomain = startTransaction.Domain;

                    if (SharedNetwork.SupportsAuthentication(startTransaction.ServerHandshake.CheckProtocol().Value))
                    {
                        var command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                        if (command.Type == NetCommandType.Authenticate)
                        {
                            bool runauth = true;
                            var challenge = ProtoBuf.Serializer.DeserializeWithLengthPrefix<AuthenticationChallenge>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                            if ((!requirewrite && (command.Identifier & 1) != 0) ||
                                (requirewrite && (command.Identifier & 2) != 0)) // server supports unauthenticated access
                            {
                                AuthenticationResponse response = new AuthenticationResponse()
                                {
                                    IdentifierToken = string.Empty,
                                    Mode = AuthenticationMode.Guest
                                };
                                ProtoBuf.Serializer.SerializeWithLengthPrefix(Connection.GetStream(), response, ProtoBuf.PrefixStyle.Fixed32);
                                command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                                if (command.Type == NetCommandType.Acknowledge)
                                    runauth = false;
                            }
                            if (runauth)
                            {
                                bool q = Printer.Quiet;
                                Printer.Quiet = false;
                                Printer.PrintMessage("Server at #b#{0}## requires authentication.", VersionrURL);
                                while (true)
                                {
                                    if (challenge.AvailableModes.Contains(AuthenticationMode.Simple))
                                    {
                                        System.Console.CursorVisible = true;
                                        Printer.PrintMessageSingleLine("#b#Username:## ");
                                        string user = System.Console.ReadLine();
                                        Printer.PrintMessageSingleLine("#b#Password:## ");
                                        string pass = GetPassword();
                                        System.Console.CursorVisible = false;

                                        user = user.Trim(new char[] { '\r', '\n', ' ' });

                                        AuthenticationResponse response = new AuthenticationResponse()
                                        {
                                            IdentifierToken = user,
                                            Mode = AuthenticationMode.Simple,
                                            Payload = System.Text.ASCIIEncoding.ASCII.GetBytes(BCrypt.Net.BCrypt.HashPassword(pass, challenge.Salt))
                                        };
                                        Printer.PrintMessage("\n");
                                        ProtoBuf.Serializer.SerializeWithLengthPrefix(Connection.GetStream(), response, ProtoBuf.PrefixStyle.Fixed32);
                                        command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                                        if (command.Type == NetCommandType.AuthRetry)
                                            Printer.PrintError("#e#Authentication failed.## Retry.");
                                        if (command.Type == NetCommandType.AuthFail)
                                        {
                                            Printer.PrintError("#e#Authentication failed.##");
                                            return false;
                                        }
                                        if (command.Type == NetCommandType.Acknowledge)
                                            break;
                                    }
                                    else
                                    {
                                        Printer.PrintError("Unsupported authentication requirements!");
                                        return false;
                                    }
                                }
                                Printer.Quiet = q;
                            }
                        }
                    }
                    if (startTransaction.Encrypted)
                    {
                        var key = startTransaction.RSAKey;
                        Printer.PrintDiagnostics("Server RSA Key: {0}", key.Fingerprint());

                        var publicKey = new System.Security.Cryptography.RSACryptoServiceProvider();
                        publicKey.ImportParameters(key);

                        Printer.PrintDiagnostics("Generating secret key for data channel...");
                        System.Security.Cryptography.RSAOAEPKeyExchangeFormatter exch = new System.Security.Cryptography.RSAOAEPKeyExchangeFormatter(publicKey);

                        System.Security.Cryptography.AesManaged aesProvider = new System.Security.Cryptography.AesManaged();
                        aesProvider.KeySize = 256;
                        aesProvider.GenerateIV();
                        aesProvider.GenerateKey();

                        AESProvider = aesProvider;
                        AESKey = aesProvider.Key;
                        AESIV = aesProvider.IV;

                        Printer.PrintDiagnostics("Key: {0}", System.Convert.ToBase64String(aesProvider.Key));
                        var keyExchangeObject = new Network.StartClientTransaction() { Key = exch.CreateKeyExchange(aesProvider.Key), IV = exch.CreateKeyExchange(aesProvider.IV) };

                        ProtoBuf.Serializer.SerializeWithLengthPrefix<StartClientTransaction>(Connection.GetStream(), keyExchangeObject, ProtoBuf.PrefixStyle.Fixed32);
                        Connection.GetStream().Flush();
                        Connected = true;
                        SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo()
                        {
                            DecryptorFunction = () => { return Decryptor; },
                            EncryptorFunction = () => { return Encryptor; },
                            Stream = Connection.GetStream(),
                            Workspace = Workspace,
                            Client = true,
                            CommunicationProtocol = protocols.Current
                        };

                        SharedInfo = sharedInfo;
                    }
                    else
                    {
                        Printer.PrintDiagnostics("Using cleartext communication");
                        var keyExchangeObject = new Network.StartClientTransaction();
                        ProtoBuf.Serializer.SerializeWithLengthPrefix<StartClientTransaction>(Connection.GetStream(), keyExchangeObject, ProtoBuf.PrefixStyle.Fixed32);
                        Connection.GetStream().Flush();
                        Connected = true;
                        SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo()
                        {
                            DecryptorFunction = null,
                            EncryptorFunction = null,
                            Stream = Connection.GetStream(),
                            Workspace = Workspace,
                            Client = true,
                            CommunicationProtocol = protocols.Current
                        };
                        SharedInfo = sharedInfo;
                    }
                    return true;
                }
                catch (Exception e)
                {
                    Printer.PrintError("Error encountered: {0}", e);
                    return false;
                }
            }
            else
                return false;
        }
        public async Task ValidLocallySignedAccessToken_FromX509Certificate()
        {
#if NETSTANDARD
            const string sPfx = @"
MIIGMQIBAzCCBfcGCSqGSIb3DQEHAaCCBegEggXkMIIF4DCCAt8GCSqGSIb3DQEHBqCCAtAwggLM
AgEAMIICxQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQImgNbotR3pnACAggAgIICmMHYqn7R
91hqe5gpwTGxNHaDmrvaLWfBq17xyVIdboPxzSAX4MoNasJplZgCzlN4vMwsY9CG3aY/AV5b4qF3
GRlkR5Ou3xJ84WJUkKkjVcql7hXZ8Zl8hyMKfQgW7SYpmJK/I4qYPqz5wg2ivZ4YbH4KA+VL9eaX
XR5KKdePWt+P9T3oFD1GYAjdPRTL/phSflvv01v2vkmx6In5hS10w2LjxyOJQtiHocOyEe7XAtor
bjsPi9jzMQmW5OESh9c+LDgEHCQQrccc0kG9j+GYJ65b7qORGq9OzBarVgiK+QGrC6aZhGgXZjMD
2K/efd4igVN/QqbpMHB+BDkZKQDRiEc4ezDqZ1VRP8T6VrYP/C+vhvPjZLgIacsxzxZ3f497OkOQ
pnrdpvBC6vPUxzsBpSTMcYlUGObWu+PNuwbOsQabps55c/jb67g/POKmkAqnJMFPXY45tT0/FrHX
hVK3rsSXQBwxy9/qzzPN+nBF7VlgvSoVzrF384t5Slf2ehwYTw3sgJoUudZ4c12kyE+uLdrOVl3Q
BHKDLfy1hRgxMQS/c3uNKkSgXAH3lk9SqMZ9dBzUoY2hZ45YogsP0dQDvzs3AQEdhGW0ZoGEQjC/
QcTTvp7lg/M9gRoBUp/DegGjf2p0N1OlPhj4m63Q2XEm65AvOkA5xxs5RTZKgcU28BJjkgEUpVNt
1rnp0sBsMABmtZ4FXP1YNcKCBdNkIYw67DOO5MRfAGqaDqosT3CL9EOGna61KLQEmtOS33NAx49y
ZtCeh/N91jnC+AMjjhhqwzRtrXJ6g/MLxEmmIFvNYcEipeYHfPynhuVywVVH/tj0SqmnDP4cQd4t
HvFQL5frBq963Wl0ToPVAC+koMvsplAr0dvJLVfNceIwggL5BgkqhkiG9w0BBwGgggLqBIIC5jCC
AuIwggLeBgsqhkiG9w0BDAoBAqCCAqYwggKiMBwGCiqGSIb3DQEMAQMwDgQINLkrmjjeasQCAggA
BIICgIc2PtM3mraGPkm8MqvJOEj64fTocAnAHzGVJ8BhwBXkQI++2d9eAGlSB7pO0JioT7uMBwCL
i3zVQ6bvDw2tbgVD3Pmc/qY0TpIySptODk6X1Y9fI1Bwrvgi+6cx7PIdFUrypnL/djNTtVIkIfFk
TO48YTlT6Gsn+z2Pe6asI0PSDoLgmw2yPauN7Xz1KkAg0KHDT+vMlSLaAYWF8k3+/jFNgPVUpaMM
t/DzuJti0R5+eVnpAPkMTJhncumvMdBYzg2Wx0URHzU4+24hSXE8/xMBN3pVsj11T7Eu5jPazIKR
qB5a5dn/ICVx/JHzz5dFonHilIvyiMfNE7VKTTerisEhCSdUgqq+sIhlPAlLTBCoyUgcGiCi7dKW
GAT47PJ4rvJsGHSUcaNORF71W1GqQQ5iTsJK5rPmGpMUmGwjsemmWmgp00BeMtmqO19B1yRrjDZO
atDYISR3UkmeI0A9VlXAspZ2ngmbuWvW0M8nrzwvDLIfgJ8rsFwexIVecFO58j2YSKBmVEykUvSd
x+PH3gr8IWAd/Ct0VNLF1Jk2ktOXx1pnM9GWUl8rbvTvM5lNevArHpWp+7vY6JlkM+trdaSE66Lr
cvvI+faKAnj4QtkmkbKPF0qLFsDssFv7AI0l7/65PhRZwJ12WpZEOKsqkUyAUbQI16Cva6cuY38y
XZ++x67rU4ldumq0YKOJPdPbAtptwMdCn7lepDaxT8mwv4SIZSd37hAP8UNvmRdRWL4dYx3m8Y+l
4hnClZt+GbKmMgXu/o4ua37kOlCV1T0VqmuRzpOwnct8HBvtVS6TuScExeiEkNBA4KwSIY04ZSm+
Sell3vQywF3jry7v/FMgPhoxJTAjBgkqhkiG9w0BCRUxFgQU+7ZMLd/K3gq6I9wxj3LcCb2tf5Uw
MTAhMAkGBSsOAwIaBQAEFOM/amdwLHU0WBmyCw96Za0+5Z+PBAgvp7LF+Qwu+AICCAA=";

            var x509Cert = new X509Certificate2(Convert.FromBase64String(sPfx));
#else
            const string sPrivateKey = @"
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQoMIfUT93VMvb5
4U5dsJLXD1D6z4o/VuVlNUaf5xH01qAv8Egpxe6f5frLB/p1eNyDjNIZ3QitD6aN
9Vfh4ifg6txBuBJtIMfSDvRJITNZ2SjKJREbflZuBk0HINKYQk2H+3TIzUbE/pN4
Cu6Mids5L/oVOnRWIe3bEC+PHR7ZAgMBAAECgYBI1qrwb+2ukeFeK59lcMnQRLVD
l3RLv9ohOy80E7h38RbJgzhR5NnK5ck1AduC7vXjqihIVf6g4F+ghmq4knI94KPQ
2fOyQGVV6jVeRVqMusx7tP9V1H26yABiK6TPklcCsWwADFmexfOxfIgbBGSmlbAd
N2/ad1Xog1xDebrbEQJBAO+2qSIDX1ahfxUyvvcMaix6Mrh/OYKb5aH1Y/7MfAav
lpbQavQHNvak2147aPNxy0ZvWdJ2HVA7hUMkgysYWSUCQQDAZalkZMSrve+Onh55
U+w5xjLklhh8PhYxx8plT8ae9VG75dGvWSz/W81B3ILg2lrNU6o08NKBJdZsJYmc
BeKlAkBtJh3zF9gEaTqlW1rqwKNjpyyLJ5r3JqczzLmAXnmmzbLi7vmULejP+5bL
XH/YQZtOcgtTMmb8jm2Kegijyc1lAkANGt+e5v4+dIGMxVhuCzlb9hQhXdftHo2E
dodivzxYN32Jvu25c+mMu0QP6GVBy53Dvp8pW/36rgkc9LGa3wvBAkEA7dGAl95T
UeNFVfuzkYNtQppcSgrx1oTcpTHoNgcvk8AgBf4yDdJJyo0IUONmgJCVffc1aTWn
nf/8cW9YC+0icQ==";
            const string sCert       = @"
MIICNDCCAZ2gAwIBAgIJAKl3qU1+NsuuMA0GCSqGSIb3DQEBCwUAMDMxCzAJBgNV
BAYTAkdCMRMwEQYDVQQIDApTb21lLVN0YXRlMQ8wDQYDVQQKDAZHb29nbGUwHhcN
MTYwODEwMTQwOTQ2WhcNNDMxMjI3MTQwOTQ2WjAzMQswCQYDVQQGEwJHQjETMBEG
A1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGR29vZ2xlMIGfMA0GCSqGSIb3DQEB
AQUAA4GNADCBiQKBgQC0KDCH1E/d1TL2+eFOXbCS1w9Q+s+KP1blZTVGn+cR9Nag
L/BIKcXun+X6ywf6dXjcg4zSGd0IrQ+mjfVX4eIn4OrcQbgSbSDH0g70SSEzWdko
yiURG35WbgZNByDSmEJNh/t0yM1GxP6TeArujInbOS/6FTp0ViHt2xAvjx0e2QID
AQABo1AwTjAdBgNVHQ4EFgQUMqzJi099PA8ML5CV1OSiHgiTGoUwHwYDVR0jBBgw
FoAUMqzJi099PA8ML5CV1OSiHgiTGoUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
AQsFAAOBgQBQ9cMInb2rEcg8TTYq8MjDEegHWLUI9Dq/IvP/FHyKDczza4eX8m+G
3buutN74pX2/GHRgqvqEvvUUuAQUnZ36k6KjTNxfzNLiSXDPNeYmy6PWsUZy4Rye
/Van/ePiXdipTKMiUyl7V6dTjkE5p/e372wNVXUpcxOMmYdWmzSMvg==";

            var privateParams = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(sPrivateKey));
            var x509Cert      = new X509Certificate2(Convert.FromBase64String(sCert));
            var rsaParameters = DotNetUtilities.ToRSAParameters(privateParams);
            var privateKey    = new System.Security.Cryptography.RSACryptoServiceProvider();
            privateKey.ImportParameters(rsaParameters);
            x509Cert.PrivateKey = privateKey;
#endif
            Assert.That(x509Cert.HasPrivateKey);

            var initializer = new ServiceAccountCredential.Initializer("some-id")
            {
                Clock = new MockClock {
                    UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                }
            };
            var cred = new ServiceAccountCredential(initializer.FromCertificate(x509Cert));

            Assert.That(cred.Scopes?.Any(), Is.False); // HasScopes must be false for the type of access token we want to test.

            string accessToken = await cred.GetAccessTokenForRequestAsync("http://authurl/");

            string expectedToken =
                "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzb21lLWlkIiwic3ViIjoi" +
                "c29tZS1pZCIsImF1ZCI6Imh0dHA6Ly9hdXRodXJsLyIsImV4cCI6MTQ1MTYxMDAwMCwia" +
                "WF0IjoxNDUxNjA2NDAwfQ.GfpDHgrFi4ZlGC5LuJEarLU4_eTrT5PVa-S40YtkdB2E1f3" +
                "4naYG2ItcfBEFg7Gbdkr1cIAyipuhEd2yLfPmWGwhOwVcBRNyK_J5w8RodS44mxNJwau0" +
                "jKy4x1K20ybLqcnNgzE0wag6fi5GHwdNIB0URdHDTiC88CRYdl1CIdk";
            Assert.That(accessToken, Is.EqualTo(expectedToken));
        }
Esempio n. 55
0
        /// <summary>
        /// Initiates an syncronous check for updates
        /// </summary>
        /// <param name="force">A value indicating if the duration and user-enabled check should be bypassed</param>
        public void CheckForUpdates(bool force)
        {
            try
            {
                if (m_config == null)
                {
                    System.Xml.Serialization.XmlSerializer src = new System.Xml.Serialization.XmlSerializer(typeof(Config));
                    using (System.IO.FileStream fs = new System.IO.FileStream(m_configFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                        m_config = (Config)src.Deserialize(fs);
                }

                //This throws an exception if somethings broken
                m_config.CheckValid();

                if (!m_config.Enabled && !force)
                    return;

                if (m_lastCheck == null)
                {
                    string file = m_config.ApplicationName + ".xml";
                    foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                        file = file.Replace(c, '-');

                    file = System.IO.Path.Combine(System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FreshKeeper"), file);

                    if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(file)))
                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(file));

                    if (System.IO.File.Exists(file))
                    {
                        System.Xml.Serialization.XmlSerializer srl = new System.Xml.Serialization.XmlSerializer(typeof(LastCheck));
                        using (System.IO.FileStream fs = new System.IO.FileStream(m_configFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                            m_lastCheck = (LastCheck)srl.Deserialize(fs);
                    }
                    else
                        m_lastCheck = new LastCheck();
                }

                if (Duplicati.Library.Core.Timeparser.ParseTimeInterval(m_config.CheckInterval, m_lastCheck.Time) > DateTime.Now)
                    return;

                Random r = new Random();
                string url = m_config.Urls[r.Next(0, m_config.Urls.Length)];

                System.Net.WebClient wc = new System.Net.WebClient();
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.PreserveWhitespace = true; //Make sure we don't alter the document
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(wc.DownloadData(url)))
                    doc.Load(ms);

                string hash = doc["UpdateList"].Attributes["SignedHash"].Value;
                doc["UpdateList"].Attributes["SignedHash"].Value = "";

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

                UpdateList lst = null;

                using(System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    doc.Save(ms);
                    if (!rsa.VerifyData(ms.ToArray(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(hash)))
                        throw new Exception("Failed to verify signature");
                    ms.Position = 0;
                    System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList));
                    lst = (UpdateList)sr.Deserialize(ms);
                    lst.SignedHash = hash;
                }

                if (lst == null || lst.Updates == null || lst.Updates.Length == 0)
                    return;

                Update newest = lst.Updates[0];

                foreach(Update u in lst.Updates)
                    if (u.Version > newest.Version && (!u.BugfixUpdate || (u.BugfixUpdate && m_config.NotifyOnRevisionChange)))
                        newest = u;

                if (newest.Version > m_config.LocalVersion)
                    if (Updateavailable != null)
                        Updateavailable(this, newest);
            }
            catch (Exception ex)
            {
                RaiseErrorEvent(ex);
                return;
            }
        }