コード例 #1
0
        private T Decrypt <T>(byte[] cipherText)
        {
            var aes       = new AesProvider(this.sessionService.SessionKey);
            var decrypted = aes.Decrypt(cipherText);
            var json      = Encoding.UTF8.GetString(decrypted);
            var result    = JsonConvert.DeserializeObject <T>(json);

            return(result);
        }
コード例 #2
0
ファイル: TOTPMiddleware.cs プロジェクト: farhadzm/TOTP
        public async Task InvokeAsync(HttpContext httpContext)
        {
            if (!httpContext.Request.Headers.ContainsKey(requestKey) || !httpContext.Request.Headers.ContainsKey(clientSecretHeader))
            {
                await WriteToReponseAsync();

                return;
            }

            var    requestKeyHeader = httpContext.Request.Headers[requestKey].ToString();
            string clientSecret     = httpContext.Request.Headers[clientSecretHeader].ToString();

            if (string.IsNullOrEmpty(requestKeyHeader) || string.IsNullOrEmpty(clientSecret))
            {
                await WriteToReponseAsync();

                return;
            }
            //اگر کلید در کش موجود بود یعنی کاربر از کلید تکراری استفاده کرده است
            if (_cache.GetString(requestKeyHeader) != null)
            {
                await WriteToReponseAsync();

                return;
            }
            var dateTimeNow    = DateTime.UtcNow;
            var expireTimeFrom = dateTimeNow.AddMinutes(-1).Ticks;
            var expireTimeTo   = dateTimeNow.Ticks;

            string decryptedRequestHeader = AesProvider.Decrypt(requestKeyHeader, clientSecret);
            var    requestKeyData         = System.Text.Json.JsonSerializer.Deserialize <TOTPRequestDto>(decryptedRequestHeader);

            if (requestKeyData.DateTimeUtcTicks >= expireTimeFrom && requestKeyData.DateTimeUtcTicks <= expireTimeTo)
            {
                //ذخیره کلید درخواست در کش برای جلوگیری از استفاده مجدد از کلید
                await _cache.SetAsync(requestKeyHeader, Encoding.UTF8.GetBytes("KeyExist"), new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(2)
                });
                await _next(httpContext);
            }
            else
            {
                await WriteToReponseAsync();

                return;
            }

            async Task WriteToReponseAsync()
            {
                httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                await httpContext.Response.WriteAsync("Forbidden: You don't have permission to call this api");
            }
        }
コード例 #3
0
ファイル: ProviderTests.cs プロジェクト: tauruscch/NStandard
            static void Test(AesProvider aesProvider)
            {
                var text         = Guid.NewGuid().ToString();
                var cipherIVPair = aesProvider.Encrypt(text.Bytes());

                var bytes         = AesIVHandler.Default.Combine(cipherIVPair);
                var _cipherIVPair = AesIVHandler.Default.Separate(bytes);

                var source = aesProvider.Decrypt(_cipherIVPair).String();

                Assert.Equal(text, source);
            }
コード例 #4
0
ファイル: ProviderTests.cs プロジェクト: zmjack/NStandard
            static void Test(AesProvider aesProvider)
            {
                var text   = Guid.NewGuid().ToString();
                var cipher = aesProvider.Encrypt(text.Bytes());

                var bytes   = cipher.ToBytes();
                var _cipher = new AesCipher().FromBytes(bytes);

                var source = aesProvider.Decrypt(_cipher).String();

                Assert.Equal(text, source);
            }
コード例 #5
0
ファイル: AesTests.cs プロジェクト: mdepaul/XCryptoProvider
        public void GoodKeyAndIVTest(int keyLen, int ivLen)
        {
            AesProvider aes = new AesProvider();
            ShaProvider sha = new ShaProvider();

            byte[] plain    = new byte[] { 0x96, 0x0D, 0x38, 0x4E, 0xE8, 0xE2, 0xE4, 0x7C, 0x32, 0x7D, 0xDB, 0x28, 0x50, 0x15, 0x23, 0x5E, 0xC1, 0xD8, 0x7A, 0x05, 0x19, 0x62, 0x63, 0x23, 0x1F, 0x27, 0x9C, 0x3B, 0xA9, 0x0E, 0x81, 0xB6 };
            string plainHex = plain.ToHex();

            byte[] encrypted = aes.Encrypt(plain);
            byte[] decrypted = aes.Decrypt(encrypted);

            Assert.Equal(plainHex, decrypted.ToHex());
        }
