Example #1
0
        /// <summary>
        /// 获取token值
        /// </summary>
        private bool GetNewToken(out string errorMsg)
        {
            errorMsg = string.Empty;
            var  loop      = 0;
            bool isSuccess = false;

            //while ((loop < 5 && !string.IsNullOrEmpty(CryptTool.ErrorMsg) && CryptTool.ErrorMsg.Contains(PRO_ReceiptsInvMgr.Resources.Message.JXCertError)) || loop == 0)
            while (loop < 5)
            {
                isSuccess = CryptTool.Login(GlobalInfo.JxPwd);
                loop++;
                if (isSuccess)
                {
                    break;
                }
            }

            if (!isSuccess)
            {
                errorMsg = CryptTool.ErrorMsg;
            }
            else
            {
                GlobalInfo.token = CryptTool.Token;
            }
            return(isSuccess);
        }
        protected override void Execute()
        {
            string phoneNo = this.phoneNo.Value;

            byte[] phoneHash = CryptTool.HashPhoneNo(phoneNo);
            System.Console.WriteLine(DataUtils.ByteArrayToHexString(phoneHash));
        }
Example #3
0
        public MainWindow()
        {
            InitializeComponent();

            MainWindowInstance = this;

            if (GlobalInfo.ExistTax)
            {
                lblNsrInfo.Visibility   = Visibility.Hidden;
                panelNsrInfo.Visibility = Visibility.Visible;
                tbNsrsbh.Text           = GlobalInfo.NSRSBH;

                CryptTool.UserPin = GlobalInfo.JxPwd;
                CryptTool.getThisCert();
                tbNsrmc.Text     = CryptTool.Nsrmc;// "北京聚达创通科技有限公司";
                GlobalInfo.NSRMC = CryptTool.Nsrmc;
            }
            else
            {
                GlobalInfo.NSRSBH  = "0";
                GlobalInfo.FJH     = "0";
                GlobalInfo.orgCode = "0";

                lblNsrInfo.Visibility   = Visibility.Visible;
                panelNsrInfo.Visibility = Visibility.Hidden;
                lblNsrInfo.Content      = PRO_ReceiptsInvMgr.Resources.Message.NotConnTaxDisk;
            }
        }
Example #4
0
        /// <summary>
        /// Wrapper to derive public key <see cref="CryptTool.DerivePublicKey"/>
        /// </summary>
        /// <param name="privateKey">private key as file path or hex-string</param>
        /// <returns>Public key as hex-string</returns>
        public string DerivePublicKey(string privateKey)
        {
            byte[] privateKeyBytes = GetKey(privateKey, Key.KeyType.PRIVATE);
            byte[] publicKey       = CryptTool.DerivePublicKey(privateKeyBytes);

            return(new Key(Key.KeyType.PUBLIC, publicKey).Encode());
        }
Example #5
0
        protected override void Execute()
        {
            byte[] privateKey = this.privateKeyField.GetValue();
            byte[] publicKey  = CryptTool.DerivePublicKey(privateKey);

            System.Console.WriteLine("res");
            System.Console.WriteLine(new Key(Key.KeyType.PUBLIC, publicKey).Encode());
        }
Example #6
0
        public void TestCreateKeyPair()
        {
            byte[] privateKey = new byte[32];            //NaCl.SECRETKEYBYTES
            byte[] publicKey  = new byte[32];            //NaCl.PUBLICKEYBYTES

            CryptTool.GenerateKeyPair(ref privateKey, ref publicKey);

            Assert.IsFalse(privateKey.SequenceEqual(new byte[32]), "empty private key");
            Assert.IsFalse(publicKey.SequenceEqual(new byte[32]), "empty public key");
        }
Example #7
0
        public void TestRandomNonce()
        {
            byte[] randomNonce = CryptTool.RandomNonce();

            //random nonce should be a byte array
            Assert.IsNotNull(randomNonce, "random nonce");

            //with a length of 24
            Assert.AreEqual(randomNonce.Length, ThreemaMessage.NONCEBYTES, "nonce length");
        }
