public void EnryptAndDecryptToken_ExpectCorrectPayloadAndTimestamp()
        {
            var payload = Guid.NewGuid().ToString();
            var handler = new BrancaTokenHandler();

            var token            = handler.CreateToken(payload, validKey);
            var decryptedPayload = handler.DecryptToken(token, validKey);

            decryptedPayload.Payload.Should().Be(payload);
            decryptedPayload.Timestamp.Should().BeCloseTo(DateTime.UtcNow, 1000);
        }
        public void CreateToken_WhenTokenGenerated_ExpectBas62EncodedTokenWithCorrectLength()
        {
            var payload = Guid.NewGuid().ToString();
            var handler = new BrancaTokenHandler();

            var token = handler.CreateToken(payload, validKey);

            token.Any(x => !Base62.CharacterSet.Contains(x)).Should().BeFalse();
            Base62.Decode(token).Length.Should().Be(
                System.Text.Encoding.UTF8.GetBytes(payload).Length + 29 + 16);
        }
Esempio n. 3
0
        public void ValidateToken_CiphertextModification_ExpectSecurityTokenException()
        {
            var handler = new BrancaTokenHandler();

            var token   = handler.CreateToken("test", key);
            var decoded = Base62.Decode(token);

            decoded[decoded.Length - 17] ^= 1; // Last byte before the Poly1305 tag

            Assert.Throws <CryptographicException>(() => handler.DecryptToken(Base62.Encode(decoded), key));
        }
        public void EnryptAndDecryptToken_WithExplicitTimestamp_ExpectCorrectPayloadAndTimestamp()
        {
            var payload   = Guid.NewGuid().ToString();
            var timestamp = new DateTime(2020, 08, 22).ToUniversalTime();
            var handler   = new BrancaTokenHandler();

            var token            = handler.CreateToken(payload, timestamp, validKey);
            var decryptedPayload = handler.DecryptToken(token, validKey);

            decryptedPayload.Payload.Should().Be(payload);
            decryptedPayload.Timestamp.Should().Be(timestamp);
        }
        public void EnryptAndDecryptToken_WithExplicitBrancaTimestamp_ExpectCorrectPayloadAndTimestamp()
        {
            var payload   = Guid.NewGuid().ToString();
            var timestamp = uint.MinValue;
            var handler   = new BrancaTokenHandler();

            var token            = handler.CreateToken(payload, timestamp, validKey);
            var decryptedPayload = handler.DecryptToken(token, validKey);

            decryptedPayload.Payload.Should().Be(payload);
            decryptedPayload.Timestamp.Should().Be(new DateTime(1970, 01, 01, 0, 0, 0, DateTimeKind.Utc));
            decryptedPayload.BrancaFormatTimestamp.Should().Be(timestamp);
        }
        public void CreateAndDecryptToken_WithSecurityTokenDescriptor_ExpectCorrectBrancaTimestampAndNoIatClaim()
        {
            var handler = new BrancaTokenHandler();

            var token = handler.CreateToken(new SecurityTokenDescriptor
            {
                EncryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(validKey), ExtendedSecurityAlgorithms.XChaCha20Poly1305)
            });

            var parsedToken = handler.DecryptToken(token, validKey);
            var jObject     = JObject.Parse(parsedToken.Payload);

            jObject["iat"].Should().BeNull();

            parsedToken.Timestamp.Should().BeCloseTo(DateTime.UtcNow, 1000);
        }
        public void CreateAndValidateToken_WithSecurityTokenDescriptor_ExpectCorrectBrancaTimestampAndNoIatClaim()
        {
            const string issuer    = "me";
            const string audience  = "you";
            const string subject   = "123";
            var          expires   = DateTime.UtcNow.AddDays(1);
            var          notBefore = DateTime.UtcNow;

            var handler = new BrancaTokenHandler();

            var token = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer    = issuer,
                Audience  = audience,
                Expires   = expires,
                NotBefore = notBefore,
                Claims    = new Dictionary <string, object> {
                    { "sub", subject }
                },
                EncryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(validKey), ExtendedSecurityAlgorithms.XChaCha20Poly1305)
            });

            var validatedToken = handler.ValidateToken(token, new TokenValidationParameters
            {
                ValidIssuer        = issuer,
                ValidAudience      = audience,
                TokenDecryptionKey = new SymmetricSecurityKey(validKey)
            });

            validatedToken.IsValid.Should().BeTrue();
            validatedToken.ClaimsIdentity.Claims.Should().Contain(
                x => x.Type == "sub" && x.Value == subject);

            var brancaToken = (BrancaSecurityToken)validatedToken.SecurityToken;

            brancaToken.Issuer.Should().Be(issuer);
            brancaToken.Audiences.Should().Contain(audience);
            brancaToken.Subject.Should().Be(subject);
            brancaToken.IssuedAt.Should().BeWithin(1.Minutes()).After(notBefore);
            brancaToken.ValidFrom.Should().BeWithin(0.Seconds()).After(notBefore);
            brancaToken.ValidTo.Should().BeWithin(0.Seconds()).After(expires);
        }
Esempio n. 8
0
        public IActionResult Branca()
        {
            var handler = new BrancaTokenHandler();

            var token = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer   = "me",
                Audience = "you",
                EncryptingCredentials = options.BrancaEncryptingCredentials
            });

            var parsedToken = handler.DecryptToken(token, ((SymmetricSecurityKey)options.BrancaEncryptingCredentials.Key).Key);

            return(View("Index", new TokenModel
            {
                Type = "Branca",
                Token = token,
                Payload = parsedToken.Payload
            }));
        }
Esempio n. 9
0
        public Result <string> Encrypt(string key, string keyType, uint timestamp, string payload)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (string.IsNullOrWhiteSpace(keyType))
            {
                throw new ArgumentNullException(nameof(keyType));
            }
            if (string.IsNullOrWhiteSpace(payload))
            {
                throw new ArgumentNullException(nameof(payload));
            }

            byte[] keyBytes;
            try
            {
                keyBytes = ParseKey(key, keyType);
            }
            catch
            {
                return(Result <string> .Failure("Unable to parse key"));
            }

            if (keyBytes.Length != 32)
            {
                return(Result <string> .Failure("Invalid key length"));
            }

            var handler = new BrancaTokenHandler();

            try
            {
                return(Result <string> .Success(handler.CreateToken(payload, timestamp, keyBytes)));
            }
            catch
            {
                return(Result <string> .Failure("Unable to create token"));
            }
        }
        public void CreateToken_WhenPayloadIsNullOrWhitespace_ExpectArgumentNullException(string payload)
        {
            var handler = new BrancaTokenHandler();

            Assert.Throws <ArgumentNullException>(() => handler.CreateToken(payload, validKey));
        }