예제 #1
0
        public async Task EncryptAndDecrypt_UsingBrainKeys()
        {
            Func <TokenContext, Task <string> > tokenCallback = (c) =>
            {
                var virgilCrypto = new VirgilCrypto();
                var signer       = new VirgilAccessTokenSigner();

                var apiKey = virgilCrypto.ImportPrivateKey(
                    Bytes.FromString(AppSettings.Get.ApiKey, StringEncoding.BASE64));

                var generator = new JwtGenerator(AppSettings.Get.AppId, apiKey,
                                                 AppSettings.Get.ApiKeyId, TimeSpan.FromDays(1), signer);

                var jwt = generator.GenerateToken("BRAINKEY_CLIENT");

                return(Task.FromResult(jwt.ToString()));
            };

            var brainKey = BrainKey.Initialize(tokenCallback);
            var keyPair1 = await brainKey.GenerateKeyPair("some password");

            await Task.Delay(TimeSpan.FromSeconds(2));

            var keyPair2 = await brainKey.GenerateKeyPair("some password");

            await Task.Delay(TimeSpan.FromSeconds(2));

            var crypto       = new VirgilCrypto();
            var plaindata    = GetRandom.Bytes(128);
            var chipherdata  = crypto.SignThenEncrypt(plaindata, keyPair1.PrivateKey, keyPair2.PublicKey);
            var originaldata = crypto.DecryptThenVerify(chipherdata, keyPair2.PrivateKey, keyPair1.PublicKey);

            originaldata.Should().BeEquivalentTo(plaindata);
        }
예제 #2
0
        public static Tuple <Jwt, JwtGenerator> PredefinedToken(
            this Faker faker,
            VirgilAccessTokenSigner signer,
            TimeSpan lifeTime,
            out string apiPublicKeyId,
            out string apiPublicKeyBase64)
        {
            var crypto      = new VirgilCrypto();
            var apiKeyPair  = crypto.GenerateKeys();
            var fingerprint = crypto.GenerateHash(crypto.ExportPublicKey(apiKeyPair.PublicKey));

            apiPublicKeyId = Bytes.ToString(fingerprint, StringEncoding.HEX);

            apiPublicKeyBase64 = Bytes.ToString(
                crypto.ExportPublicKey(apiKeyPair.PublicKey), StringEncoding.BASE64);

            var jwtGenerator = new JwtGenerator(
                faker.AppId(),
                apiKeyPair.PrivateKey,
                apiPublicKeyId,
                lifeTime,
                signer);

            var additionalData = new Dictionary <string, string>
            {
                { "username", "some_username" }
            };
            var dict  = additionalData.ToDictionary(entry => (object)entry.Key, entry => (object)entry.Value);
            var token = jwtGenerator.GenerateToken("some_identity", dict);

            return(new Tuple <Jwt, JwtGenerator>(token, jwtGenerator));
        }
        public static PythiaProtocol Initialize(PythiaProtocolConfig config)
        {
            if (config.ProofKeys == null || !config.ProofKeys.Any())
            {
                throw new ArgumentException(
                          $"{nameof(config.ProofKeys)} value cannot be null or empty");
            }

            if (string.IsNullOrWhiteSpace(config.AppId))
            {
                throw new ArgumentException(
                          $"{nameof(config.AppId)} value cannot be null or empty");
            }

            if (string.IsNullOrWhiteSpace(config.ApiKeyId))
            {
                throw new ArgumentException(
                          $"{nameof(config.ApiKeyId)} value cannot be null or empty");
            }

            if (string.IsNullOrWhiteSpace(config.ApiKey))
            {
                throw new ArgumentException(
                          $"{nameof(config.ApiKey)} value cannot be null or empty");
            }

            Func <TokenContext, Task <string> > tokenCallback = (c) =>
            {
                var virgilCrypto = new VirgilCrypto();
                var signer       = new VirgilAccessTokenSigner();

                var apiKey = virgilCrypto.ImportPrivateKey(
                    Bytes.FromString(config.ApiKey, StringEncoding.BASE64));

                var generator = new JwtGenerator(config.AppId, apiKey,
                                                 config.ApiKeyId, TimeSpan.FromDays(1), signer);

                var jwt = generator.GenerateToken("PYTHIA_CLIENT");

                return(Task.FromResult(jwt.ToString()));
            };

            var connection    = new ServiceConnection(config.ApiURL);
            var tokenProvider = new CachingJwtProvider(tokenCallback);

            var client       = new PythiaClient(connection, new NewtonsoftJsonSerializer());
            var pythiaCrypto = new PythiaCrypto();

            var protocol = new PythiaProtocol(client, pythiaCrypto,
                                              tokenProvider, config.ProofKeys);

            return(protocol);
        }
