Exemple #1
0
        private CryptoService service; // this instance gives us access to running on card service

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructor for class Crypto.
        /// </summary>
        /// <param name="service">on card service</param>
        public Crypto(CryptoService service)
        {
            this.service = service; // initialize on card service
            rijndael = new RijndaelManaged(); // initialize Rijndael cryptographic algorithm
            rijndael.Mode = CipherMode.CBC; // set cipher mode to Cipher Block Chaining
            rijndael.Padding = PaddingMode.PKCS7; // set padding mode to PKCS7
        }
Exemple #2
0
 public UserRepository()
 {
     _context = new UserContext();
     _crypto = new CryptoService();
 }
Exemple #3
0
 private void ChangePasswordDialog_Load(object sender, EventArgs e)
 {
     userNameTextBox.Text         = CcSettings.Settings.Default.UserName;
     oldPasswordTextBox.Text      = CryptoService.DecryptString(CcSettings.Settings.Default.Password);
     savePasswordCheckBox.Checked = CcSettings.Settings.Default.SavePassword;
 }
Exemple #4
0
        internal static async Task <byte[]> CreatePasswordAsync(string userId, byte[] salt, string password)
        {
            var passwd = PreparePassword(userId, salt, password);

            return(CryptoService.ComputeMD5Hash(await CryptoService.EncryptAsync(passwd)));
        }
Exemple #5
0
        public static void Init(string customUserAgent = null)
        {
            if (Inited)
            {
                return;
            }
            Inited = true;

            var           platformUtilsService   = Resolve <IPlatformUtilsService>("platformUtilsService");
            var           storageService         = Resolve <IStorageService>("storageService");
            var           secureStorageService   = Resolve <IStorageService>("secureStorageService");
            var           cryptoPrimitiveService = Resolve <ICryptoPrimitiveService>("cryptoPrimitiveService");
            var           i18nService            = Resolve <II18nService>("i18nService");
            var           messagingService       = Resolve <IMessagingService>("messagingService");
            SearchService searchService          = null;

            var stateService          = new StateService();
            var cryptoFunctionService = new PclCryptoFunctionService(cryptoPrimitiveService);
            var cryptoService         = new CryptoService(storageService, secureStorageService, cryptoFunctionService);
            var tokenService          = new TokenService(storageService);
            var apiService            = new ApiService(tokenService, platformUtilsService, (bool expired) =>
            {
                messagingService.Send("logout", expired);
                return(Task.FromResult(0));
            }, customUserAgent);
            var appIdService    = new AppIdService(storageService);
            var userService     = new UserService(storageService, tokenService);
            var settingsService = new SettingsService(userService, storageService);
            var cipherService   = new CipherService(cryptoService, userService, settingsService, apiService,
                                                    storageService, i18nService, () => searchService);
            var folderService = new FolderService(cryptoService, userService, apiService, storageService,
                                                  i18nService, cipherService);
            var collectionService = new CollectionService(cryptoService, userService, storageService, i18nService);

            searchService = new SearchService(cipherService);
            var vaultTimeoutService = new VaultTimeoutService(cryptoService, userService, platformUtilsService,
                                                              storageService, folderService, cipherService, collectionService, searchService, messagingService, tokenService,
                                                              null, (expired) =>
            {
                messagingService.Send("logout", expired);
                return(Task.FromResult(0));
            });
            var policyService = new PolicyService(storageService, userService);
            var syncService   = new SyncService(userService, apiService, settingsService, folderService,
                                                cipherService, cryptoService, collectionService, storageService, messagingService, policyService,
                                                (bool expired) =>
            {
                messagingService.Send("logout", expired);
                return(Task.FromResult(0));
            });
            var passwordGenerationService = new PasswordGenerationService(cryptoService, storageService,
                                                                          cryptoFunctionService, policyService);
            var totpService = new TotpService(storageService, cryptoFunctionService);
            var authService = new AuthService(cryptoService, apiService, userService, tokenService, appIdService,
                                              i18nService, platformUtilsService, messagingService, vaultTimeoutService);
            var exportService      = new ExportService(folderService, cipherService);
            var auditService       = new AuditService(cryptoFunctionService, apiService);
            var environmentService = new EnvironmentService(apiService, storageService);
            var eventService       = new EventService(storageService, apiService, userService, cipherService);

            Register <IStateService>("stateService", stateService);
            Register <ICryptoFunctionService>("cryptoFunctionService", cryptoFunctionService);
            Register <ICryptoService>("cryptoService", cryptoService);
            Register <ITokenService>("tokenService", tokenService);
            Register <IApiService>("apiService", apiService);
            Register <IAppIdService>("appIdService", appIdService);
            Register <IUserService>("userService", userService);
            Register <ISettingsService>("settingsService", settingsService);
            Register <ICipherService>("cipherService", cipherService);
            Register <IFolderService>("folderService", folderService);
            Register <ICollectionService>("collectionService", collectionService);
            Register <ISearchService>("searchService", searchService);
            Register <IPolicyService>("policyService", policyService);
            Register <ISyncService>("syncService", syncService);
            Register <IVaultTimeoutService>("vaultTimeoutService", vaultTimeoutService);
            Register <IPasswordGenerationService>("passwordGenerationService", passwordGenerationService);
            Register <ITotpService>("totpService", totpService);
            Register <IAuthService>("authService", authService);
            Register <IExportService>("exportService", exportService);
            Register <IAuditService>("auditService", auditService);
            Register <IEnvironmentService>("environmentService", environmentService);
            Register <IEventService>("eventService", eventService);
        }
Exemple #6
0
        protected void ValidateUser(object sender, AuthenticateEventArgs e)
        {
            int    userLvl        = 0;
            string Password       = Convert.ToString(Login1.Password);
            string HashedPassword = null;
            string Salt           = null;
            string constr         = ConfigurationManager.ConnectionStrings["CS414_FasTestConnectionString"].ConnectionString;

            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Validate_Password", con))
                //using (SqlCommand cmd = new SqlCommand("Validate_User"))
                {
                    try
                    {
                        try
                        {
                            int UserName = Convert.ToInt32(Login1.UserName);


                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@pUserID", UserName);
                            cmd.Parameters.Add("@pPassword", SqlDbType.VarChar, 50).Direction = ParameterDirection.Output;
                            cmd.Parameters.Add("@pSalt", SqlDbType.VarChar, 50).Direction     = ParameterDirection.Output;
                            cmd.Parameters.Add("@CredentialLevel", SqlDbType.Int).Direction   = ParameterDirection.Output;
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                            HashedPassword = cmd.Parameters["@pPassword"].Value.ToString();
                            Salt           = cmd.Parameters["@pSalt"].Value.ToString();
                        }
                        catch
                        {
                            Login1.FailureText = "Username and/or password is incorrect.";
                        }
                        try
                        {
                            userLvl = Convert.ToInt32(cmd.Parameters["@CredentialLevel"].Value);
                        }
                        catch
                        {
                            Login1.FailureText = "Username and/or password is incorrect.";
                        }
                    }
                    catch (SqlException ex)
                    {
                        Login1.FailureText = "Username and/or password is incorrect. " + ex.ToString();
                    }
                    finally
                    {
                        con.Close();
                    }

                    /*try
                     * {
                     *  cmd.CommandType = CommandType.StoredProcedure;
                     *  cmd.Parameters.AddWithValue("@Username", Convert.ToInt32(Login1.UserName));
                     *  cmd.Parameters.AddWithValue("@Password", Convert.ToString(Login1.Password));
                     *  cmd.Connection = con;
                     *  con.Open();
                     *  userLvl = Convert.ToInt32(cmd.ExecuteScalar());
                     * }
                     * catch
                     * {
                     *  Login1.FailureText = "Username and/or password is incorrect.";
                     * }
                     * finally
                     * {
                     * con.Close();
                     * }*/
                }

                if (CryptoService.ValidateHash(HashedPassword, Password, Salt))
                {
                    switch (userLvl)
                    {
                    //case -1:
                    // Login1.FailureText = "Username and/or password is incorrect.";
                    // break;
                    case 1:
                        FormsAuthentication.SetAuthCookie(Login1.UserName, Login1.RememberMeSet);
                        Response.Redirect("~/Admin/AdminHome.aspx");
                        break;

                    case 2:
                        FormsAuthentication.SetAuthCookie(Login1.UserName, Login1.RememberMeSet);
                        Response.Redirect("~/Teacher/TeacherHome.aspx");
                        break;

                    case 3:
                        FormsAuthentication.SetAuthCookie(Login1.UserName, Login1.RememberMeSet);
                        Response.Redirect("~/Student/StudentHome.aspx");
                        break;
                    }
                }
                //else
                //Login1.FailureText = "Username and/or password is incorrect.";
            }
        }