Example #8
0
        public void TestDerivePublicKey()
        {
            Key privateKey = Key.DecodeKey(Common.myPrivateKey);
            Key publicKey  = Key.DecodeKey(Common.myPublicKey);

            byte[] derivedPublicKey = CryptTool.DerivePublicKey(privateKey.key);

            Assert.IsNotNull(derivedPublicKey, "derived public key");
            Assert.IsTrue(derivedPublicKey.SequenceEqual(publicKey.key));
        }
        public bool MessageCallback([FromForm] ThreemaMessageCallback threemaMessageCallback)
        {
            try
            {
                try
                {
                    _log.LogDebug("ThreemaController.MessageCallback: ModelState {0}, ThreemaMessageCallback {1}", ModelState.IsValid, threemaMessageCallback.ToString());
                }
                catch (Exception ex)
                {
                    _log.LogError("ThreemaController.MessageCallback 1 " + ex.Message);
                }

                string nonce = threemaMessageCallback.Nonce;
                string box   = threemaMessageCallback.Box;

                string callbackPublicKey = GetPublicKey(threemaMessageCallback.From);

                string myPrivateKey = this._configuration["Threema:PrivateKey"];
                Key    privateKey   = Key.DecodeKey(myPrivateKey);
                Key    publicKey    = Key.DecodeKey(callbackPublicKey);

                ThreemaMessage message = CryptTool.DecryptMessage(
                    DataUtils.HexStringToByteArray(box),
                    privateKey.key,
                    publicKey.key,
                    DataUtils.HexStringToByteArray(nonce)
                    );

                switch (message.GetTypeCode())
                {
                case TextMessage.TYPE_CODE:
                    _log.LogInformation("ThreemaController.MessageCallback TextMessage from {0} to {1}: {2}", threemaMessageCallback.From, threemaMessageCallback.To, message.ToString());
                    break;

                //case DeliveryReceipt.TYPE_CODE:
                //class DeliveryReceipt statt public class DeliveryReceipt
                case 0x80:
                    _log.LogInformation("ThreemaController.MessageCallback DeliveryReceipt from {0} to {1}: {2}", threemaMessageCallback.From, threemaMessageCallback.To, message.ToString());
                    break;

                default:
                    _log.LogInformation("ThreemaController.MessageCallback ThreemaMessage? from {0} to {1}: {2}", threemaMessageCallback.From, threemaMessageCallback.To, message.ToString());
                    break;
                }

                return(true);
            }
            catch (Exception ex)
            {
                _log.LogError("ThreemaController.MessageCallback 2 " + ex.Message);
                return(false);
            }
        }
Example #10
0
        protected override void Execute()
        {
            byte[] privateKey = new byte[32];            //NaCl.SECRETKEYBYTES
            byte[] publicKey  = new byte[32];            //NaCl.PUBLICKEYBYTES

            CryptTool.GenerateKeyPair(ref privateKey, ref publicKey);

            // Write both keys to file
            DataUtils.WriteKeyFile(this.privateKeyPath.Value, new Key(Key.KeyType.PRIVATE, privateKey));
            DataUtils.WriteKeyFile(this.publicKeyPath.Value, new Key(Key.KeyType.PUBLIC, publicKey));
        }
Example #11
0
        /// <summary>
        /// Wrapper to generate key pair <see cref="Threema.MsgApi.CryptTool.GenerateKeyPair"/>
        /// </summary>
        /// <param name="privateKeyPath">Full path name of private key file</param>
        /// <param name="publicKeyPath">Full path name of public key file</param>
        public void GenerateKeyPair(string privateKeyPath, string publicKeyPath)
        {
            byte[] privateKey = new byte[32];            //NaCl.SECRETKEYBYTES
            byte[] publicKey  = new byte[32];            //NaCl.PUBLICKEYBYTES

            CryptTool.GenerateKeyPair(ref privateKey, ref publicKey);

            // Write both keys to file
            DataUtils.WriteKeyFile(privateKeyPath, new Key(Key.KeyType.PRIVATE, privateKey));
            DataUtils.WriteKeyFile(publicKeyPath, new Key(Key.KeyType.PUBLIC, publicKey));
        }