예제 #4
0
        public async Task YTC16()
        {
            var correnctPassword = "******";
            var wrongPassword    = "******";

            var crypto = Substitute.For <IPythiaCrypto>();

            crypto.Blind(correnctPassword).Returns(new PythiaCrypto().Blind(correnctPassword));
            crypto.Blind(wrongPassword).Returns(new PythiaCrypto().Blind(wrongPassword));
            crypto.Deblind(Arg.Any <byte[]>(), Arg.Any <byte[]>())
            .Returns((arg) => new PythiaCrypto().Deblind((byte[])arg[0], (byte[])arg[1]));
            crypto.GenerateSalt().Returns(new PythiaCrypto().GenerateSalt());
            crypto.Verify(Arg.Any <PythiaProofParams>()).Returns(true, false, false, false, false);

            var virgilCrypto = new VirgilCrypto();
            var signer       = new VirgilAccessTokenSigner();

            var apiKey    = virgilCrypto.ImportPrivateKey(Bytes.FromString(AppSettings.Get.ApiKey, StringEncoding.BASE64));
            var generator = new JwtGenerator(AppSettings.Get.AppId, apiKey, AppSettings.Get.ApiKeyId, TimeSpan.FromDays(1), signer);
            var jwt       = generator.GenerateToken("PYTHIA-CLIENT");

            var connection    = new ServiceConnection(AppSettings.Get.ApiURL);
            var tokenProvider = new ConstAccessTokenProvider(jwt);

            var client = new PythiaClient(connection, new NewtonsoftJsonSerializer());

            var protocol = new PythiaProtocol(client, crypto, tokenProvider, AppSettings.Get.ProofKeys.Skip(1));
            var bpp      = await protocol.CreateBreachProofPasswordAsync(correnctPassword);

            await Task.Delay(TimeSpan.FromSeconds(2));

            var verifyResult1 = await protocol.VerifyBreachProofPasswordAsync(correnctPassword, bpp, false);

            verifyResult1.Should().BeTrue();
            await Task.Delay(TimeSpan.FromSeconds(2));

            Func <Task> verifyResult2 = async() => { await protocol.VerifyBreachProofPasswordAsync(correnctPassword, bpp, true); };

            verifyResult2.Should().Throw <Exception>();
            await Task.Delay(TimeSpan.FromSeconds(2));

            var verifyResult3 = await protocol.VerifyBreachProofPasswordAsync(wrongPassword, bpp, false);

            verifyResult3.Should().BeFalse();
            await Task.Delay(TimeSpan.FromSeconds(2));

            Func <Task> verifyResult4 = async() => { await protocol.VerifyBreachProofPasswordAsync(wrongPassword, bpp, true); };

            verifyResult4.Should().Throw <Exception>();
            await Task.Delay(TimeSpan.FromSeconds(2));
        }
예제 #5
0
        public void Verify_Should_VerifyTestCreatedInAnotherSDK()
        {
            var jwt    = new Jwt(AppSettings.ImportedJwt);
            var signer = new VirgilAccessTokenSigner();
            var crypto = new VirgilCrypto();

            var jwtVerifier = new JwtVerifier(
                signer,
                crypto.ImportPublicKey(
                    Bytes.FromString(AppSettings.ImportedAccessPublicKey, StringEncoding.BASE64)),
                AppSettings.ImportedAccessPublicKeyId);

            Assert.IsTrue(jwtVerifier.VerifyToken(jwt));
        }