Exemple #7
0
        private async void btnImportPasswords_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title            = "Import Passwords";
            ofd.DefaultExt       = "bpf";
            ofd.Filter           = Globals.Information.AppName + " files (*.bpf)|*.bpf|All files (*.*)|*.*";
            ofd.FilterIndex      = 1;
            ofd.CheckPathExists  = true;
            ofd.RestoreDirectory = true;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                List <Password> importedPasswords = await BearPassService.Instance().ImportPasswordsAsync(ofd.FileName);

                if (importedPasswords != null)
                {
                    if (Messenger.Confirm("The file contains " + importedPasswords.Count + " passwords. Are you sure you want to import these passwords to your account?"))
                    {
                        try
                        {
                            await PasswordsService.Instance().SaveNewUserPasswordsAsync(user, CryptoService.Instance().DecryptUserPasswords(user, importedPasswords));
                        }
                        catch
                        {
                            Messenger.Show("Unable to import passwords. Either these passwords were encrypted with a different Master Password than yours or you changed your Master Password.", "Error");
                        }
                        ShowPasswords(await PasswordsService.Instance().GetAllUserPasswordsAsync(user));
                    }
                }
            }
        }
Exemple #8
0
        public void TestVerify()
        {
            // Sample challenge-response
            //    Send to wallet:
            // req: lnurl1dp68gup69uhnzwfj9ccnvwpwxqhrzdej8gerwdf5xvhkcmnpw46xstmnd9nku6tw8a6xzeead3hkw6twye4nz0f4xqenqvps89zrxd6xxaryx3fc8yc5y3fcxycyxwzyx3qnydz9xveyyd6pg56r2wpjxscnxd2p8qcrzdzpx9prxd29xapnjdjxx4ryys3t74l
            // url:http://192.168.0.172:27543/lnauth/signin?tag=login&k1=5030009D37F7FCE891BE810C8D4A24E32B7AE45824135A8014A1B35E7C96F5FB
            //    Response from wallet:
            // key: 038b02325d76b1e096071a6fdaf6c695800ad79b7245f7e6b0d5ccd505a2d4c10c
            // k1:5030009D37F7FCE891BE810C8D4A24E32B7AE45824135A8014A1B35E7C96F5FB
            // sig:3044022006a071c4997c313e3c0bcb13daed2dddf1ebe5d899405125e674423c12480150022006664645062a1f2b5bca4d35c76ef72b0cdd46e1ba0cab89bd085c18a2922f6d

            // Works
            //var publicKey = CryptoService.HexStringToByteArray("038b02325d76b1e096071a6fdaf6c695800ad79b7245f7e6b0d5ccd505a2d4c10c");
            //var hash = CryptoService.HexStringToByteArray("5030009D37F7FCE891BE810C8D4A24E32B7AE45824135A8014A1B35E7C96F5FB");
            //var signature = CryptoService.HexStringToByteArray("3044022006a071c4997c313e3c0bcb13daed2dddf1ebe5d899405125e674423c12480150022006664645062a1f2b5bca4d35c76ef72b0cdd46e1ba0cab89bd085c18a2922f6d");

            // Fails - should work
            var publicKey = CryptoService.HexStringToByteArray("038b02325d76b1e096071a6fdaf6c695800ad79b7245f7e6b0d5ccd505a2d4c10c");
            var hash      = CryptoService.HexStringToByteArray("6A6EAB458D4DE401A78F109911274A1A21A9A512BA861933D6937E0EA95B016A");
            var signature = CryptoService.HexStringToByteArray("3045022100da228f52aaeef71ba92b0241832e5e19f23f74bc663057017c35ce81c51efe5702206a0c1c1f56af604ada61557f827ca0778546c25d6729edbd43a8853f9a96435f");

            var secp256k1 = ECCurve.CreateFromValue("1.3.132.0.10");
            // signature is DER encoded -> convert to 64 byte array

            var p1len = signature[3];
            var sigp1 = signature.Skip(4).SkipWhile(b => b == 0).Take(32).ToArray();             // Remove any 0 padded bytes
            var p2len = signature.Skip(4 + p1len + 1).Take(1).ToArray()[0];
            var sigp2 = signature.Skip(4 + p1len + 2).SkipWhile(b => b == 0).Take(32).ToArray(); // Remove any 0 padded bytes
            var sig   = sigp1.Concat(sigp2).ToArray();
            // decompress the public key

            //var i = publicKey[0];
            //var x = new BigInteger(publicKey.Skip(1).ToArray());

            //var p = new BigInteger(CryptoService.HexStringToByteArray("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"));
            //var a = new BigInteger(0);
            //var b = new BigInteger(7);

            //var y_sq = (x * x * x + a * x + b) % p;

            //var y = BigInteger.ModPow(y_sq, (p + 1) / 4, p);

            //if ((i == 02 && y % 2 != 0) || (i == 03 && y % 2 == 0))
            //{
            //    y = (p - y % p);
            //}

            //var pkX1 = x.ToByteArray();
            //var pkY1 = y.ToByteArray();

            PubKey pk      = new PubKey(publicKey);
            var    pkBytes = pk.Decompress().ToBytes();

            var pkX = pkBytes.Skip(1).Take(32).ToArray();
            var pkY = pkBytes.Skip(33).ToArray();

            var dsa = ECDsa.Create(new ECParameters
            {
                Curve = secp256k1,
                //D optional: (private key bytes) we don't have
                Q = new ECPoint
                {
                    // gets the {x,y} from the uncompressed public key
                    X = pkX,
                    Y = pkY,
                }
            });

            var isValid = dsa.VerifyHash(hash, sig);

            Assert.IsTrue(isValid);
            //CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob)
            //ECDsaCng ecsdKey = new ECDsaCng()
        }