コード例 #6
0
        public void EncryptDecryptByteArrayTest(AesKeySize keySize)
        {
            byte[]     input             = DataHelper.RandomBytes(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            byte[] encryptedData = provider.Encrypt(input, b => b, StandardConverters.StreamToBytes);
            Assert.NotNull(encryptedData);

            byte[] decryptedData = provider.Decrypt(encryptedData, b => b, StandardConverters.StreamToBytes);
            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
コード例 #7
0
ファイル: AesTests.cs プロジェクト: Jacfal/OpenCryptoTool
        public void Aes_Encryption_Decryption_Success(string testPhrase, int keySize)
        {
            // ARRANGE
            var aesCrypto = new AesProvider();

            var key = aesCrypto.GenerateKey(keySize);
            var IV  = aesCrypto.GenerateInitializationVector();

            // ACT
            var encrypted = aesCrypto.Encrypt(testPhrase, key, IV, CipherMode.CBC);
            var decrypted = aesCrypto.Decrypt(encrypted, key, IV, CipherMode.CBC);

            // ASSERT
            Assert.AreEqual(testPhrase, decrypted);
        }
コード例 #8
0
ファイル: SessionService.cs プロジェクト: dizzar99/Insurance
        public async Task RefreshSessionKey()
        {
            var aes    = new AesProvider(this.SessionKey);
            var secret = aes.Encrypt(this.clientRandom);

            string url = $"api/sessions/{this.SessionId}/refresh";

            var result = await this.http.PostAsync(Environment.ApplicationUrl + url, new StringContent(JsonConvert.SerializeObject(secret), Encoding.UTF8, "application/json"));

            var obj = await result.Content.ReadAsStringAsync();

            var refreshedKey = JsonConvert.DeserializeObject <byte[]>(obj);

            this.SessionKey = aes.Decrypt(refreshedKey);
        }
        public void EncryptDecryptStringTest(AesKeySize keySize)
        {
            string     input             = StringHelper.RandomString(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            string encryptedData = provider.Encrypt(input);

            Assert.NotNull(encryptedData);

            string decryptedData = provider.Decrypt(encryptedData);

            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
コード例 #10
0
ファイル: AesTests.cs プロジェクト: mdepaul/XCryptoProvider
        public void EncryptDecryptTest(string hexKey, string hexIv, string plainText)
        {
            byte[] key        = hexKey.FromHex();
            byte[] iv         = hexIv.FromHex();
            byte[] plainBytes = plainText.FromHex();

            AesProvider aes = new AesProvider(key, iv);

            byte[] encrptedBytes  = aes.Encrypt(plainBytes);
            byte[] decryptedBytes = aes.Decrypt(encrptedBytes);

            string encryptedHex = encrptedBytes.ToHex();
            string decryptedHex = decryptedBytes.ToHex();

            Assert.Equal(plainText, decryptedHex, true);
        }
コード例 #11
0
        public void EncryptDecryptStringTest(AesKeySize keySize)
        {
            string     input             = DataHelper.RandomString(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            string encryptedData = provider.Encrypt(input, Encoding.UTF8.GetBytes, StandardConverters.StreamToBase64String);

            Assert.NotNull(encryptedData);

            string decryptedData = provider.Decrypt(encryptedData, Convert.FromBase64String, StandardConverters.StreamToString);

            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
コード例 #12
0
        private async Task <T> GetResponseResultFromServer <T>(HttpResponseMessage response)
        {
            bool   hasError = response.IsSuccessStatusCode;
            string json;

            if (!hasError)
            {
                var byteResult = await response.Content.ReadAsByteArrayAsync();

                var aes = new AesProvider(this.sessionService.SessionKey);
                var decryptedByteResult = aes.Decrypt(byteResult);
                json = Encoding.UTF8.GetString(decryptedByteResult);
                return(JsonConvert.DeserializeObject <T>(json));
            }
            else
            {
                var responseMessage = await response.Content.ReadAsStringAsync();

                var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(responseMessage);
                var error         = errorResponse.ErrorMessage;
                switch (error)
                {
                case "Session key expired.":
                {
                    await this.sessionService.RefreshSessionKey();

                    throw new Exception("Refresh sessionKey.");
                }

                case "Invalid token.":
                {
                    throw new Exception("Refresh access token.");
                }

                default:
                {
                    throw new Exception(error);
                }
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// 测试操作的可用性
        /// </summary>
        /// <remarks>
        /// 测试完成后,需删除方法内部所有内容, 并返回false
        /// </remarks>
        /// <returns>是否正在测试,true: 正在测试, false: 不在测试</returns>
        private static bool AesTest()
        {
            Rsa();
            return(true);

            var text       = "Hello World!";
            var encryptKey = Guid.NewGuid().ToString("N"); //"d9b46c3513654f66bea91f7e81009ce9";
            var key        = encryptKey.ToBytes();
            //key = Encoding.UTF8.GetBytes(encryptKey);
            var iv = new byte[16];

            var enc = AesProvider.Encrypt(text, key, iv);
            var dec = AesProvider.Decrypt(enc, key, iv);

            Console.WriteLine($"加密前:{text}");
            Console.WriteLine($"加密后:{enc}");
            Console.WriteLine($"   key:{BitConverter.ToString(key).Replace("-", "")}");
            Console.WriteLine($"    iv:{BitConverter.ToString(iv).Replace("-", "")}");

            return(true);
        }
コード例 #14
0
ファイル: TemporyTicket.cs プロジェクト: zmjack/Dawnx
        public static TemporaryTicket Parse(AesProvider aesProvider, string ciphertext)
        {
            var json = aesProvider.Decrypt(ciphertext.Flow(BytesFlow.FromUrlSafeBase64)).String();

            return(JsonConvert.DeserializeObject <TemporaryTicket>(json));
        }