예제 #6
0
        public void JwtVerifier_Should_VerifyImportedJwt()
        {
            //STC-22
            var    signer = new VirgilAccessTokenSigner();
            string apiPublicKeyId;
            string apiPublicKeyBase64;
            var    crypto = new VirgilCrypto();

            var token = faker.PredefinedToken(signer, TimeSpan.FromMinutes(10), out apiPublicKeyId, out apiPublicKeyBase64).Item1;

            var jwtVerifier = new JwtVerifier(
                signer,
                crypto.ImportPublicKey(Bytes.FromString(apiPublicKeyBase64, StringEncoding.BASE64)),
                apiPublicKeyId);

            Assert.IsTrue(jwtVerifier.VerifyToken(token));
        }
        public async Task <IActionResult> SecureLogin(LoginModel model)
        {
            var user = await _userManager.FindByNameAsync(model.Username);

            if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var role = await _userManager.GetRolesAsync(user);

                var crypto            = new VirgilCrypto();
                var appKey            = crypto.ImportPrivateKey(Bytes.FromString(_appsettings.APPKEYBASE64, StringEncoding.BASE64), _appsettings.APP_KEY_PASSWORD.ToString());
                var accessTokenSigner = new VirgilAccessTokenSigner();
                var jwtGenerator      = new JwtGenerator(_appsettings.APP_ID, appKey, _appsettings.APP_KEY_ID, TimeSpan.FromMinutes(5), accessTokenSigner);
                var token             = jwtGenerator.GenerateToken(user.Id).ToString() + jwtGenerator.GenerateToken(user.UserName).ToString() + jwtGenerator.GenerateToken(role.FirstOrDefault()).ToString();
                return(Ok(new { token, user.Id, user.UserName, user.Email }));
            }
            return(BadRequest(new { message = "Username or Password is Incorrect" }));
        }
예제 #8
0
        static AuthenticationService()
        {
            NewtonsoftJsonSerializer njs = new NewtonsoftJsonSerializer();
            var config = njs.Deserialize <Config>(File.ReadAllText(@"appsettings.json"));

            var apiKeyBase64   = config.API_KEY;
            var privateKeyData = Bytes.FromString(apiKeyBase64, StringEncoding.BASE64);

            var crypto = new VirgilCrypto();
            var apiKey = crypto.ImportPrivateKey(privateKeyData);

            var accessTokenSigner = new VirgilAccessTokenSigner();

            var appId    = config.APP_ID;
            var apiKeyId = config.API_KEY_ID;
            var ttl      = TimeSpan.FromHours(1); // 1 hour (JWT's lifetime)

            _jwtGenerator = new JwtGenerator(appId, apiKey, apiKeyId, ttl, accessTokenSigner);
            _authTokens   = new Dictionary <string, string>();
        }
        public async Task <IActionResult> Login(LoginModel model)
        {
            var user = await _userManager.FindByNameAsync(model.Username);

            if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var role = await _userManager.GetRolesAsync(user);

                IdentityOptions _options        = new IdentityOptions();
                var             tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserID", user.Id.ToString()),
                        new Claim("Username", user.UserName.ToString()),
                        new Claim(_options.ClaimsIdentity.RoleClaimType, role.FirstOrDefault())
                    }),
                    Expires            = DateTime.UtcNow.AddMinutes(5),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appsettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
                };
                var tokenHandler  = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var token         = tokenHandler.WriteToken(securityToken);

                var SecureRole = await _userManager.GetRolesAsync(user);

                var crypto            = new VirgilCrypto();
                var appKey            = crypto.ImportPrivateKey(Bytes.FromString(_appsettings.APPKEYBASE64, StringEncoding.BASE64), _appsettings.APP_KEY_PASSWORD.ToString());
                var accessTokenSigner = new VirgilAccessTokenSigner();
                var jwtGenerator      = new JwtGenerator(_appsettings.APP_ID, appKey, _appsettings.APP_KEY_ID, TimeSpan.FromMinutes(5), accessTokenSigner);
                var SecureToken       = jwtGenerator.GenerateToken(user.Id).ToString() + jwtGenerator.GenerateToken(user.UserName).ToString() + jwtGenerator.GenerateToken(role.FirstOrDefault()).ToString();



                return(Ok(new { token, SecureToken, user.Id, user.UserName, user.Email }));
            }
            else
            {
                return(BadRequest(new { message = "Username or Password is Incorrect" }));
            }
        }