Example #12
0
        /// <summary>
        /// Encrypt a text message and send it to the given recipient.
        /// </summary>
        /// <param name="threemaId">target Threema ID</param>
        /// <param name="text">the text to send</param>
        /// <returns>generated message ID</returns>
        public string SendTextMessage(string threemaId, string text)
        {
            //fetch public key
            byte[] publicKey = this.apiConnector.LookupKey(threemaId);

            if (publicKey == null)
            {
                throw new InvalidKeyException("invalid threema id");
            }
            EncryptResult res = CryptTool.EncryptTextMessage(text, this.privateKey, publicKey);

            return(this.apiConnector.SendE2EMessage(threemaId, res.Nonce, res.Result));
        }
        private bool CheckCredential(string encryptedId)
        {
            string Id = CryptTool.Decrypt(encryptedId);

            if (Id.Contains("Client") && Id.Contains("Miner Tracker"))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        protected override void Execute()
        {
            byte[] privateKey = this.privateKeyField.GetValue();
            byte[] publicKey  = this.publicKeyField.GetValue();
            byte[] nonce      = this.nonceField.GetValue();

            /* read box from stdin */
            //byte[] box = DataUtils.HexStringToByteArray(ReadStream(System.Console.In));
            byte[] box = DataUtils.HexStringToByteArray(DataUtils.Utf8Endcode(System.Console.ReadLine().Trim()));

            ThreemaMessage message = CryptTool.DecryptMessage(box, privateKey, publicKey, nonce);

            System.Console.WriteLine(message);
        }
        protected override void Execute()
        {
            byte[] privateKey = this.privateKeyField.GetValue();
            byte[] publicKey  = this.publicKeyField.GetValue();

            /* read text from stdin */
            //string text = ReadStream(System.Console.In).Trim();
            string text = DataUtils.Utf8Endcode(System.Console.ReadLine().Trim());

            EncryptResult res = CryptTool.EncryptTextMessage(text, privateKey, publicKey);

            System.Console.WriteLine(DataUtils.ByteArrayToHexString(res.Nonce));
            System.Console.WriteLine(DataUtils.ByteArrayToHexString(res.Result));
        }
Example #16
0
        /// <summary>
        /// Wrapper to decrypt box <see cref="Threema.MsgApi.CryptTool.DecryptMessage"/>
        /// </summary>
        /// <param name="box">Encrypted box as hex-straing</param>
        /// <param name="recipientPrivateKey">Recipient private key as hex-string</param>
        /// <param name="senderPublicKey">Sender public key as hex-string</param>
        /// <param name="nonce">Nonce as hex-string</param>
        /// <returns>Array with type and decrypted message</returns>
        public ArrayList DecryptMessage(string box, string recipientPrivateKey, string senderPublicKey, string nonce)
        {
            byte[] privateKey = GetKey(recipientPrivateKey, Key.KeyType.PRIVATE);
            byte[] publicKey  = GetKey(senderPublicKey, Key.KeyType.PUBLIC);
            byte[] nonceBytes = DataUtils.HexStringToByteArray(nonce);
            byte[] boxBytes   = DataUtils.HexStringToByteArray(box);

            ThreemaMessage message = CryptTool.DecryptMessage(boxBytes, privateKey, publicKey, nonceBytes);

            var result = new ArrayList();

            result.Add(message.GetTypeCode().ToString());
            result.Add(message.ToString());
            return(result);
        }
Example #17
0
        public void TestEncrypt()
        {
            string text = "Dies ist eine Testnachricht. äöü";

            Key privateKey = Key.DecodeKey(Common.myPrivateKey);
            Key publicKey  = Key.DecodeKey(Common.otherPublicKey);

            EncryptResult res = CryptTool.EncryptTextMessage(text, privateKey.key, publicKey.key);

            Assert.IsNotNull(res);
            Assert.IsNotNull(res.Nonce);
            Assert.IsNotNull(res.Result);
            Assert.IsFalse(res.Nonce.SequenceEqual(new byte[res.Nonce.Length]));
            Assert.IsFalse(res.Result.SequenceEqual(new byte[res.Result.Length]));
        }
Example #18
0
        /// <summary>
        /// Wrapper to encrypt text <see cref="Threema.MsgApi.CryptTool.EncryptTextMessage"/>
        /// </summary>
        /// <param name="text">Text to encrypt</param>
        /// <param name="senderPrivateKey">Sender private key as hex-string</param>
        /// <param name="recipientPublicKey">Recipient public key as hex-string</param>
        /// <returns>Array with encrypted text, nonce and size</returns>
        public ArrayList EncryptTextMessage(string text, string senderPrivateKey, string recipientPublicKey)
        {
            byte[] privateKey = GetKey(senderPrivateKey, Key.KeyType.PRIVATE);
            byte[] publicKey  = GetKey(recipientPublicKey, Key.KeyType.PUBLIC);

            string textEncoded = DataUtils.Utf8Endcode(text);

            EncryptResult encryptResult = CryptTool.EncryptTextMessage(textEncoded, privateKey, publicKey);

            var result = new ArrayList();

            result.Add(DataUtils.ByteArrayToHexString(encryptResult.Result));
            result.Add(DataUtils.ByteArrayToHexString(encryptResult.Nonce));
            result.Add(encryptResult.Size.ToString());
            return(result);
        }
Example #19
0
        public void TestDecrypt()
        {
            string nonce = "0a1ec5b67b4d61a1ef91f55e8ce0471fee96ea5d8596dfd0";
            string box   = "45181c7aed95a1c100b1b559116c61b43ce15d04014a805288b7d14bf3a993393264fe554794ce7d6007233e8ef5a0f1ccdd704f34e7c7b77c72c239182caf1d061d6fff6ffbbfe8d3b8f3475c2fe352e563aa60290c666b2e627761e32155e62f048b52ef2f39c13ac229f393c67811749467396ecd09f42d32a4eb419117d0451056ac18fac957c52b0cca67568e2d97e5a3fd829a77f914a1ad403c5909fd510a313033422ea5db71eaf43d483238612a54cb1ecfe55259b1de5579e67c6505df7d674d34a737edf721ea69d15b567bc2195ec67e172f3cb8d6842ca88c29138cc33e9351dbc1e4973a82e1cf428c1c763bb8f3eb57770f914a";

            Key privateKey = Key.DecodeKey(Common.otherPrivateKey);
            Key publicKey  = Key.DecodeKey(Common.myPublicKey);

            ThreemaMessage message = CryptTool.DecryptMessage(
                DataUtils.HexStringToByteArray(box),
                privateKey.key,
                publicKey.key,
                DataUtils.HexStringToByteArray(nonce)
                );

            Assert.IsNotNull(message);
            Assert.IsInstanceOfType(message, typeof(TextMessage), "message is not a instance of text message");
            Assert.AreEqual(((TextMessage)message).Text, "Dies ist eine Testnachricht. äöü");
        }
Example #20
0
        /// <summary>
        /// Encrypt an image message and send it to the given recipient.
        /// </summary>
        /// <param name="threemaId">threemaId target Threema ID</param>
        /// <param name="imageFilePath">path to read image data from</param>
        /// <returns>generated message ID</returns>
        public string SendImageMessage(string threemaId, string imageFilePath)
        {
            //fetch public key
            byte[] publicKey = this.apiConnector.LookupKey(threemaId);

            if (publicKey == null)
            {
                throw new InvalidKeyException("invalid threema id");
            }

            //check capability of a key
            CapabilityResult capabilityResult = this.apiConnector.LookupKeyCapability(threemaId);

            if (capabilityResult == null || !capabilityResult.CanImage)
            {
                throw new NotAllowedException();
            }

            byte[] fileData = File.ReadAllBytes(imageFilePath);
            if (fileData == null)
            {
                throw new IOException("invalid file");
            }

            //encrypt the image
            EncryptResult encryptResult = CryptTool.Encrypt(fileData, this.privateKey, publicKey);

            //upload the image
            UploadResult uploadResult = apiConnector.UploadFile(encryptResult);

            if (!uploadResult.IsSuccess)
            {
                throw new IOException("could not upload file (upload response " + uploadResult.ResponseCode + ")");
            }

            //send it
            EncryptResult imageMessage = CryptTool.EncryptImageMessage(encryptResult, uploadResult, this.privateKey, publicKey);

            return(apiConnector.SendE2EMessage(
                       threemaId,
                       imageMessage.Nonce,
                       imageMessage.Result));
        }
Example #21
0
        private void DoSetUserName()
        {
//             if (string.IsNullOrEmpty(tbTaxKey.Password))
//             {
//                 MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PwdNotEmpty, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
//                 return;
//             }

            CryptTool.ErrorMsg = string.Empty;
            CryptTool.UserPin  = tbTaxKey.Password;
            CryptTool.getThisCert();

            if (string.IsNullOrEmpty(CryptTool.ErrorMsg))
            {
                tbRegNsrsbh.Text   = CryptTool.Nsrsbh;
                tbRegNsrmc.Text    = CryptTool.Nsrmc;
                tbTaxKey.IsEnabled = false;
            }
            else
            {
                MessageBoxEx.Show(this, CryptTool.ErrorMsg, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
            }
        }
Example #22
0
        private void DoSetUserName()
        {
            if (string.IsNullOrEmpty(pwd.Password))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PwdNotEmpty, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }

            CryptTool.ErrorMsg = string.Empty;
            CryptTool.UserPin  = pwd.Password;
            CryptTool.getThisCert();

            if (string.IsNullOrEmpty(CryptTool.ErrorMsg))
            {
                txtNsrsbh.Text  = CryptTool.Nsrsbh;
                txtNsrName.Text = CryptTool.Nsrmc;
                pwd.IsEnabled   = false;
            }
            else
            {
                MessageBoxEx.Show(this, CryptTool.ErrorMsg, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
            }
        }
Example #23
0
        /// <summary>
        /// Decrypt a Message and download the blobs of the Message (e.g. image or file)
        /// </summary>
        /// <param name="threemaId">Threema ID of the sender</param>
        /// <param name="messageId">Message ID</param>
        /// <param name="box">Encrypted box data of the file/image message</param>
        /// <param name="nonce">Nonce that was used for message encryption</param>
        /// <param name="outputFolder">Output folder for storing decrypted images/files</param>
        /// <returns>Result of message reception</returns>
        public ReceiveMessageResult ReceiveMessage(string threemaId, string messageId, byte[] box, byte[] nonce, string outputFolder)
        {
            //fetch public key
            byte[] publicKey = this.apiConnector.LookupKey(threemaId);

            if (publicKey == null)
            {
                throw new InvalidKeyException("invalid threema id");
            }

            ThreemaMessage message = CryptTool.DecryptMessage(box, this.privateKey, publicKey, nonce);

            if (message == null)
            {
                return(null);
            }

            ReceiveMessageResult result = new ReceiveMessageResult(messageId, message);

            if (message.GetType() == typeof(ImageMessage))
            {
                //download image
                ImageMessage imageMessage = (ImageMessage)message;
                byte[]       fileData     = this.apiConnector.DownloadFile(imageMessage.BlobId);

                if (fileData == null)
                {
                    throw new MessageParseException();
                }

                byte[]   decryptedFileContent = CryptTool.Decrypt(fileData, privateKey, publicKey, imageMessage.Nonce);
                FileInfo imageFile            = new FileInfo(outputFolder + "/" + messageId + ".jpg");

                using (FileStream stream = File.OpenWrite(imageFile.FullName))
                {
                    stream.Write(decryptedFileContent, 0, decryptedFileContent.Length);
                    stream.Close();
                }

                result.Files.Add(imageFile);
            }
            else if (message.GetType() == typeof(FileMessage))
            {
                //download file
                FileMessage fileMessage = (FileMessage)message;
                byte[]      fileData    = this.apiConnector.DownloadFile(fileMessage.BlobId);

                byte[]   decryptedFileData = CryptTool.DecryptFileData(fileData, fileMessage.EncryptionKey);
                FileInfo file = new FileInfo(outputFolder + "/" + messageId + "-" + fileMessage.FileName);

                using (FileStream stream = File.OpenWrite(file.FullName))
                {
                    stream.Write(decryptedFileData, 0, decryptedFileData.Length);
                    stream.Close();
                }

                result.Files.Add(file);

                if (fileMessage.ThumbnailBlobId != null)
                {
                    byte[] thumbnailData = this.apiConnector.DownloadFile(fileMessage.ThumbnailBlobId);

                    byte[]   decryptedThumbnailData = CryptTool.DecryptFileThumbnailData(thumbnailData, fileMessage.EncryptionKey);
                    FileInfo thumbnailFile          = new FileInfo(outputFolder + "/" + messageId + "-thumbnail.jpg");
                    using (FileStream stream = File.OpenWrite(thumbnailFile.FullName))
                    {
                        stream.Write(decryptedThumbnailData, 0, decryptedThumbnailData.Length);
                        stream.Close();
                    }

                    result.Files.Add(thumbnailFile);
                }
            }

            return(result);
        }
Example #24
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (GlobalInfo.DeviceType == DeviceType.JSP.GetHashCode())
            {
                if (string.IsNullOrEmpty(tbloginNsrsbh.Text))
                {
                    MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PromptInputNsrsbh, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                    return;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(cbxSkpLoginNsrsbh.Text))
                {
                    MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PromptInputNsrsbh, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                    return;
                }
            }


            if (string.IsNullOrEmpty(loginPwd.Password))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PromptInputPwd, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(taxKey.Password))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PromptInputKey, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }

            CryptTool.UserPin = taxKey.Password;
            var ret = CryptTool.openThisDevice();

            if (ret != 0)
            {
                string msg = CryptTool.ErrorMsg;
                if (msg.Contains("0xA7"))
                {
                    msg = PRO_ReceiptsInvMgr.Resources.Message.NotFindTax;
                }
                MessageBoxEx.Show(this, msg, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }

            string errorMsg = string.Empty;
            string nsrsbh   = GlobalInfo.DeviceType == DeviceType.JSP.GetHashCode() ? tbloginNsrsbh.Text : cbxSkpLoginNsrsbh.Text.ToString();

            //登陆时取token   20190324
//             int retryCount = 3;
//             do
//             {
//                 --retryCount;
//                 GlobalInfo.token = GetTokenHelper.GetToken_dll(nsrsbh, CryptTool.UserPin, GlobalInfo.Dqdm);
//             } while (GlobalInfo.token.Length == 0 && retryCount > 0);

            var retObj = loginService.Login(nsrsbh, loginPwd.Password, GlobalInfo.token, out errorMsg);

            if (retObj == null)
            {
                MessageBoxEx.Show(this, errorMsg, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            else
            {
                GlobalInfo.NSRSBH      = nsrsbh;
                GlobalInfo.Dqdm        = retObj.areaId;
                GlobalInfo.AppId       = retObj.appKey;
                GlobalInfo.ExpiredTime = retObj.expiredTime;
                GlobalInfo.JxPwd       = taxKey.Password;

                ConfigObject configObject = new ConfigObject();
                configObject.NSRSBH   = nsrsbh;
                configObject.LoginPwd = loginPwd.Password;
                configObject.CertPwd  = taxKey.Password;
                configObject.TaxType  = GlobalInfo.DeviceType;

                if (chbRemember.IsChecked.HasValue)
                {
                    configObject.IsRemember = chbRemember.IsChecked.Value;
                    loginService.UpdateOrSaveUserInfo(configObject);
                }


                MainWindow win = new MainWindow();
                this.Close();
                win.Show();
                LoginWinInstance = null;
            }
        }
Example #25
0
        public MainWindow(Dictionary <string, string> args)
        {
            InitializeComponent();

            //Set Client ID
            string rawID = $"{Environment.MachineName}-{Environment.UserName}-Miner Tracker-Client";

            CLIENT_ID = CryptTool.Encrypt(rawID);

            //Set SystemTray Icon
            systemTrayIcon         = new NotifyIcon();
            systemTrayIcon.Icon    = new Icon(SYSTEM_TRAY_ICON);
            systemTrayIcon.Visible = true;
            systemTrayIcon.Text    = ToolTipsText;
            this.Hide();
            systemTrayIcon.DoubleClick +=
                delegate(object callBack, EventArgs mouseEvent)
            {
                this.Show();
                this.WindowState = WindowState.Normal;
                this.Activate();
            };
            systemTrayIcon.BalloonTipClosed += (sender, e) => { var thisIcon = (NotifyIcon)sender; thisIcon.Visible = false; thisIcon.Dispose(); };
            System.Windows.Forms.ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
            PCIDContextMenu         = contextMenu.MenuItems.Add("Checking PCID...");
            PCIDContextMenu.Enabled = false;
            GPUContextMenu          = contextMenu.MenuItems.Add("GPU List");
            GPUContextMenu.Enabled  = false;
            contextMenu.MenuItems.Add("View Log", (s, e) =>
            {
                try
                {
                    Process.Start("notepad.exe", Path.Combine(ServiceConfig.LogPath, EventLogger.GetLogFileName()));
                }
                catch (Exception ex)
                {
                    ShowErrorDialog("Unable to open log", ex.ToString());
                    EventLogger.WriteLog("OPEN LOG ERROR", ex.ToString());
                }
            });
            contextMenu.MenuItems.Add("Change PC ID", (s, e) =>
            {
                OpenSettingContextMenu();
            });

            contextMenu.MenuItems.Add("Restore", (s, e) =>
            {
                this.Show();
                this.WindowState = WindowState.Normal;
                this.Activate();
            });
            contextMenu.MenuItems.Add("Exit", (s, e) =>
            {
                System.Windows.Application.Current.Shutdown();
            });

            systemTrayIcon.ContextMenu = contextMenu;
            //Get version
            var currentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            FooterVersionTextBlock.Text = $"Version: {currentVersion}";
            var createdTime = AssemblyInformationManager.GetCreatedTime(@"C:\Program Files\Miner Tracker\Miner Tracker Desktop.exe");

            AboutVersionTextBlock.Text = $"Version {currentVersion} -Released {createdTime.Month}/{createdTime.Year}";

            //Get config
            var serviceConfigReader = new ConfigurationReader();

            ServiceConfig = serviceConfigReader.GetServiceConfig();
            //If can not get service config, then show error and shutdown
            if (!ClassUtils.CheckNull(ServiceConfig))
            {
                EventLogger.WriteLog("CLIENT READ SERVICE CONFIG ERROR", "Null retrieved config");
                ShowErrorDialog("File system error", "Unable to retrieve service configuration");
                System.Windows.Application.Current.Shutdown();
            }

            var userConfigReader = new ConfigurationReader(isService: false, userConfigPath: ServiceConfig.UserConfigPath, userConfigFile: ServiceConfig.UserConfigFileName);

            UserConfig = userConfigReader.GetUserConfig();
            var CurrentUserConfig = UserConfig;

            //Service config is okay but can not retrieve the user.config

            if (!ClassUtils.CheckNull(UserConfig))
            {
                ShowErrorDialog("File system error", "Unable to retrieve client configuration. Options have been set to default.");
                UserConfig = new UserConfiguration
                {
                    ID                 = CurrentUserConfig == null || CurrentUserConfig.ID == 0 ? ServiceConfig.UserID : CurrentUserConfig.ID,
                    LogPath            = CurrentUserConfig == null || CurrentUserConfig.LogPath == null ? ServiceConfig.UserLogPath : CurrentUserConfig.LogPath,
                    OpenOnStartup      = CurrentUserConfig == null || CurrentUserConfig.OpenOnStartup == null ? ServiceConfig.UserOpenOnStartup : CurrentUserConfig.OpenOnStartup,
                    CheckInterval      = CurrentUserConfig == null || CurrentUserConfig.CheckInterval == null ? ServiceConfig.UserCheckInterval : CurrentUserConfig.CheckInterval,
                    MinimizedWhenClose = CurrentUserConfig == null || CurrentUserConfig.MinimizedWhenClose == null ? ServiceConfig.UserMinimizedWhenClose : CurrentUserConfig.MinimizedWhenClose,
                    PCID               = CurrentUserConfig == null || CurrentUserConfig.PCID == null ? ServiceConfig.UserPCID : CurrentUserConfig.PCID,
                    PreviousPCID       = CurrentUserConfig == null || CurrentUserConfig.PreviousPCID == null ? ServiceConfig.UserPCID : CurrentUserConfig.PreviousPCID
                };
                SaveUserConfig();
            }
            // Since here, can use UserConfig
            SetupComputerSection();
            SetupConfigSection();
            SetupOptionSection();
            try
            {
                CheckTimer          = new System.Timers.Timer();
                CheckTimer.Elapsed += new ElapsedEventHandler(OnTimer);
                CheckTimer.Interval = 10;
                CheckTimer.Start();
            }
            catch (Exception ex)
            {
                EventLogger.WriteLog("TIMER ERROR", ex.ToString(), UserConfig.LogPath);
                EventLogger.WriteLog("", "Exiting....", UserConfig.LogPath);
                return;
            }

            if (args.TryGetValue("--minimized", out string value))
            {
                if (value.Equals("true"))
                {
                    //this.Hide();
                }
            }
        }
Example #26
0
 /// <summary>
 /// Wrapper to hash email <see cref="Threema.MsgApi.CryptTool.HashEmail"/>
 /// </summary>
 /// <param name="email">Email adress</param>
 /// <returns>Hash of email adress as hex-string</returns>
 public string HashEmail(string email)
 {
     byte[] emailHash = CryptTool.HashEmail(email);
     return(DataUtils.ByteArrayToHexString(emailHash));
 }
 protected override void Execute()
 {
     byte[] emailHash = CryptTool.HashEmail(this.emailField.Value);
     System.Console.WriteLine(DataUtils.ByteArrayToHexString(emailHash));
 }
Example #28
0
 /// <summary>
 /// Wrapper to hash email <see cref="Threema.MsgApi.CryptTool.HashPhoneNo"/>
 /// </summary>
 /// <param name="phoneNo">Phone number</param>
 /// <returns>Hash of phone number as hex-string</returns>
 public string HashPhoneNo(string phoneNo)
 {
     byte[] phoneHash = CryptTool.HashPhoneNo(phoneNo);
     return(DataUtils.ByteArrayToHexString(phoneHash));
 }
Example #29
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(pwd.Password))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PwdNotEmpty, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            var deviceId = BoxInfoHelper.GetDeviceNo();

            if (string.IsNullOrEmpty(deviceId))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.GetDeviceNoError, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            var    isSuccess    = false;
            string getDqdmError = string.Empty;

            this.Dispatcher.Invoke(new Action(() =>
            {
                WaitingBox.Show(() =>
                {
                    string netLocation = service.GetNetLocation(GlobalInfo.Dqdm);

                    if (!string.IsNullOrEmpty(netLocation))
                    {
                        CryptTool.LoginUrl = netLocation + ConfigHelper.GetAppSettingValue("JXLoginUri");
                        CryptTool.QueryUrl = netLocation + ConfigHelper.GetAppSettingValue("JXQueryUri");
                    }

                    if (!string.IsNullOrEmpty(getDqdmError))
                    {
                        return;
                    }

                    var loop = 0;
                    while ((loop < 5 && !string.IsNullOrEmpty(CryptTool.ErrorMsg) && CryptTool.ErrorMsg.Contains(PRO_ReceiptsInvMgr.Resources.Message.JXCertError)) || loop == 0)
                    {
                        isSuccess        = CryptTool.Login(pwd.Password);
                        GlobalInfo.NSRMC = CryptTool.Nsrmc;

                        loop++;
                        if (isSuccess)
                        {
                            break;
                        }
                    }
                }, PRO_ReceiptsInvMgr.Resources.Message.loginWait);
            }));

            if (!string.IsNullOrEmpty(getDqdmError))
            {
                MessageBoxEx.Show(this, getDqdmError, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            else
            {
                Logging.Log4NetHelper.Info(this, "地区代码:" + GlobalInfo.Dqdm);
            }

            if (!isSuccess)
            {
                MessageBoxEx.Show(this, CryptTool.ErrorMsg, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
            }
            else
            {
                GlobalInfo.JxPwd = pwd.Password;
                GlobalInfo.token = CryptTool.Token;

                JXManager win = new JXManager();
                win.Show();

                isBack = false;
                this.Close();
            }
        }
Example #30
0
        /// <summary>
        /// Encrypt a file message and send it to the given recipient.
        /// The thumbnailMessagePath can be null.
        /// </summary>
        /// <param name="threemaId">target Threema ID</param>
        /// <param name="fileMessageFile">the file to be sent</param>
        /// <param name="thumbnailMessageFile">file for thumbnail; if not set, no thumbnail will be sent</param>
        /// <returns>generated message ID</returns>
        public string SendFileMessage(string threemaId, FileInfo fileMessageFile, FileInfo thumbnailMessageFile)
        {
            //fetch public key
            byte[] publicKey = this.apiConnector.LookupKey(threemaId);

            if (publicKey == null)
            {
                throw new InvalidKeyException("invalid threema id");
            }

            //check capability of a key
            CapabilityResult capabilityResult = this.apiConnector.LookupKeyCapability(threemaId);

            if (capabilityResult == null || !capabilityResult.CanImage)
            {
                throw new NotAllowedException();
            }

            if (fileMessageFile == null)
            {
                throw new ArgumentException("fileMessageFile must not be null.");
            }

            if (!fileMessageFile.Exists)
            {
                throw new FileNotFoundException(fileMessageFile.FullName);
            }

            byte[] fileData;
            using (Stream stream = File.OpenRead(fileMessageFile.FullName))
            {
                fileData = new byte[stream.Length];
                stream.Read(fileData, 0, (int)stream.Length);
                stream.Close();
            }

            if (fileData == null)
            {
                throw new IOException("invalid file");
            }

            //encrypt the image
            EncryptResult encryptResult = CryptTool.EncryptFileData(fileData);

            //upload the image
            UploadResult uploadResult = apiConnector.UploadFile(encryptResult);

            if (!uploadResult.IsSuccess)
            {
                throw new IOException("could not upload file (upload response " + uploadResult.ResponseCode + ")");
            }

            UploadResult uploadResultThumbnail = null;

            if (thumbnailMessageFile != null && thumbnailMessageFile.Exists)
            {
                byte[] thumbnailData;
                using (Stream stream = File.OpenRead(thumbnailMessageFile.FullName))
                {
                    thumbnailData = new byte[stream.Length];
                    stream.Read(thumbnailData, 0, (int)stream.Length);
                    stream.Close();
                }

                if (thumbnailData == null)
                {
                    throw new IOException("invalid thumbnail file");
                }

                //encrypt the thumbnail
                EncryptResult encryptResultThumbnail = CryptTool.encryptFileThumbnailData(fileData, encryptResult.Secret);

                //upload the thumbnail
                uploadResultThumbnail = this.apiConnector.UploadFile(encryptResultThumbnail);
            }

            //send it
            EncryptResult fileMessage = CryptTool.EncryptFileMessage(
                encryptResult,
                uploadResult,
                GetMIMEType(fileMessageFile),
                fileMessageFile.Name,
                (int)fileMessageFile.Length,
                uploadResultThumbnail,
                privateKey, publicKey);

            return(this.apiConnector.SendE2EMessage(
                       threemaId,
                       fileMessage.Nonce,
                       fileMessage.Result));
        }