Exemple #9
0
        public async Task <ActionResult> Detail(int?PostId = null, string postIdEnc = null, string postTitle = null, int?vote = null)
        {
            XFrameOptionsDeny();
            if (PostId == null && postIdEnc == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (postIdEnc != null)
            {
                PostId = CryptoService.StringToIntId(postIdEnc);
            }

            using (var db = new ZapContext())
            {
                var userAppId = User.Identity.GetUserId();
                var userId    = userAppId == null ? 0 : (await db.Users.FirstOrDefaultAsync(u => u.AppId == userAppId).ConfigureAwait(true))?.Id;

                if (userId.HasValue && userId != 0)
                {
                    await ClaimsHelpers.ValidateClaims(userAppId, User).ConfigureAwait(true);
                }

                var pst = db.Posts
                          .Where(p => p.PostId == PostId && !p.IsDraft && !p.IsDeleted)
                          .Select(p => new PostViewModel()
                {
                    PostTitle = p.PostTitle,
                    Content   = p.Content,
                    PostId    = p.PostId,
                    GroupId   = p.Group.GroupId,
                    GroupName = p.Group.GroupName,
                    IsSticky  = p.IsSticky,
                    UserName  = p.UserId.Name,
                    UserId    = p.UserId.Id,
                    UserAppId = p.UserId.AppId,
                    UserProfileImageVersion = p.UserId.ProfileImage.Version,
                    Score             = p.Score,
                    TimeStamp         = p.TimeStamp,
                    TimeStampEdited   = p.TimeStampEdited,
                    IsNSFW            = p.IsNSFW,
                    ViewerIsFollowing = userId.HasValue ? p.FollowedByUsers.Select(v => v.Id).Contains(userId.Value) : false,
                    ViewerIsMod       = userId.HasValue ? p.Group.Moderators.Select(m => m.Id).Contains(userId.Value) : false,
                    ViewerUpvoted     = userId.HasValue ? p.VotesUp.Select(v => v.Id).Contains(userId.Value) : false,
                    ViewerDownvoted   = userId.HasValue ? p.VotesDown.Select(v => v.Id).Contains(userId.Value) : false,
                    ViewerIgnoredUser = userId.HasValue ? (p.UserId.Id == userId.Value ? false : p.UserId.IgnoredByUsers.Select(u => u.Id).Contains(userId.Value)) : false,
                    ViewerIgnoredPost = userId.HasValue ? (p.UserId.Id == userId.Value ? false : p.IgnoredByUsers.Select(u => u.Id).Contains(userId.Value)) : false,
                    CommentVms        = p.Comments.Select(c => new PostCommentsViewModel()
                    {
                        PostId              = p.PostId,
                        CommentId           = c.CommentId,
                        Text                = c.Text,
                        Score               = c.Score,
                        IsReply             = c.IsReply,
                        IsDeleted           = c.IsDeleted,
                        TimeStamp           = c.TimeStamp,
                        TimeStampEdited     = c.TimeStampEdited,
                        UserId              = c.UserId.Id,
                        UserName            = c.UserId.Name,
                        UserAppId           = c.UserId.AppId,
                        ProfileImageVersion = c.UserId.ProfileImage.Version,
                        ViewerUpvoted       = userId.HasValue ? c.VotesUp.Select(v => v.Id).Contains(userId.Value) : false,
                        ViewerDownvoted     = userId.HasValue ? c.VotesDown.Select(v => v.Id).Contains(userId.Value) : false,
                        ViewerIgnoredUser   = userId.HasValue ? (c.UserId.Id == userId ? false : c.UserId.IgnoredByUsers.Select(u => u.Id).Contains(userId.Value)) : false,
                        ParentCommentId     = c.Parent == null ? 0 : c.Parent.CommentId,
                        ParentUserId        = c.Parent == null ? 0 : c.Parent.UserId.Id,
                        ParentUserName      = c.Parent == null ? "" : c.Parent.UserId.Name,
                    }),
                })
                          .AsNoTracking()
                          .FirstOrDefault();

                if (pst == null)
                {
                    return(RedirectToAction("PostNotFound"));
                }

                if (vote.HasValue)
                {
                    ViewBag.showVote = true;
                    ViewBag.vote     = vote.Value;
                }

                return(View(pst));
            }
        }
Exemple #10
0
        static void Main(string[] args)
        {
            _loggerService = new LoggerService();
            _loggerService.Log("###### INITIALIZED CLI ######");
            LogRecievedArgs(args);
            bool isRecursive = args.Any(k => k.Length > 0 && k.First() == '\"');
            var  argsV2      = isRecursive ? StringFormats.StringToParams(string.Join(" ", args)) : args;

            LogProcessedArgs(argsV2);
            var storedData = StoredDataManager.GetStoredData();

            IRegistryService   registryService   = new RegistryService();
            ICryptoService     cryptoService     = new CryptoService(registryService);
            IStoredDataService storedDataService = new StoredDataService(storedData, cryptoService);

            commandManager        = new CommandManager(_loggerService, storedDataService, cryptoService);
            commandManager.OnLog += CommandManager_OnLog;

            RegisterCommands(storedDataService, registryService, cryptoService);

            try
            {
                var inputCommand = new InputRequest(argsV2);
                commandManager.ExecuteInputRequest(inputCommand);
            }
            catch (DuplicateCommandException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Found {ex.Commands.Count} commands with the same name in different namespaces. In this case is necessary use the namespace for execute it. Commands: {string.Join(",", ex.Commands.ToArray())}");
            }
            catch (CommandNotFoundException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Command not found. Use 'help' for check the available commands");
            }
            catch (InvalidParamsException)
            {
                ExceptionManager.RaiseException(_loggerService, $"This command cannot be executed with this combination of parameters");
            }
            catch (InvalidParamNameException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Invalid parameter name '{ex.Message}'");
            }
            catch (NotArgumentsException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Check all the params with 'help' command");
            }
            catch (NotValidCommandNameException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Invalid command name '{ex.Message}'");
            }
            catch (AliasRepeatedException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Alias '{ex.Message}' is already used");
            }
            catch (AliasNotFoundException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Alias '{ex.Message}' is not registered");
            }
            catch (ParameterRepeatedException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Parameter '{ex.Message}' is already used");
            }
            catch (ParameterNotFoundException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Parameter '{ex.Message}' is not registered");
            }
            catch (InvalidParamException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Cannot resolver parameter {ex.Message}");
            }
            catch (PathNotFoundException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Path '{ex.Message}' does not exists");
            }
            catch (TemplateConfigFileNotFoundException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Can't find '{Definitions.TemplateConfigFilename}' file in path");
            }
            catch (InvalidTemplateConfigFileException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Config file '{Definitions.TemplateConfigFilename}' is invalid. Error parsing: {ex.Message}");
            }
            catch (InvalidStringFormatException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Invalid string format. {ex.Message}");
            }
            catch (TemplateNameRepeatedException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Template name repeated");
            }
            catch (TemplateNotFoundException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Can't find any template with this name");
            }
            catch (RepositoryNotFoundException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Can't find any repository with this name");
            }
            catch (PipelineConfigFileNotFoundException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Can't find '{Definitions.PipelineConfigFilename}' file in path");
            }
            catch (InvalidPipelineConfigFileException ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Config file '{Definitions.PipelineConfigFilename}' is invalid. Error parsing: {ex.Message}");
            }
            catch (PipelineNameRepeatedException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Pipeline name repeated");
            }
            catch (PipelineNotFoundException)
            {
                ExceptionManager.RaiseException(_loggerService, $"Can't find any pipeline with this name");
            }
            catch (Exception ex)
            {
                ExceptionManager.RaiseException(_loggerService, $"Throwed uncatched exception: {ex.ToString()}");
            }
            finally
            {
                _loggerService.Log("###### FINISHED! ######");
            }
        }
Exemple #11
0
 private static void BartUnzip()
 {
     CryptoService.BartDecompress("C:\\temp\\email.eml.bart.zip");
 }
Exemple #12
0
 private static void BartZip()
 {
     CryptoService.BartCompress("C:\\temp\\email.eml");
 }
Exemple #13
0
        static void DecryptFiles()
        {
            var privk = RegistryHelper.GetPrivateKey();

            CryptoService.DecryptFiles("c:\\temp", privk);
        }
Exemple #14
0
        static void EncryptFiles()
        {
            var pubk = RegistryHelper.GetPublicKey();

            CryptoService.EncryptFiles("c:\\temp", pubk);
        }
        private static ReadOnlyMemory <byte> GenerateNonce(EncryptionType encryptionType, int minSize)
        {
            var transformer = CryptoService.CreateTransform(encryptionType);

            return(transformer.GenerateRandomBytes(minSize));
        }
 public UserController()
 {
     userService   = new UserService();
     cryptoService = new CryptoService();
 }
Exemple #17
0
        public override KrbPaData Validate(KrbKdcReq asReq, PreAuthenticationContext preauth)
        {
            if (!preauth.PreAuthenticationState.TryGetValue(PaDataType.PA_PK_AS_REQ, out PaDataState paState) ||
                !(paState is PkInitState state))
            {
                return(null);
            }

            var authPack = ValidateAuthPack(preauth, state);

            ValidateAuthenticator(authPack.PKAuthenticator, asReq.Body);

            var requestAlg = authPack.ClientPublicValue?.Algorithm?.Algorithm;

            IKeyAgreement agreement;

            if (requestAlg?.Value == EllipticCurveDiffieHellman.Value)
            {
                agreement = FromEllipticCurveDomainParameters(authPack.ClientPublicValue);
            }
            else if (requestAlg?.Value == DiffieHellman.Value)
            {
                agreement = FromDiffieHellmanDomainParameters(authPack.ClientPublicValue);
            }
            else
            {
                throw OnlyKeyAgreementSupportedException();
            }

            var derivedKey = agreement.GenerateAgreement();

            var etype = asReq.Body.EType.First();

            var transform = CryptoService.CreateTransform(etype);

            ReadOnlyMemory <byte> clientDHNonce = authPack.ClientDHNonce.GetValueOrDefault();
            ReadOnlyMemory <byte> serverDHNonce = default;

            if (clientDHNonce.Length > 0)
            {
                serverDHNonce = transform.GenerateRandomBytes(agreement.PublicKey.KeyLength);

                Service.Principals.CacheKey(agreement.PrivateKey);
            }

            var keyInfo = new KrbKdcDHKeyInfo {
                SubjectPublicKey = agreement.PublicKey.EncodePublicKey()
            };

            if (agreement.PublicKey.CacheExpiry.HasValue)
            {
                keyInfo.DHKeyExpiration = agreement.PublicKey.CacheExpiry;
                keyInfo.Nonce           = authPack.PKAuthenticator.Nonce;
            }

            var sessionKey = PKInitString2Key.String2Key(
                derivedKey.Span,
                transform.KeySize,
                clientDHNonce.Span,
                serverDHNonce.Span
                );

            var paPkRep = new KrbPaPkAsRep
            {
                DHInfo = new KrbDHReplyInfo
                {
                    DHSignedData  = SignDHResponse(keyInfo),
                    ServerDHNonce = serverDHNonce
                }
            };

            preauth.PaData = new[]
            {
                new KrbPaData
                {
                    Type  = PaDataType.PA_PK_AS_REP,
                    Value = paPkRep.Encode()
                }
            };

            preauth.EncryptedPartKey = new KerberosKey(key: sessionKey.ToArray(), etype: etype);
            preauth.ClientAuthority  = PaDataType.PA_PK_AS_REQ;

            return(null);
        }
 public CryptoServiceTests()
 {
     _cryptoService = new CryptoService();
 }
 protected static string DecryptFolder(string rawData)
 {
     return(CryptoService.Decrypt(rawData));
 }
        public TokenModel StartSession([FromBody] TokenModel refreshToken)
        {
            using (IUMdbEntities entities = new IUMdbEntities())
            {
                #region Validation

                #region CheckIfRefreshTokenIsNull
                if (refreshToken == null)
                {
                    return(null);
                }
                #endregion

                JWTService serviceJWT = new JWTService(DefaultSecretKey.key);

                #region checkIfTokenIsValid
                if (!serviceJWT.IsTokenValid(refreshToken.Token))
                {
                    return(null);
                }
                #endregion

                string        username, password, tokenType;
                List <string> userRoles;
                List <Claim>  tokenClaims = serviceJWT.GetTokenClaims(refreshToken.Token).ToList();
                username  = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.Username)).Value;
                password  = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.Password)).Value;
                userRoles = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.Roles)).Value.Split(',').ToList();
                tokenType = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.TokenType)).Value;

                #region checkTokenType
                if (!tokenType.Equals(MyTokenTypes.RefreshToken))
                {
                    return(null);
                }
                #endregion

                #region checkIfRefreshTokenMatches
                bool checkIfRefreshTokenMatches = entities.Users
                                                  .Any(e => e.Username == username && e.RefreshToken == refreshToken.Token);

                if (!checkIfRefreshTokenMatches)
                {
                    return(null);
                }
                #endregion

                string dbUserHashedPassword = entities.Users
                                              .Where(e => e.Username == username)
                                              .Select(e => e.Password)
                                              .First();
                CryptoService cryptoService = new CryptoService();

                #region checkIfUserPasswordMatches
                bool checkIfUserPasswordMatches = cryptoService.CompareStringToHash(password, dbUserHashedPassword);

                if (!checkIfUserPasswordMatches)
                {
                    return(null);
                }
                #endregion

                #endregion

                Users dbUser = entities.Users
                               .Where(e => e.Username == username)
                               .First();

                JWTContainerModel newBearerTokenJWTContainerModel = JWTContainerModel.GetUserJWTContainerModel(
                    username, password, userRoles, MyTokenTypes.BearerToken);
                string newBearerToken = serviceJWT.GenerateToken(newBearerTokenJWTContainerModel, true);

                Users newUser = new Users()
                {
                    Id           = dbUser.Id,
                    Username     = dbUser.Username,
                    Password     = dbUser.Password,
                    RefreshToken = dbUser.RefreshToken,
                    BearerToken  = newBearerToken,
                    GoogleId     = dbUser.GoogleId
                };

                entities.Users.AddOrUpdate(newUser);
                entities.SaveChanges();

                return(new TokenModel(newBearerToken));
            }
        }
        public async Task <IActionResult> Pay() //[FromBody] modelType model
        {
            //TODO: Implement Realistic Implementation
            //await Task.Yield();
            //return Ok(HttpContext.Request.Form.Count);

            var crService = new CryptoService();
            var dsHelper  = new DataStringHelper();

            var payment = new Payment
            {
                MerchantId   = "1755156",
                TerminalId   = "E7883166",
                PurchaseTime = "181107091010",
                OrderId      = "VHS1036004",
                Currency     = "980",
                TotalAmount  = "100",
                PurchaseDesc = "Test purchase",
                SessionData  = "584sds565hgj76GGjh6756248",
            };

            var dataString = dsHelper.GetDataStringForSign(
                merchantId: payment.MerchantId,
                terminalId: payment.TerminalId,
                purchaseTime: payment.PurchaseTime,
                orderId: payment.OrderId,
                currency: payment.Currency,
                totalAmount: payment.TotalAmount,
                sessionData: payment.SessionData
                );

            //payment.Signature = Base64UrlTextEncoder.Encode(crService.GetSign(dataString));
            payment.Signature = crService.GetSign(dataString);

            var contentResult = new ContentResult {
                ContentType = "text/html",
                StatusCode  = (int)HttpStatusCode.OK,
                //Content = "<html><body>Welcome</body></html>"
            };

            StringBuilder s = new StringBuilder();

            s.AppendFormat("<html>");
            //s.AppendFormat("<body onload='document.forms[\"form\"].submit()'>");
            s.AppendFormat("<body>");
            s.AppendFormat("<form name='form' action='{0}' method='post'>", "https://ecg.test.upc.ua/go/enter");
            s.AppendFormat("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "Version", payment.Version);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "MerchantID", payment.MerchantId);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "TerminalID", payment.TerminalId);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "PurchaseTime", payment.PurchaseTime);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "OrderID", payment.OrderId);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "Currency", payment.Currency);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "TotalAmount", payment.TotalAmount);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "SD", payment.SessionData);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "locale", "uk");
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "PurchaseDesc", payment.PurchaseDesc);
            s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", "Signature", payment.Signature);
            s.AppendFormat("<input type='submit' value='Post' />");
            s.AppendFormat("</form></body></html>");

            contentResult.Content = s.ToString();

            return(contentResult);

            //var client = new HttpClient();
            //client.BaseAddress = new Uri("https://ecg.test.upc.ua");
            //client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //var responce = await client.PostAsync("go/enter", new StringContent(JsonConvert.SerializeObject(payment), Encoding.UTF8, "application/json"));

            // IList<KeyValuePair<string, string>> nameValueCollection = new List<KeyValuePair<string, string>> {
            //     { new KeyValuePair<string, string>("MerchantID", payment.MerchantId) },
            //     { new KeyValuePair<string, string>("TerminalId", payment.TerminalId) },
            //     { new KeyValuePair<string, string>("PurchaseTime", payment.PurchaseTime) },
            //     { new KeyValuePair<string, string>("OrderId", payment.OrderId) },
            //     { new KeyValuePair<string, string>("Currency", payment.Currency) },
            //     { new KeyValuePair<string, string>("TotalAmount", payment.TotalAmount) },
            //     { new KeyValuePair<string, string>("SD", payment.SessionData) },
            //     { new KeyValuePair<string, string>("Signature", payment.Signature) },
            // };

            // var response = await client.PostAsync("https://ecg.test.upc.ua/go/enter", new FormUrlEncodedContent(nameValueCollection));
            // var str = await response.Content.ReadAsStringAsync();

            //return Ok(str);
        }
        public TokenModel LogIn([FromBody] Users user)
        {
            using (IUMdbEntities entities = new IUMdbEntities())
            {
                #region Validation

                #region checkIfUserIsNull
                if (user == null)
                {
                    return(null);
                }
                #endregion

                #region checkIfUserExist
                bool checkIfUserExist = entities.Users
                                        .Any(e => e.Username == user.Username);

                if (!checkIfUserExist)
                {
                    return(null);
                }
                #endregion

                string dbUserHashedPassword = entities.Users
                                              .Where(e => e.Username == user.Username)
                                              .Select(e => e.Password)
                                              .First();
                CryptoService cryptoService = new CryptoService();

                #region checkIfUserPasswordMatches
                bool checkIfUserPasswordMatches = cryptoService.CompareStringToHash(user.Password, dbUserHashedPassword);

                if (!checkIfUserPasswordMatches)
                {
                    return(null);
                }
                #endregion

                #endregion

                Users dbUser = entities.Users
                               .First(e => e.Username == user.Username);

                List <string> userRoles = entities.Workplaces
                                          .Where(e => e.UserId == dbUser.Id)
                                          .Select(e => e.UserRoles.RoleName)
                                          .ToList();

                JWTContainerModel newRefreshTokenJWTContainerModel = JWTContainerModel.GetUserJWTContainerModel(
                    user.Username, user.Password, userRoles, MyTokenTypes.RefreshToken);
                JWTService serviceJWT      = new JWTService(DefaultSecretKey.key);
                string     newRefreshToken = serviceJWT.GenerateToken(newRefreshTokenJWTContainerModel);

                Users newUser = new Users()
                {
                    Id           = dbUser.Id,
                    Username     = dbUser.Username,
                    Password     = dbUser.Password,
                    RefreshToken = newRefreshToken,
                    GoogleId     = dbUser.GoogleId
                };

                entities.Users.AddOrUpdate(newUser);
                entities.SaveChanges();

                return(new TokenModel(newRefreshToken));
            }
        }
        public async void dataListening(object cSocket)
        {
            string content      = string.Empty;
            Socket clientSocket = (Socket)cSocket;

            LoggingService.Instance.AddLog("*Client: " + ToString() + " open");

            while (isOpen)
            {
                try
                {
                    if (!clientSocket.Connected)
                    {
                        LoggingService.Instance.AddLog("*Client: " + ToString() + " closed");
                        LoggingService.Instance.RemoveClient(this);
                        clientSocket.Shutdown(SocketShutdown.Both);
                        clientSocket.Close();
                        isOpen = false;
                        return;
                    }

                    content = receiveData(clientSocket);

                    if (CryptoService.isEncrypted(content))
                    {
#if IMPROVED_PACKET_ENCRYPTION
                        var content2 = CryptoService.Decrypt <AesManaged>(content.Substring(0, content.Length - StringConstants.PacketEnding.Length), StringConstants.SymmetricKey, StringConstants.SymmetricSalt);
                        content = string.Format("{0}{1}", content2, content.Substring(content.Length - StringConstants.PacketEnding.Length));
#endif
                        if (content.IndexOf(StringConstants.PacketEnding) > -1)
                        {
                            if (content.Split('\t').Length < 3)
                            {
                                defaultSend(clientSocket);
                            }
                            else
                            {
                                LoggingService.Instance.AddLog("> " + ToString() + "\t-->\t" + content);
                                if (content.StartsWith("4\tEOT\t"))
                                {
                                    LoggingService.Instance.AddLog("*Client: " + ToString() + " closed");
                                    LoggingService.Instance.RemoveClient(this);
                                    clientSocket.Shutdown(SocketShutdown.Both);
                                    clientSocket.Close();
                                    isOpen = false;
                                    return;
                                }

                                content = await PacketAnalyzeService.Instance.getPacketResponse(content, this);

                                LoggingService.Instance.AddLog("> " + ToString() + "\t<--\t" + content);
#if IMPROVED_PACKET_ENCRYPTION
                                content = string.Format("{0}{1}", CryptoService.Encrypt <AesManaged>(content.Substring(0, content.Length - StringConstants.PacketEnding.Length), StringConstants.SymmetricKey, StringConstants.SymmetricSalt), StringConstants.PacketEnding);
#endif
                                sendData(clientSocket, content);
                            }
                        }
                        else
                        {
                            defaultSend(clientSocket);
                        }
                    }
                    else
                    {
                        defaultSend(clientSocket);
                    }
                }
                catch (SocketException ex)
                {
                    LoggingService.Instance.WriteException(ex);
                }
            }
        }
        /*********** Control request ***********/

        private void HandleControlRequest(string rpNonce, IPEndPoint ps4Endpoint, PS4RemotePlayData ps4RemotePlayData)
        {
            bool   connectedSuccess = false;
            Socket socket           = null;

            try
            {
                IPEndPoint ipEndPoint = new IPEndPoint(ps4Endpoint.Address, ControlPort);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ipEndPoint);

                byte[] rpKeyBuffer    = HexUtil.Unhexlify(ps4RemotePlayData.RemotePlay.RpKey);
                byte[] rpNonceDecoded = Convert.FromBase64String(rpNonce);
                OnPs4LogInfo?.Invoke(this,
                                     "RP-Nonce from \"/sce/rp/session\" response: " + HexUtil.Hexlify(rpNonceDecoded));

                Session session = CryptoService.GetSessionForControl(rpKeyBuffer, rpNonceDecoded);

                string controlAesKey = HexUtil.Hexlify(CryptoService.GetSessionAesKeyForControl(rpKeyBuffer, rpNonceDecoded));
                string controlNonce  = HexUtil.Hexlify(CryptoService.GetSessionNonceValueForControl(rpNonceDecoded));
                OnPs4LogInfo?.Invoke(this, "!!! Control AES Key: " + controlAesKey);
                OnPs4LogInfo?.Invoke(this, "!!! Control AES Nonce: " + controlNonce + Environment.NewLine);

                byte[] registrationKeyBuffer    = HexUtil.Unhexlify(ps4RemotePlayData.RemotePlay.RegistrationKey);
                byte[] registrationKeyPadding   = { 0, 0, 0, 0, 0, 0, 0, 0 };
                byte[] encryptedRegistrationKey =
                    session.Encrypt(ByteUtil.ConcatenateArrays(registrationKeyBuffer, registrationKeyPadding));
                string encodedRegistrationKey = Convert.ToBase64String(encryptedRegistrationKey);

                byte[] randomDid    = Guid.NewGuid().ToByteArray();
                byte[] didPrefix    = { 0x00, 0x18, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x80 };
                byte[] didPadding   = { 48, 48, 48, 48, 48, 48, 48 };
                byte[] encryptedDid = session.Encrypt(ByteUtil.ConcatenateArrays(didPrefix, randomDid, didPadding));
                string encodedDid   = Convert.ToBase64String(encryptedDid);

                string osType          = "Win10.0.0";
                byte[] osTypeBuffer    = Encoding.UTF8.GetBytes(osType);
                byte[] osTypePadding   = { 0 };
                byte[] encryptedOsType = session.Encrypt(ByteUtil.ConcatenateArrays(osTypeBuffer, osTypePadding));
                string encodedOsType   = Convert.ToBase64String(encryptedOsType);

                string host = ps4Endpoint.Address + ":" + ControlPort;

                string requestData = "GET /sce/rp/session/ctrl HTTP/1.1\r\n" +
                                     $"HOST: {host}\r\n" +
                                     "User-Agent: remoteplay Windows\r\n" +
                                     "Connection: keep-alive\r\n" +
                                     "Content-Length: 0\r\n" +
                                     $"RP-Auth: {encodedRegistrationKey}\r\n" +
                                     "RP-Version: 9.0\r\n" +
                                     $"RP-Did: {encodedDid}\r\n" +
                                     "RP-ControllerType: 3\r\n" +
                                     "RP-ClientType: 11\r\n" +
                                     $"RP-OSType: {encodedOsType}\r\n" +
                                     "RP-ConPath: 1\r\n" +
                                     "\r\n";

                socket.Send(Encoding.UTF8.GetBytes(requestData));
                byte[] receiveBuffer = new byte[8192];
                int    readBytes     = socket.Receive(receiveBuffer);
                byte[] response      = new byte[readBytes];
                Buffer.BlockCopy(receiveBuffer, 0, response, 0, response.Length);
                string httpResponse = Encoding.ASCII.GetString(receiveBuffer, 0, readBytes);

                HttpStatusCode statusCode = HttpUtils.GetStatusCode(httpResponse);
                if (statusCode == HttpStatusCode.OK)
                {
                    OnPs4LogInfo?.Invoke(this, "\"/sce/rp/session/ctrl\" response: " + Environment.NewLine + httpResponse.Trim() + Environment.NewLine);
                    OnPs4LogInfo?.Invoke(this, "TCP connection to PS4 established" + Environment.NewLine);
                    _clientSocket = socket;
                    _clientSocket.ReceiveTimeout = 0;
                    PingPongAsyncResult connectionStateObject = new PingPongAsyncResult {
                        RemoteSocket = _clientSocket
                    };
                    connectionStateObject.RemoteSocket.BeginReceive(connectionStateObject.Buffer, 0,
                                                                    connectionStateObject.Buffer.Length, SocketFlags.None, PingPongHandler,
                                                                    connectionStateObject);
                    OnPs4ConnectionSuccess?.Invoke(this, EventArgs.Empty);
                    connectedSuccess = true;
                    InitializeRemotePlayChannel(session, ps4Endpoint);
                }
            }
            catch (Exception e)
            {
                OnPs4ConnectionError?.Invoke(this, "Exception occured /sce/rp/session/ctrl" + e);
            }
            finally
            {
                if (!connectedSuccess)
                {
                    socket?.Close();
                }
            }
        }
