Esempio n. 1
1
		public void DefaultCtor() {
			Nonce nonce = new Nonce();
			Assert.Less((DateTime.Now - nonce.CreationDate).TotalSeconds, 2);
			Assert.GreaterOrEqual(nonce.Age.TotalSeconds, 0);
			Assert.LessOrEqual(nonce.Age.TotalSeconds, 2);
			Assert.IsFalse(nonce.IsExpired);
			Assert.AreEqual(nonce.CreationDate + Protocol.MaximumUserAgentAuthenticationTime, nonce.ExpirationDate);
			Assert.IsFalse(string.IsNullOrEmpty(nonce.Code));
		}
Esempio n. 2
0
 public void EqualsTest()
 {
     Assert.AreNotEqual(new Nonce(), new Nonce());
     Nonce nonce1 = new Nonce();
     Nonce nonce2 = new Nonce(nonce1.Code, false);
     Assert.AreEqual(nonce1, nonce2);
 }
Esempio n. 3
0
		public void ExpiredNonce() {
			string code = "somecode";
			TimeSpan age = Protocol.MaximumUserAgentAuthenticationTime.Add(TimeSpan.FromSeconds(10));
			DateTime creationDate = DateTime.Now.Subtract(age);
			Nonce nonce = new Nonce(creationDate, code, false);
			Assert.AreEqual(creationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") + code, nonce.Code);
			Assert.AreEqual(creationDate.ToUniversalTime(), nonce.CreationDate);
			Assert.Less(((DateTime.Now - age) - creationDate).TotalSeconds, 2);
			Assert.IsTrue(nonce.IsExpired);
		}
Esempio n. 4
0
            public async Task WhenNonceIsInCache_AndItIsNotNull_ReturnsCachedNonce()
            {
                var cachedNonce = new Nonce("c1", "abc123", _now.AddMinutes(1));
                var cacheKey    = CacheKeyFactory(cachedNonce);
                var cacheEntry  = _cache.CreateEntry(cacheKey);

                cacheEntry.Value = cachedNonce;

                var actual = await _sut.Get(cachedNonce.ClientId, cachedNonce.Value);

                actual.Should().Be(cachedNonce);
            }
            public async Task WhenThereIsAPreviousNonce_ThatIsNotExpired_ReturnsSignatureVerificationFailure()
            {
                var nonce = new Nonce(_client.Id, _signature.Nonce, _now.AddSeconds(1));

                A.CallTo(() => _nonceStore.Get(_client.Id, _signature.Nonce))
                .Returns(nonce);

                var actual = await _method(_signedRequest, _signature, _client);

                actual.Should().NotBeNull().And.BeAssignableTo <SignatureVerificationFailure>()
                .Which.Code.Should().Be("REPLAYED_REQUEST");
            }
Esempio n. 6
0
 public override byte[] ToBytes()
 {
     return(TLUtils.Combine(
                TLUtils.SignatureToBytes(Signature),
                PQ.ToBytes(),
                P.ToBytes(),
                Q.ToBytes(),
                Nonce.ToBytes(),
                ServerNonce.ToBytes(),
                NewNonce.ToBytes(),
                DCId.ToBytes()));
 }
Esempio n. 7
0
 public PreEvaluationBlock(
     IBlockContent <T> content,
     HashAlgorithmType hashAlgorithm,
     Nonce nonce
     )
     : base(
         new BlockContent <T>(content),
         hashAlgorithm,
         nonce
         )
 {
 }
            public async Task Upserts()
            {
                var nonce1 = new Nonce(new KeyId("c1"), "abc123", _now.AddMinutes(1));
                await _sut.Register(nonce1);

                var nonce2 = new Nonce(nonce1.ClientId, nonce1.Value, _now.AddMinutes(2));
                await _sut.Register(nonce2);

                var actual = await _sut.Get(nonce1.ClientId, nonce1.Value);

                actual.Should().BeEquivalentTo(nonce2);
            }
Esempio n. 9
0
        public static void NotEqual(byte[] bytes)
        {
            var expected = new Nonce(new byte[] { 0xFF, 0xFF }, 0);
            var actual   = new Nonce(bytes, 0);

            Assert.NotEqual(expected, actual);
            Assert.NotEqual(expected.GetHashCode(), actual.GetHashCode());
            Assert.False(expected.Equals(actual));
            Assert.False(expected.Equals((object)actual));
            Assert.False(expected == actual);
            Assert.True(expected != actual);
        }
Esempio n. 10
0
        public static void Equal(int size)
        {
            var expected = new Nonce(Utilities.RandomBytes.Slice(0, size), 0);
            var actual   = new Nonce(Utilities.RandomBytes.Slice(0, size), 0);

            Assert.Equal(expected, actual);
            Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
            Assert.True(actual.Equals(expected));
            Assert.True(actual.Equals((object)expected));
            Assert.True(actual == expected);
            Assert.False(actual != expected);
        }
Esempio n. 11
0
        /// <summary>
        /// Creates a <see cref="Block{T}"/> instance by manually filling all field values.
        /// For a more automated way, see also <see cref="Mine"/> method.
        /// </summary>
        /// <param name="index">The height of the block to create.  Goes to the <see cref="Index"/>.
        /// </param>
        /// <param name="difficulty">The mining difficulty that <paramref name="nonce"/> has to
        /// satisfy.  Goes to the <see cref="Difficulty"/>.</param>
        /// <param name="nonce">The nonce which satisfy the given <paramref name="difficulty"/> with
        /// any other field values.  Goes to the <see cref="Nonce"/>.</param>
        /// <param name="miner">An optional address refers to who mines this block.
        /// Goes to the <see cref="Miner"/>.</param>
        /// <param name="previousHash">The previous block's <see cref="Hash"/>.  If it's a genesis
        /// block (i.e., <paramref name="index"/> is 0) this should be <c>null</c>.
        /// Goes to the <see cref="PreviousHash"/>.</param>
        /// <param name="timestamp">The time this block is created.  Goes to
        /// the <see cref="Timestamp"/>.</param>
        /// <param name="transactions">The transactions to be mined together with this block.
        /// Transactions become sorted in an unpredicted-before-mined order and then go to
        /// the <see cref="Transactions"/> property.
        /// </param>
        /// <seealso cref="Mine"/>
        public Block(
            long index,
            long difficulty,
            Nonce nonce,
            Address?miner,
            HashDigest <SHA256>?previousHash,
            DateTimeOffset timestamp,
            IEnumerable <Transaction <T> > transactions)
        {
            Index        = index;
            Difficulty   = difficulty;
            Nonce        = nonce;
            Miner        = miner;
            PreviousHash = previousHash;
            Timestamp    = timestamp;
            Transactions = transactions.OrderBy(tx => tx.Id).ToArray();
            Hash         = Hashcash.Hash(ToBencodex(false, false));

            // As the order of transactions should be unpredictable until a block is mined,
            // the sorter key should be derived from both a block hash and a txid.
            var hashInteger = new BigInteger(Hash.ToByteArray());

            // If there are multiple transactions for the same signer these should be ordered by
            // their tx nonces.  So transactions of the same signer should have the same sort key.
            // The following logic "flattens" multiple tx ids having the same signer into a single
            // txid by applying XOR between them.
            IImmutableDictionary <Address, IImmutableSet <Transaction <T> > > signerTxs = Transactions
                                                                                          .GroupBy(tx => tx.Signer)
                                                                                          .ToImmutableDictionary(
                g => g.Key,
                g => (IImmutableSet <Transaction <T> >)g.ToImmutableHashSet()
                );
            IImmutableDictionary <Address, BigInteger> signerTxIds = signerTxs
                                                                     .ToImmutableDictionary(
                pair => pair.Key,
                pair => pair.Value
                .Select(tx => new BigInteger(tx.Id.ToByteArray()))
                .OrderBy(txid => txid)
                .Aggregate((a, b) => a ^ b)
                );

            // Order signers by values derivied from both block hash and their "flatten" txid:
            IImmutableList <Address> signers = signerTxIds
                                               .OrderBy(pair => pair.Value ^ hashInteger)
                                               .Select(pair => pair.Key)
                                               .ToImmutableArray();

            // Order transactions for each signer by their tx nonces:
            Transactions = signers
                           .SelectMany(signer => signerTxs[signer].OrderBy(tx => tx.Nonce))
                           .ToImmutableArray();
        }
Esempio n. 12
0
 private byte[] GetEncodedRaw()
 {
     return(CustomRLP.EncodeList(
                RLP.EncodeElement(Nonce.HexToByteArray()),
                RLP.EncodeElement(To.HexToByteArray()),
                RLP.EncodeElement(Value.HexToByteArray()),
                RLP.EncodeElement(Data.HexToByteArray()),
                RLP.EncodeElement(Timestamp.HexToByteArray()),
                CustomRLP.EncodeLong(Gas),
                CustomRLP.EncodeLong(GasPrice),
                RLP.EncodeElement(Type.HexToByteArray())
                ));
 }
Esempio n. 13
0
        public void CompareToSameDateNonce()
        {
            // Arrange
            var date   = DateTime.Now;
            var nonce1 = Nonce.FromDate(date);
            var nonce2 = Nonce.FromDate(date);

            // Act
            var actual = nonce1.CompareTo(nonce2);

            // Assert
            Assert.AreEqual(0, actual);
        }
Esempio n. 14
0
 private static string GetExpected(
     string samlToken,
     Nonce nonce,
     byte[] bodyhash,
     SigningAlgorithm signAlg,
     byte[] signature)
 {
     return($"SIGN token=\"{Bas64CompressedUtf8(samlToken)}\", " +
            $"nonce=\"{nonce}\", " +
            $"bodyhash=\"{Convert.ToBase64String(bodyhash)}\", " +
            $"signature_alg=\"{SigningAlgorithmConverter.EnumToString(signAlg)}\", " +
            $"signature=\"{Convert.ToBase64String(signature)}\"");
 }
Esempio n. 15
0
        public void ThrowsOnRepeat()
        {
            // Arrange
            var date  = DateTime.Now;
            var nonce = Nonce.FromDate(date);


            var verifier = new RequestsVerifier(2, 4);

            // Act & Assert
            Assert.DoesNotThrow(() => verifier.VerifyAgeAndRepeatOnNewRequest(nonce));
            Assert.Throws <AuthException>(() => verifier.VerifyAgeAndRepeatOnNewRequest(nonce));
        }
        public Task Register(Nonce nonce)
        {
            if (nonce == null)
            {
                throw new ArgumentNullException(nameof(nonce));
            }

            var cacheKey = CacheKeyFactory(nonce.ClientId, nonce.Value);

            _cache.Set(cacheKey, nonce, nonce.Expiration);

            return(_decorated.Register(nonce));
        }
Esempio n. 17
0
        public async Task ChallengeAsync(AuthType type, Nonce nonce, string challenge)
        {
            AuthType  = type;
            AuthNonce = nonce;

            Authenticating = true;
            Authenticated  = false;

            await SendAsync(new ChallengeMessage()
            {
                Challenge = Convert.ToBase64String(Encoding.UTF8.GetBytes(challenge)),
            }).ConfigureAwait(false);
        }
Esempio n. 18
0
        public void DecryptWithTestVectors(string name, uint counter, byte[] keybytes, byte[] ciphertext, byte[] noncebytes, byte[] expected)
        {
            var key   = new Key(keybytes);
            var nonce = new Nonce(noncebytes);

            var cipher = new ChaCha20 {
                Key = key, Counter = counter
            };
            var plaintext = new byte[ciphertext.Length];

            cipher.Decrypt(ciphertext, 0, plaintext, 0, ciphertext.Length, in nonce);
            Assert.Equal(expected, plaintext);
        }
Esempio n. 19
0
        public static void DecryptWithCiphertextOverlapping(AeadAlgorithm a)
        {
            using (var k = new Key(a))
            {
                var n  = new Nonce(Utilities.RandomBytes.Slice(0, a.NonceSize), 0);
                var ad = Utilities.RandomBytes.Slice(0, 100).ToArray();

                var b = Utilities.RandomBytes.Slice(200, 200).ToArray();

                Assert.Throws <ArgumentException>("plaintext", () => a.Decrypt(k, n, ad, b.AsSpan(10, 100 + a.TagSize), b.AsSpan(60, 100)));
                Assert.Throws <ArgumentException>("plaintext", () => a.Decrypt(k, n, ad, b.AsSpan(60, 100 + a.TagSize), b.AsSpan(10, 100)));
            }
        }
Esempio n. 20
0
        public void CompareToNewerDateNonce()
        {
            // Arrange
            var date   = DateTime.Now;
            var nonce1 = Nonce.FromDate(date);
            var nonce2 = Nonce.FromDate(date.Subtract(new TimeSpan(0, 0, 0, 1)));

            // Act
            var actual = nonce1.CompareTo(nonce2);

            // Assert
            Assert.IsTrue(actual > 0);
        }
Esempio n. 21
0
            public async Task WhenNonceIsInCache_AndItIsNotNull_DoesNotCallDecoratedService()
            {
                var cachedNonce = new Nonce("c1", "abc123", _now.AddMinutes(1));
                var cacheKey    = CacheKeyFactory(cachedNonce);
                var cacheEntry  = _cache.CreateEntry(cacheKey);

                cacheEntry.Value = cachedNonce;

                await _sut.Get(cachedNonce.ClientId, cachedNonce.Value);

                A.CallTo(() => _decorated.Get(A <KeyId> ._, A <string> ._))
                .MustNotHaveHappened();
            }
Esempio n. 22
0
        public Rfc7905(
            Role role,
            AeadAlgorithm algorithm,
            Key clientWriteKey,
            ReadOnlySpan <byte> clientWriteIV,
            Key serverWriteKey,
            ReadOnlySpan <byte> serverWriteIV)
        {
            Debug.Assert(algorithm.NonceSize == 12);
            Debug.Assert(clientWriteIV.Length == 12);
            Debug.Assert(serverWriteIV.Length == 12);

            _algorithm = algorithm;

            switch (role)
            {
            // if this is the server side, use serverWriteKey and
            // serverWriteIV for sending, and clientWriteKey and
            // clientWriteIV for receiving
            case Role.Server:
                _sendKey = serverWriteKey;
                _sendIV  = new Nonce(fixedField: serverWriteIV,
                                     counterFieldSize: 0);
                _sendSequenceNumber = new Nonce(fixedFieldSize: 4,
                                                counterFieldSize: 8);

                _receiveKey = clientWriteKey;
                _receiveIV  = new Nonce(fixedField: clientWriteIV,
                                        counterFieldSize: 0);
                _receiveSequenceNumber = new Nonce(fixedFieldSize: 4,
                                                   counterFieldSize: 8);
                break;

            // if this is the client side, use clientWriteKey and
            // clientWriteIV for sending, and serverWriteKey and
            // serverWriteIV for receiving
            case Role.Client:
                _sendKey = clientWriteKey;
                _sendIV  = new Nonce(fixedField: clientWriteIV,
                                     counterFieldSize: 0);
                _sendSequenceNumber = new Nonce(fixedFieldSize: 4,
                                                counterFieldSize: 8);

                _receiveKey = serverWriteKey;
                _receiveIV  = new Nonce(fixedField: serverWriteIV,
                                        counterFieldSize: 0);
                _receiveSequenceNumber = new Nonce(fixedFieldSize: 4,
                                                   counterFieldSize: 8);
                break;
            }
        }
Esempio n. 23
0
        public override async Task <string> Sell(Order order)
        {
            string url      = "https://poloniex.com/tradingApi";
            var    postPars = new Dictionary <string, string>();

            postPars.Add("command", "sell");
            postPars.Add("currencyPair", order.Pair);
            postPars.Add("rate", order.Price.ToString(CultureInfo.InvariantCulture));
            postPars.Add("amount", order.Amount.ToString(CultureInfo.InvariantCulture));
            postPars.Add("nonce", Nonce.ToString());
            string result = await SendPrivateApiRequestAsync(url, postPars);

            return(result);
        }
        public Locked(byte[] locked, Nonce nonce)
        {
            if (locked == null)
            {
                throw new ArgumentNullException(nameof(locked));
            }
            else if (nonce == null)
            {
                throw new ArgumentNullException(nameof(nonce));
            }

            Ciphertext = locked;
            Nonce      = nonce;
        }
Esempio n. 25
0
        public static void CompareValue(int first, int second)
        {
            var left  = new Nonce(0, 4) + first;
            var right = new Nonce(0, 4) + second;

            var expected = Math.Sign(first.CompareTo(second));
            var actual   = left.CompareTo(right);

            Assert.Equal(expected, actual);
            Assert.Equal(expected < 0, left < right);
            Assert.Equal(expected <= 0, left <= right);
            Assert.Equal(expected > 0, left > right);
            Assert.Equal(expected >= 0, left >= right);
        }
 /// <inheritdoc />
 public override int GetHashCode()
 {
     unchecked {
         int hashCode = FunctionType.GetHashCode();
         hashCode = (hashCode * 397) ^ FunctionName.ToLowerInvariant().GetHashCode();
         hashCode = (hashCode * 397) ^ (FunctionConfiguration != null ? FunctionConfiguration.GetHashCodeExt() : 0);
         hashCode = (hashCode * 397) ^ (KeySizeBits.HasValue ? KeySizeBits.Value.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Nonce != null ? Nonce.GetHashCodeExt() : 0);
         hashCode = (hashCode * 397) ^ (Salt != null ? Salt.GetHashCodeExt() : 0);
         hashCode = (hashCode * 397) ^ (AdditionalData != null ? AdditionalData.GetHashCodeExt() : 0);
         hashCode = (hashCode * 397) ^ (OutputSizeBits.HasValue ? OutputSizeBits.Value.GetHashCode() : 0);
         return(hashCode);
     }
 }
Esempio n. 27
0
 public string Serialize()
 {
     return("0x" + AionUtils.ByteToHex(RLP.EncodeList(
                                           RLP.EncodeElement(Nonce.HexToByteArray()),
                                           RLP.EncodeElement(To.HexToByteArray()),
                                           RLP.EncodeElement(Value.HexToByteArray()),
                                           RLP.EncodeElement(Data.HexToByteArray()),
                                           RLP.EncodeElement(Timestamp.HexToByteArray()),
                                           CustomRLP.EncodeLong(Gas),
                                           CustomRLP.EncodeLong(GasPrice),
                                           RLP.EncodeElement(Type.HexToByteArray()),
                                           RLP.EncodeElement(Signature)
                                           )));
 }
Esempio n. 28
0
            public async Task AddsToCacheWithExpectedExpiration()
            {
                var nonce = new Nonce(new KeyId("c1"), "abc123", _now.AddSeconds(30));

                var cacheKey = "CacheEntry_Nonce_c1_abc123";

                _cache.TryGetValue(cacheKey, out _).Should().BeFalse();

                await _sut.Register(nonce);

                _cache.TryGetEntry(cacheKey, out var actualEntry).Should().BeTrue();
                actualEntry.As <ICacheEntry>().Value.Should().Be(nonce);
                actualEntry.As <ICacheEntry>().AbsoluteExpiration.Should().Be(nonce.Expiration);
            }
Esempio n. 29
0
        public void DateIsUnixTimeInUtc()
        {
            // Arrange
            var date  = DateTime.Now;
            var nonce = Nonce.FromDate(date);

            var expected = ((DateTimeOffset)date.ToUniversalTime()).ToUnixTimeMilliseconds().ToString();

            // Act
            var actual = nonce.ToString().Split(':')[0];

            // Assert
            Assert.AreEqual(expected, actual);
        }
        protected async override Task OnHandleMessageAsync(Message message, NetworkSession session)
        {
            AuthSession authSession = (AuthSession)session;

            await EventLogger.Instance.RequestEventAsync(authSession.RemoteEndPoint).ConfigureAwait(false);

            if (authSession.Authenticated || authSession.Authenticating)
            {
                await authSession.FailureAsync("Already Authenticating").ConfigureAwait(false);

                return;
            }

            AuthMessage authMessage = (AuthMessage)message;

            if (Common.AuthProtocolVersion != authMessage.ProtocolVersion)
            {
                Logger.Debug($"Bad version, expected: {Common.AuthProtocolVersion}, got: {authMessage.ProtocolVersion}");
                await authSession.FailureAsync("Bad Version").ConfigureAwait(false);

                return;
            }

            Nonce nonce = new Nonce(ConfigurationManager.AppSettings["authRealm"], Convert.ToInt32(ConfigurationManager.AppSettings["authExpiry"]));

            string challenge;

            switch (authMessage.MechanismType)
            {
            case AuthType.DigestMD5:
                /*challenge = BuildDigestMD5Challenge(nonce);
                 * break;*/
                await authSession.FailureAsync("MD5 mechanism not supported!").ConfigureAwait(false);

                return;

            case AuthType.DigestSHA512:
                challenge = BuildDigestSHA512Challenge(nonce);
                break;

            default:
                await authSession.FailureAsync("Unsupported mechanism").ConfigureAwait(false);

                return;
            }

            Logger.Debug($"Session {authSession.Id} generated challenge: {challenge}");
            await authSession.ChallengeAsync(authMessage.MechanismType, nonce, challenge).ConfigureAwait(false);
        }
        public void TestChaCha20Poly1305()
        {
            var key       = Key.Import(AeadAlgorithm.ChaCha20Poly1305, Chacha20Poly1305Key, KeyBlobFormat.RawSymmetricKey);
            var nonce     = new Nonce(Chacha20Poly1305Nonce, Chacha20Poly1305NoneCounterTag);
            var encrypted = AeadAlgorithm.ChaCha20Poly1305.Encrypt(key, nonce, Chacha20Poly1305Aad,
                                                                   Encoding.UTF8.GetBytes(Chacha20Poly1305Pt));

            Assert.Equal(Chacha20Poly1305Ct, encrypted.AsSpan().Slice(0, Chacha20Poly1305Ct.Length).ToArray());

            var decryptOk = AeadAlgorithm.ChaCha20Poly1305.Decrypt(key, nonce, Chacha20Poly1305Aad, encrypted, out var decrypted);

            Assert.True(decryptOk);

            Assert.Equal(Chacha20Poly1305Pt, Encoding.UTF8.GetString(decrypted));
        }
Esempio n. 32
0
        public override string ToString()
        {
            string updatedAddresses = string.Join(
                string.Empty,
                UpdatedAddresses.Select(a => "\n    " + ByteUtil.Hex(a.ToArray()))
                );

            return($@"{nameof(RawTransaction)}
  {nameof(Nonce)} = {Nonce.ToString(CultureInfo.InvariantCulture)}
  {nameof(Signer)} = {ByteUtil.Hex(Signer.ToArray())}
  {nameof(PublicKey)} = {ByteUtil.Hex(PublicKey.ToArray())}
  {nameof(UpdatedAddresses)} = {updatedAddresses}
  {nameof(Timestamp)} = {Timestamp}
  {nameof(Signature)} = {ByteUtil.Hex(Signature.ToArray())}");
        }
Esempio n. 33
0
        public void EncryptWithADTestWithPlainText()
        {
            String key                  = "908b166535c01a935cf1e130a5fe895ab4e6f3ef8855d87e9b7581c4ab663ddc";
            String additionalData       = "90578e247e98674e661013da3c5c1ca6a8c8f48c90b485c0dfa1494e23d56d72";
            String plaintext            = "034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa";
            String expectedCipherResult = "b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c3822";

            Nonce nonce = new Nonce();

            nonce.Increment();

            (byte[] actualCipherText, byte[] mac) = ChaCha20Poly1305.EncryptWithAdditionalData(key.HexToByteArray(), nonce.GetBytes(), additionalData.HexToByteArray(), plaintext.HexToByteArray());

            Assert.Equal(expectedCipherResult, actualCipherText.ToHex() + mac.ToHex());
        }
Esempio n. 34
0
			public static bool TryParse(byte[] hexBytes32, int startIndex, out Nonce nonce)
			{
				int data1 = 0, data2 = 0, data3 = 0, data4 = 0;

				if (HexEncoding.TryParseHex8(hexBytes32, startIndex + 0, out data1) &&
					HexEncoding.TryParseHex8(hexBytes32, startIndex + 8, out data2) &&
					HexEncoding.TryParseHex8(hexBytes32, startIndex + 16, out data3) &&
					HexEncoding.TryParseHex8(hexBytes32, startIndex + 24, out data4))
				{
					nonce = new Nonce(data1, data2, data3, data4);
					return true;
				}

				nonce = new Nonce();
				return false;
			}
        public static Summary GetInfo(Flipper flipper)
        {
            Summary id = null;

            Nonce nonce = new Nonce();

            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://ws.byu.edu/rest/v2.0/identity/person/PRO/personSummary.cgi/" + flipper.person_id);
            request.Headers.Add("Authorization", nonce.GetNonce(flipper.net_id));

            request.Method = "GET";
            request.Accept = "application/json";

            HttpWebResponse response = null;
            try
            {
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {

                        Stream ReceiveStream = response.GetResponseStream();
                        StreamReader readStream = new StreamReader(ReceiveStream);
                        string json = readStream.ReadToEnd();
                        id = jsSerializer.Deserialize<Summary>(json);
                    }
                }
            }
            catch (WebException wx)
            {
                if (response == null)
                {
                    System.Diagnostics.Debug.WriteLine(wx.Message);

                }
                return null;
            }

            return id;
        }
Esempio n. 36
0
		Token(Nonce nonce, ServiceEndpoint provider) {
			Nonce = nonce;
			Endpoint = provider;
		}
Esempio n. 37
0
		/// <summary>
		/// Deserializes a token returned to us from the provider and verifies its integrity.
		/// </summary>
		/// <remarks>
		/// As part of deserialization, the signature is verified to check
		/// for tampering, and the nonce (if included by the RP) is also checked.
		/// If no signature is present (due to stateless mode), the endpoint is verified
		/// by discovery (slow but secure).
		/// </remarks>
		public static Token Deserialize(string token, INonceStore store) {
			byte[] tok = Convert.FromBase64String(token);
			if (tok.Length < 1) throw new OpenIdException(Strings.InvalidSignature);
			bool signaturePresent = tok[0] == 1;
			bool signatureVerified = false;
			MemoryStream dataStream;

			if (signaturePresent) {
				if (persistSignature(store)) {
					// Verify the signature to guarantee that our state hasn't been
					// tampered with in transit or on the provider.
					HashAlgorithm hmac = createHashAlgorithm(store);
					int signatureLength = hmac.HashSize / 8;
					dataStream = new MemoryStream(tok, 1 + signatureLength, tok.Length - 1 - signatureLength);
					byte[] newSig = hmac.ComputeHash(dataStream);
					dataStream.Position = 0;
					if (tok.Length - 1 < newSig.Length)
						throw new OpenIdException(Strings.InvalidSignature);
					for (int i = 0; i < newSig.Length; i++)
						if (tok[i + 1] != newSig[i])
							throw new OpenIdException(Strings.InvalidSignature);
					signatureVerified = true;
				} else {
					// Oops, we have no application state, so we have no way of validating the signature.
					throw new OpenIdException(Strings.InconsistentAppState);
				}
			} else {
				dataStream = new MemoryStream(tok, 1, tok.Length - 1);
			}

			StreamReader reader = new StreamReader(dataStream);
			ServiceEndpoint endpoint = ServiceEndpoint.Deserialize(reader);
			Nonce nonce = null;
			if (signatureVerified && persistNonce(endpoint, store)) {
				nonce = new Nonce(reader.ReadLine(), false);
				nonce.Consume(store);
			}
			if (!signatureVerified) {
				verifyEndpointByDiscovery(endpoint);
			}

			return new Token(nonce, endpoint);
		}
Esempio n. 38
0
 public void AddToNonces(Nonce nonce)
 {
     base.AddObject("Nonces", nonce);
 }
Esempio n. 39
0
 public static Nonce CreateNonce(int nonceId, string context, string code, global::System.DateTime issuedUtc, global::System.DateTime expiresUtc)
 {
     Nonce nonce = new Nonce();
     nonce.NonceId = nonceId;
     nonce.Context = context;
     nonce.Code = code;
     nonce.IssuedUtc = issuedUtc;
     nonce.ExpiresUtc = expiresUtc;
     return nonce;
 }
Esempio n. 40
0
			public bool IsEqualValue(Nonce y)
			{
				return Data1 == y.Data1 && Data2 == y.Data2 && Data3 == y.Data3 && Data4 == y.Data4;
			}