Exemple #25
0
        internal static byte[] CreatePassword(string userId, byte[] salt, string password)
        {
            var passwd = PreparePassword(userId, salt, password);

            return(CryptoService.ComputeMD5Hash(CryptoService.Encrypt(passwd)));
        }
        private RemotePlayContext SendBigBangMessages(Socket udpClient, Session session, RemotePlayContext remotePlayContext)
        {
            /******** Big Payload send ********/

            // Generate random handshake key, for ECDH pubkey signature calculation
            byte[] handshakeKey = new byte[16];
            new Random().NextBytes(handshakeKey);

            // Generate ECDH keypair
            var ecdhKeyPair = CryptoService.GenerateEcdhKeyPair();
            // Get public key bytes
            var ownPublicKey = Session.GetPublicKeyBytesFromKeyPair(ecdhKeyPair);

            // Calculate ECDH pubkey signature
            var ecdhSignature = Session.CalculateHMAC(handshakeKey, ownPublicKey);

            int    unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            string timestampUnix = unixTimestamp.ToString();
            string sessionKey    = timestampUnix + CryptoService.GetUniqueKey(64);

            LaunchSpecification launchSpecs = LaunchSpecification.GetStandardSpecs("sessionId123", handshakeKey);

            byte[] launchSpecBuffer = Encoding.UTF8.GetBytes(launchSpecs.Serialize());

            byte[] cryptoBuffer = new byte[launchSpecBuffer.Length];
            cryptoBuffer = session.Encrypt(cryptoBuffer, 0);
            byte[] newLaunchSpec = new byte[launchSpecBuffer.Length];
            for (int i = 0; i < launchSpecBuffer.Length; i++)
            {
                newLaunchSpec[i] = (byte)(launchSpecBuffer[i] ^ cryptoBuffer[i]);
            }

            TakionMessage takionBigPayloadMessage = new TakionMessage
            {
                Type       = TakionMessage.PayloadType.Big,
                bigPayload = new BigPayload
                {
                    clientVersion = 9,
                    sessionKey    = sessionKey,
                    launchSpec    = Convert.ToBase64String(newLaunchSpec),
                    encryptedKey  = new byte[] { 0, 0, 0, 0 },
                    ecdhPubKey    = ownPublicKey,
                    ecdhSig       = ecdhSignature
                }
            };

            MemoryStream bigPayloadStream = new MemoryStream();

            Serializer.Serialize(bigPayloadStream, takionBigPayloadMessage);
            byte[] bigPayloadBuffer = ByteUtil.ConcatenateArrays(new byte[1], bigPayloadStream.ToArray()); // Padding byte + BigPayload
            ushort bigPayloadSize   = (ushort)(12 + bigPayloadBuffer.Length);

            ControlMessage controlMessageBigPayload = new ControlMessage(0, remotePlayContext.ReceiverId, 0, 0, 0, 1, bigPayloadSize, remotePlayContext.FuncIncr, 0x10000);

            controlMessageBigPayload.UnParsedPayload = bigPayloadBuffer;
            byte[] initialControlMessage2Data = GetByteArrayForControlMessage(controlMessageBigPayload);

            OnPs4LogInfo?.Invoke(this, Environment.NewLine + "Sending big payload:");
            OnPs4LogInfo?.Invoke(this, "ECDH pubkey: " + HexUtil.Hexlify(takionBigPayloadMessage.bigPayload.ecdhPubKey));
            OnPs4LogInfo?.Invoke(this, "ECDH sig: " + HexUtil.Hexlify(takionBigPayloadMessage.bigPayload.ecdhSig));
            OnPs4LogInfo?.Invoke(this, "Session key: " + takionBigPayloadMessage.bigPayload.sessionKey + Environment.NewLine);

            ControlResult bigPayloadResult = SendControlDataAndWaitForAnswer(udpClient, initialControlMessage2Data, 2, "Send BigPayload");

            if (!bigPayloadResult.WasSuccessful)
            {
                return(null);
            }

            /******** Bang Payload receive ********/

            ControlMessage answerPacket1 = bigPayloadResult.ControlMessages[0];
            ControlMessage answerPacket2 = bigPayloadResult.ControlMessages[1];

            if (answerPacket1.ProtoBuffFlag != 1 && answerPacket2.ProtoBuffFlag != 1)
            {
                return(null);
            }

            TakionMessage bangPayload = answerPacket1.ProtoBuffFlag == 1 ?
                                        Serializer.Deserialize <TakionMessage>(new MemoryStream(answerPacket1.UnParsedPayload)) :
                                        Serializer.Deserialize <TakionMessage>(new MemoryStream(answerPacket2.UnParsedPayload));

            if (bangPayload.bangPayload == null)
            {
                return(null);
            }

            ControlMessage bangPayloadControl = answerPacket1.ProtoBuffFlag == 1 ? answerPacket1 : answerPacket2;

            OnPs4LogInfo?.Invoke(this, Environment.NewLine + "Received bang payload:");
            OnPs4LogInfo?.Invoke(this, "ECDH pubkey: " + HexUtil.Hexlify(bangPayload.bangPayload.ecdhPubKey));
            OnPs4LogInfo?.Invoke(this, "ECDH sig: " + HexUtil.Hexlify(bangPayload.bangPayload.ecdhSig));
            OnPs4LogInfo?.Invoke(this, "Session key: " + bangPayload.bangPayload.sessionKey);

            /* Derive ECDH shared secret */
            var foreignPubkeyParams = Session.ConvertPubkeyBytesToCipherParams(bangPayload.bangPayload.ecdhPubKey);

            remotePlayContext.SharedSecret   = Session.GenerateSharedSecret(ecdhKeyPair.Private, foreignPubkeyParams);
            remotePlayContext.LocalGmacInfo  = CryptoService.SetUpGmac(2, handshakeKey, remotePlayContext.SharedSecret);
            remotePlayContext.RemoteGmacInfo = CryptoService.SetUpGmac(3, handshakeKey, remotePlayContext.SharedSecret);
            OnPs4LogInfo?.Invoke(this, "HANDSHAKE KEY: " + HexUtil.Hexlify(handshakeKey));
            OnPs4LogInfo?.Invoke(this, "SHARED SECRET: " + HexUtil.Hexlify(remotePlayContext.SharedSecret));

            byte[]         ackBangPayload        = HexUtil.Unhexlify("00000000");
            ushort         ackBangPayloadSize    = (ushort)(12 + ackBangPayload.Length);
            ControlMessage ackBangPayloadMessage = new ControlMessage(0, bangPayloadControl.FuncIncr, 0, 0, 3, 0, ackBangPayloadSize, bangPayloadControl.FuncIncr, 0x19000);

            ackBangPayloadMessage.UnParsedPayload = ackBangPayload;
            byte[] ackBangPayloadMessageData = GetByteArrayForControlMessage(ackBangPayloadMessage);
            remotePlayContext.LastSentMessage = ackBangPayloadMessageData;

            SendData(udpClient, ackBangPayloadMessageData);

            return(remotePlayContext);
        }
Exemple #27
0
        private void RegisterLocalServices()
        {
            ServiceContainer.Register <ILogService>("logService", new AndroidLogService());

            // Note: This might cause a race condition. Investigate more.
            Task.Run(() =>
            {
                FFImageLoading.Forms.Platform.CachedImageRenderer.Init(true);
                FFImageLoading.ImageService.Instance.Initialize(new FFImageLoading.Config.Configuration
                {
                    FadeAnimationEnabled         = false,
                    FadeAnimationForCachedImages = false,
                    HttpClient = new HttpClient(new AndroidClientHandler()
                    {
                        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                    })
                });
                ZXing.Net.Mobile.Forms.Android.Platform.Init();
            });
            CrossFingerprint.SetCurrentActivityResolver(() => CrossCurrentActivity.Current.Activity);

            var preferencesStorage     = new PreferencesStorageService(null);
            var documentsPath          = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var liteDbStorage          = new LiteDbStorageService(Path.Combine(documentsPath, "bitwarden.db"));
            var localizeService        = new LocalizeService();
            var broadcasterService     = new BroadcasterService();
            var messagingService       = new MobileBroadcasterMessagingService(broadcasterService);
            var i18nService            = new MobileI18nService(localizeService.GetCurrentCultureInfo());
            var secureStorageService   = new SecureStorageService();
            var cryptoPrimitiveService = new CryptoPrimitiveService();
            var mobileStorageService   = new MobileStorageService(preferencesStorage, liteDbStorage);
            var deviceActionService    = new DeviceActionService(mobileStorageService, messagingService,
                                                                 broadcasterService, () => ServiceContainer.Resolve <IEventService>("eventService"));
            var platformUtilsService = new MobilePlatformUtilsService(deviceActionService, messagingService,
                                                                      broadcasterService);
            var biometricService        = new BiometricService();
            var cryptoFunctionService   = new PclCryptoFunctionService(cryptoPrimitiveService);
            var cryptoService           = new CryptoService(mobileStorageService, secureStorageService, cryptoFunctionService);
            var passwordRepromptService = new MobilePasswordRepromptService(platformUtilsService, cryptoService);

            ServiceContainer.Register <IBroadcasterService>("broadcasterService", broadcasterService);
            ServiceContainer.Register <IMessagingService>("messagingService", messagingService);
            ServiceContainer.Register <ILocalizeService>("localizeService", localizeService);
            ServiceContainer.Register <II18nService>("i18nService", i18nService);
            ServiceContainer.Register <ICryptoPrimitiveService>("cryptoPrimitiveService", cryptoPrimitiveService);
            ServiceContainer.Register <IStorageService>("storageService", mobileStorageService);
            ServiceContainer.Register <IStorageService>("secureStorageService", secureStorageService);
            ServiceContainer.Register <IDeviceActionService>("deviceActionService", deviceActionService);
            ServiceContainer.Register <IPlatformUtilsService>("platformUtilsService", platformUtilsService);
            ServiceContainer.Register <IBiometricService>("biometricService", biometricService);
            ServiceContainer.Register <ICryptoFunctionService>("cryptoFunctionService", cryptoFunctionService);
            ServiceContainer.Register <ICryptoService>("cryptoService", cryptoService);
            ServiceContainer.Register <IPasswordRepromptService>("passwordRepromptService", passwordRepromptService);

            // Push
#if FDROID
            ServiceContainer.Register <IPushNotificationListenerService>(
                "pushNotificationListenerService", new NoopPushNotificationListenerService());
            ServiceContainer.Register <IPushNotificationService>(
                "pushNotificationService", new NoopPushNotificationService());
#else
            var notificationListenerService = new PushNotificationListenerService();
            ServiceContainer.Register <IPushNotificationListenerService>(
                "pushNotificationListenerService", notificationListenerService);
            var androidPushNotificationService = new AndroidPushNotificationService(
                mobileStorageService, notificationListenerService);
            ServiceContainer.Register <IPushNotificationService>(
                "pushNotificationService", androidPushNotificationService);
#endif
        }
Exemple #28
0
        private void deszyfrowanieButton_Click(object sender, EventArgs e)
        {
            ListView.SelectedListViewItemCollection selectedItems = deszyfratorListView.SelectedItems;
            int keySize = 0;

            byte[] iv                  = { };
            byte[] sessionKey          = { };
            byte[] blockOfFile         = { };
            byte[] encryptedFile       = { };
            bool   fileDecryptionBegin = false;
            string mode                = "";
            string extension           = "";

            if (!isDecodingPossible())
            {
                return;
            }

            List <byte[]> decryptedFile = new List <byte[]>();
            CryptoService service       = new CryptoService();
            RSAParameters privatekey    = new RSAParameters();

            deszyfrowanieProgressBar.Minimum = 1;
            deszyfrowanieProgressBar.Value   = 1;
            deszyfrowanieProgressBar.Maximum = (int)(new FileInfo(plikDeszyfrowaniaTextBox.Text)).Length;

            using (StreamReader stream = new StreamReader(plikDeszyfrowaniaTextBox.Text, Encoding.UTF8))
            {
                string line = "";
                while ((line = stream.ReadLine()) != null)
                {
                    if (line.Contains("<Name>"))
                    {
                        foreach (ListViewItem item in selectedItems)
                        {
                            if (item.Text == takeValueFromNode(line, "<Name>"))
                            {
                                line       = stream.ReadLine();
                                sessionKey = Convert.FromBase64String(takeValueFromNode(line, "<sessionKey>"));
                                try
                                {
                                    byte[] hash = service.createSha512Hash(hasloTextBox.Text, 16);
                                    privatekey = loadPrivateKey(hash, item.Text);
                                    sessionKey = service.rsaDecoding(sessionKey, privatekey);
                                }
                                catch (System.Security.Cryptography.CryptographicException)
                                {
                                    deszyfrowanieProgressBar.Step = (int)(new FileInfo(plikDeszyfrowaniaTextBox.Text)).Length;
                                    deszyfrowanieProgressBar.PerformStep();
                                    return;
                                }
                            }
                        }
                    }
                    if (line.Contains("<Extension>"))
                    {
                        extension = takeValueFromNode(line, "<Extension>");
                    }
                    if (line.Contains("<KeySize>"))
                    {
                        keySize = Convert.ToInt32(takeValueFromNode(line, "<KeySize>"));
                    }
                    if (line.Contains("<IV>"))
                    {
                        iv = Convert.FromBase64String(takeValueFromNode(line, "<IV>"));
                    }
                    if (line.Contains("<Mode>"))
                    {
                        mode = takeValueFromNode(line, "<Mode>");
                    }
                    if (line.Contains("</EnFile"))
                    {
                        fileDecryptionBegin = false;
                    }
                    else
                    if (line.Contains("EnFile"))
                    {
                        fileDecryptionBegin = true;
                    }
                    else
                    if (fileDecryptionBegin)
                    {
                        blockOfFile = Convert.FromBase64String(line.Substring(0, line.Length));
                        decryptedFile.Add(service.aesDecoding(sessionKey, mode, 128, blockOfFile, iv));
                        deszyfrowanieProgressBar.Step = ASCIIEncoding.Unicode.GetByteCount(line);
                        deszyfrowanieProgressBar.PerformStep();
                    }
                }
            }

            using (FileStream stream = new FileStream(lokalizacjaDeszyfrowaniaTextBox.Text + "\\" + nazwaPlikuDeszyfrowanegoTextBox.Text + "." + extension, FileMode.Create))
            {
                foreach (byte[] line in decryptedFile)
                {
                    stream.Write(line, 0, line.Length);
                }
            }
        }
Exemple #29
0
        public static void Init(HttpClientHandler httpClientHandler = null)
        {
            if (Inited)
            {
                return;
            }
            Inited = true;

            var           platformUtilsService   = Resolve <IPlatformUtilsService>("platformUtilsService");
            var           storageService         = Resolve <IStorageService>("storageService");
            var           secureStorageService   = Resolve <IStorageService>("secureStorageService");
            var           cryptoPrimitiveService = Resolve <ICryptoPrimitiveService>("cryptoPrimitiveService");
            var           i18nService            = Resolve <II18nService>("i18nService");
            var           messagingService       = Resolve <IMessagingService>("messagingService");
            SearchService searchService          = null;

            var stateService          = new StateService();
            var cryptoFunctionService = new PclCryptoFunctionService(cryptoPrimitiveService);
            var cryptoService         = new CryptoService(storageService, secureStorageService, cryptoFunctionService);
            var tokenService          = new TokenService(storageService);
            var apiService            = new ApiService(tokenService, platformUtilsService, (bool expired) => Task.FromResult(0),
                                                       httpClientHandler);
            var appIdService    = new AppIdService(storageService);
            var userService     = new UserService(storageService, tokenService);
            var settingsService = new SettingsService(userService, storageService);
            var cipherService   = new CipherService(cryptoService, userService, settingsService, apiService,
                                                    storageService, i18nService, () => searchService);
            var folderService = new FolderService(cryptoService, userService, apiService, storageService,
                                                  i18nService, cipherService);
            var collectionService = new CollectionService(cryptoService, userService, storageService, i18nService);

            searchService = new SearchService(cipherService);
            var lockService = new LockService(cryptoService, userService, platformUtilsService, storageService,
                                              folderService, cipherService, collectionService, searchService, messagingService, null);
            var syncService = new SyncService(userService, apiService, settingsService, folderService,
                                              cipherService, cryptoService, collectionService, storageService, messagingService,
                                              () => messagingService.Send("logout"));
            var passwordGenerationService = new PasswordGenerationService(cryptoService, storageService,
                                                                          cryptoFunctionService);
            var totpService = new TotpService(storageService, cryptoFunctionService);
            var authService = new AuthService(cryptoService, apiService, userService, tokenService, appIdService,
                                              i18nService, platformUtilsService, messagingService);
            // TODO: export service
            var auditService       = new AuditService(cryptoFunctionService, apiService);
            var environmentService = new EnvironmentService(apiService, storageService);

            Register <IStateService>("stateService", stateService);
            Register <ICryptoFunctionService>("cryptoFunctionService", cryptoFunctionService);
            Register <ICryptoService>("cryptoService", cryptoService);
            Register <ITokenService>("tokenService", tokenService);
            Register <IApiService>("apiService", apiService);
            Register <IAppIdService>("appIdService", appIdService);
            Register <IUserService>("userService", userService);
            Register <ISettingsService>("settingsService", settingsService);
            Register <ICipherService>("cipherService", cipherService);
            Register <IFolderService>("folderService", folderService);
            Register <ICollectionService>("collectionService", collectionService);
            Register <ISearchService>("searchService", searchService);
            Register <ISyncService>("syncService", syncService);
            Register <ILockService>("lockService", lockService);
            Register <IPasswordGenerationService>("passwordGenerationService", passwordGenerationService);
            Register <ITotpService>("totpService", totpService);
            Register <IAuthService>("authService", authService);
            Register <IAuditService>("auditService", auditService);
            Register <IEnvironmentService>("environmentService", environmentService);
        }
 public void Setup()
 {
     _encodedString = CryptoService.Encrypt(StringToEncode);
 }
        public void when_decrypting_we_get_same_value_as_string_to_encode()
        {
            var decodedString = CryptoService.Decrypt(_encodedString);

            Assert.AreEqual(StringToEncode, decodedString);
        }
        private void SeedTestData()
        {
            var dogsRepository = Container.Resolve <IRepository <Dog> >();

            dogsRepository.DeleteAll(); // **** CLEAN BD ****
            // Les données seront ajoutées une seul foi dans la BD.
            if (dogsRepository.GetAll().Count() != 0)
            {
                return;
            }

            var dog1 = new Dog()
            {
                Name        = UiText.ANY_DOG_NAME,
                ImageUrl    = UiText.ANY_DOG_IMAGE_URL,
                Price       = UiText.ANY_DOG_PRICE,
                Race        = UiText.ANY_DOG_RACE,
                Sex         = UiText.ANY_DOG_SEX,
                Description = UiText.ANY_DOG_DESCRIPTION
            };
            var dog2 = new Dog()
            {
                Name        = "Cloud",
                ImageUrl    = "https://images.dog.ceo/breeds/shiba/shiba-11.jpg",
                Price       = (float)399.99,
                Race        = "Samoyede",
                Sex         = "Male",
                Description = "13 mois, chien blanc"
            };
            var dog3 = new Dog()
            {
                Name        = "Leo",
                ImageUrl    = "https://images.dog.ceo/breeds/pug/n02110958_1975.jpg",
                Price       = (float)269.99,
                Race        = "Husky",
                Sex         = "Male",
                Description = "Gentil et calme"
            };

            dogsRepository.Add(dog1);
            dogsRepository.Add(dog2);
            dogsRepository.Add(dog3);

            var usersRepository = Container.Resolve <IRepository <User> >();

            usersRepository.DeleteAll(); // **** CLEAN BD ****
            // Les données seront ajoutées une seul foi dans la BD.
            if (usersRepository.GetAll().Count() != 0)
            {
                return;
            }

            ICryptoService        cryptoService        = new CryptoService();
            ISecureStorageService secureStorageService = new SecureStorageService();
            string salt = cryptoService.GenerateSalt();
            string key  = cryptoService.GenerateEncryptionKey();

            var user1 = new User()
            {
                Login          = "******",
                HashedPassword = cryptoService.HashSHA512("456", salt),
                PasswordSalt   = salt,
                CreditCard     = cryptoService.Encrypt("1234", key),
                DogId          = dog1.Id
            };

            secureStorageService.SetUserEncryptionKeyAsync(user1, key);
            usersRepository.Add(user1);   // après le add, user1 contient un id

            salt = cryptoService.GenerateSalt();
            key  = cryptoService.GenerateEncryptionKey();

            var user2 = new User()
            {
                Login          = "******",
                HashedPassword = cryptoService.HashSHA512("789", salt),
                PasswordSalt   = salt,
                CreditCard     = cryptoService.Encrypt("1234", key),
                DogId          = -1
            };

            secureStorageService.SetUserEncryptionKeyAsync(user2, key);
            usersRepository.Add(user2);
        }