In C#, how do I get the verified publisher of a signed .exe file? I am working on a program blocking application, and would like to be able to detect the publisher, if any, of a program.
I think you can use
X509Certificate.CreateFromSignedFile()
If you pass name of the .exe or .msi or any signed file to this method, it will create a X509Certificate object. You can then use GetName() method to get certification publisher information. Below code should get you started if you have not discovered it already.
using System;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApplication1
{
public class ConsoleApplication1
{
[STAThread]
static void Main(string[] args)
{
X509Certificate xcert = null;
try
{
xcert = X509Certificate.CreateFromSignedFile(args[0]);
Console.WriteLine(args[0] + "\t" + xcert.GetName() + "\t" + xcert.GetPublicKeyString());
}
catch (Exception e) { Console.WriteLine(args[0] + ": Unable to readDER-encoded signature."); }
}
}
}
Related
My requirement is the following:
I have various bits of network hardware, from which we regularly export configurations (this is done using another c#/.NET app I created, this works really well - the tool logs in via SSH to the various devices and downloads the latest configuration to the local hard disk of the server from which the app runs).
We have various SharePoint online sites (provided via our M365 subscription).
I want to have these configs uploaded to a particular folder, in a particular document library, in a particular SharePoint Online site, basically so that there is an off-site backup of the config files.
I was following the steps in this blog: https://daoudisamir.com/from-c-to-sharepoint-file-upload-using-csom-with-subfolders-structure/.
It looked like it did what I wanted... but when I try to build the code, it tells me that I'm missing references to assemblies etc. I know that this means that I'm missing "using" directives, but I've tried all sorts of variations to reference the various NUGET packages that are instructed to be installed, but I can't get this to work and couldn't see anywhere on the blog itself to email the owner.
Anyone got any ideas... at the moment, my code is more or less a copy/paste of what's on the blog page, but I've included my code here for convenience:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Security;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
namespace UploadToSharePoint_Net48
{
internal class Program
{
static void Main(string[] args)
{
string SiteUrl = "https://You.sharepoint.com/sites/Upload";
string DocumentLibrary = "UploadLibrary";
string FileName = #"C:\testupload.pdf";
string CustomerFolder = "1564_dsfgsst";
string UserName = "samir.daoudi#******.co.uk";
string Password = "*****";
UploadFileToSharePoint(SiteUrl, DocumentLibrary, CustomerFolder, FileName, UserName, Password);
}
private static void UploadFileToSharePoint(string SiteUrl, string DocLibrary, string ClientSubFolder, string FileName, string Login, string Password)
{
try
{
#region ConnectToSharePoint
var securePassword = new SecureString();
foreach (char c in Password)
{ securePassword.AppendChar(c); }
var onlineCredentials = new SP.SharePointOnlineCredentials(Login, securePassword);
#endregion
#region Insert the data
using (SP.ClientContext CContext = new SP.ClientContext(SiteUrl))
{
CContext.Credentials = onlineCredentials;
SP.Web web = CContext.Web;
SP.FileCreationInformation newFile = new SP.FileCreationInformation();
byte[] FileContent = System.IO.File.ReadAllBytes(FileName);
newFile.ContentStream = new MemoryStream(FileContent);
newFile.Url = Path.GetFileName(FileName);
SP.List DocumentLibrary = web.Lists.GetByTitle(DocLibrary);
//SP.Folder folder = DocumentLibrary.RootFolder.Folders.GetByUrl(ClientSubFolder);
SP.Folder Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder);
Clientfolder.Update();
SP.File uploadFile = Clientfolder.Files.Add(newFile);
CContext.Load(DocumentLibrary);
CContext.Load(uploadFile);
CContext.ExecuteQuery();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("The File has been uploaded" + Environment.NewLine + "FileUrl -->" + SiteUrl + "/" + DocLibrary + "/" + ClientSubFolder + "/" + Path.GetFileName(FileName));
}
#endregion
}
catch (Exception exp)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace);
}
finally
{
Console.ReadLine();
}
}
}
}
The errors are with all the references to SP.xxxxx
I can see that there is no definition for anything called "SP", but I'm assuming at this stage that this is in one of the external libraries or whatever is in the NUGETS that are required.
Any help gratefully received.
Thanks
Colin
We installed nuget titanium web proxy, created a window service and initiated titanium web proxy. The windows service works, runs, and start and stop times are written to a log file. But the web proxy is supposed to catch internet request and afford them, though no such events happens and nothing is logged, when i open some page with different browsers.
Here is our code:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Titanium.Web.Proxy;
using Titanium.Web.Proxy.EventArguments;
namespace WebProxy1 {
public partial class MyNewService : ServiceBase {
public ProxyServer proxyServer;
public MyNewService() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
proxyServer = new ProxyServer(true, true, true);
proxyServer.BeforeRequest += OnRequest;
proxyServer.Start();
WriteToFile("Service is started at " + DateTime.Now);
}
protected override void OnStop() {
proxyServer.Stop();
WriteToFile("Service is stopped at " + DateTime.Now);
}
public void WriteToFile(string Message) {
string path = "E:\\Downloads\\Logs";
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
string filepath = "E:\\Downloads\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath)) {
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath)) {
sw.WriteLine(Message);
}
} else {
using (StreamWriter sw = File.AppendText(filepath)) {
sw.WriteLine(Message);
}
}
}
public async Task OnRequest(object sender, SessionEventArgs e) {
WriteToFile(e.HttpClient.Request.Url);
// To cancel a request with a custom HTML content
// Filter URL
if (e.HttpClient.Request.Method.ToUpper() == "GET" && e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("google.com")) {
e.Ok("<!DOCTYPE html>" +
"<html><body><h1>" +
"Website Blocked" +
"</h1>" +
"<p>Blocked by titanium web proxy.</p>" +
"</body>" +
"</html>");
}
// Redirect example
if (e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org")) {
e.Redirect("https://www.paypal.com");
}
}
}
}
I think you did not set the titanium proxy properly.
Before starting the proxy, you have to set endpoint.
There is titanium proxy using example here.
This is my sample source.
var explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, 8000, true)
{
// Use self-issued generic certificate on all https requests
// Optimizes performance by not creating a certificate for each https-enabled domain
// Useful when certificate trust is not required by proxy clients
//GenericCertificate = new X509Certificate2(Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "genericcert.pfx"), "password")
};
// Fired when a CONNECT request is received
explicitEndPoint.BeforeTunnelConnect += OnBeforeTunnelConnect;
// An explicit endpoint is where the client knows about the existence of a proxy
// So client sends request in a proxy friendly manner
proxyServer.AddEndPoint(explicitEndPoint);
proxyServer.Start();
I am new to WebAPI ,I am trying to rename a folder within WebAPI itself.
for that I am using Directory.Move('source', 'destination');
source : D:\\Projects\\Dot Net\\ChurchAdmin\\ChurchAdmin\\api\\Images\\Announcements\\Church\\ComitteeMeetings
destination : D:\\Projects\\Dot Net\\ChurchAdmin\\ChurchAdmin\\api\\Images\\Announcements\\Church\\Meeting
When I debug this line Directory.Move('source', 'destination'); I got the error as follows ExceptionMessage: "Could not find a part of the path."
I tried in many ways I can't resolve this issue .Can anyone help me to fix this .
GetFullPath(String)
Returns the absolute path for the specified path string.
Check my tested Example on console application:-
Simple use Path.GetFullPath(yourRelativePath); thats it
#Panagiotis you are right
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string source_dir = "C:\\Users\\hitesh.anshani\\Documents\\visual studio 2017\\Projects\\ConsoleApp1\\ConsoleApp1\\hitesh";
string des_dir = "C:\\Users\\hitesh.anshani\\Documents\\visual studio 2017\\Projects\\ConsoleApp1\\ConsoleApp1\\hitesh1233";
var abc = Environment.CurrentDirectory;
Directory.Move(Path.GetFullPath(source_dir), Path.GetFullPath(des_dir));
}
}
}
Try this:
class Program
{
static void Main(string[] args)
{
string sourceDirectory = #"D:\Projects\Dot Net\ChurchAdmin\ChurchAdmin\api\Images\Announcements\Church\ComitteeMeetings"
string destinationDirectory = #"D:\Projects\Dot Net\ChurchAdmin\ChurchAdmin\api\Images\Announcements\Church\Meetings"
try
{
System.IO.Directory.Move(sourceDirectory, destinationDirectory);
}
catch (Exception eX)
{
Console.WriteLine(eX.Message);
}
}
}
I want to check if a certain feature is installed on a certain machine.
I have a powershell code that checks this, and now I want to check this from .net code.
I can see that in the cmdlet, the code checks if there is an invalid namespace error.
When searching the web, I found the following code:
ManagementClass myClass = new ManagementClass(scope, path, getOptions);
try
{
myClass.get();
}
catch (System.Management.Exception ex)
{
if (ex.ErrorCode == ManagementStatus.InvalidNamespace)
{
return true;
}
}
...
I want to clean this code a bit, so basically I have 2 questions:
Is there another way to check for an InvalidNamespace error? (The code I've copied was later used to invoke some method within myClass, so I wonder if I can somehow achieve my goal in a more direct way)
Do I really need the parameter getOptions?
To get all the wmi namespaces, you must first connect to the root namespace and then query for all the __NAMESPACE instances, and for each instance recursively repeat this process. about the getOptions parameter which is a ObjectGetOptions class is not necessary in this case, so can be null.
Check this code to get all the wmi namespaces (you can populate a list with that info and then check if the namespace exist in the machine)
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace MyConsoleApplication
{
class Program
{
static private void GetWmiNameSpaces(string root)
{
try
{
ManagementClass nsClass = new ManagementClass( new ManagementScope(root), new ManagementPath("__namespace"), null);
foreach (ManagementObject ns in nsClass.GetInstances())
{
string namespaceName = root + "\\" + ns["Name"].ToString();
Console.WriteLine(namespaceName);
//call the funcion recursively
GetWmiNameSpaces(namespaceName);
}
}
catch (ManagementException e)
{
Console.WriteLine(e.Message);
}
}
static void Main(string[] args)
{
//set the initial root to search
GetWmiNameSpaces("root");
Console.ReadKey();
}
}
}
Im trying to set the certificate friendly name during the certificate request/acceptance process. I understand that this a property of the microsoft store rather than the certificate and an wondering what .net/c# technique might be used to set it.
Use X509Certificate2.FriendlyName. However, you must export the certificate as PFX/PKCS#12:
X509Certificate2 certificate = new X509Certificate2(...);
certificate.FriendlyName = "MyName";
File.WriteAllBytes(path, certificate.Export(X509ContentType.Pkcs12));
So here is a commmand line example of how to do this. You need CAPICOM from microsoft which wraps the CryptoAPI.
The friendly name is a property of the cert store rather than the certificate so this code imports a certificate to the cert store and sets the friendly name as it does so.
The code takes two parameters the path to the cert file and the friendly name you wish to set.
Code:-
using System;
using System.Collections.Generic;
using System.Text;
using CAPICOM;
using System.Collections;
using System.Runtime.InteropServices;
namespace CertTool
{
class Program
{
const uint CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x20000;
const int CAPICOM_PROPID_FRIENDLY_NAME = 11;
const int CAPICOM_ENCODE_BINARY = 1;
static private String _currStoreName = "My";
static private String _FriendlyName = "Not Set";
static private String _CertPath = "C:\\test.cer";
static StoreClass _oCurrStore;
static ExtendedPropertyClass _friendlyProp;
static CertificateClass _certificate;
static ExtendedProperties _extendedProp;
static void Main(string[] args)
{
try
{
//Friendly name Argument
if (args.Length > 0)
{
_FriendlyName = args[0];
}
//Certpath argument
if (args.Length > 1)
{
_CertPath = args[1];
}
//Set and open the Store
_oCurrStore = new StoreClass();
_oCurrStore.Open(
CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE,
_currStoreName,
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
//Call the import certificate function
importCert();
}
catch(Exception ex){
Console.WriteLine(ex.Message);
Console.WriteLine(args[0]);
}
}
//Function import the certificate to the machine store and sets the friendly name
static bool importCert()
{
try
{
//Create Certificate Object
_certificate = new CertificateClass();
//Load the certificate into the obejct from file
_certificate.Load(_CertPath, "", CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_EXPORTABLE, CAPICOM_KEY_LOCATION.CAPICOM_LOCAL_MACHINE_KEY);
//Create extended property Class for friendly name
_friendlyProp = new ExtendedPropertyClass();
_friendlyProp.PropID = CAPICOM_PROPID.CAPICOM_PROPID_FRIENDLY_NAME;
_friendlyProp.set_Value(CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BINARY, _FriendlyName);
//Add extendedProp on cert object
_extendedProp = _certificate.ExtendedProperties();
//Set extendded prop to friendly name object
_extendedProp.Add(_friendlyProp);
_oCurrStore.Add(_certificate);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(_CertPath);
return true;
}
}
}
}
Ok, found an answer to that here:
Hi,
Please have a look at this to check if it suits your need:
When you run the .net Code in X64 Environment you will get the following error message.
" Failed --Retrieving the COM class factory for component with CLSID ...."
E.g. in CMS Export / Import server side .net code = "ExportSiteContentIncremental(...) Failed --Retrieving the COM class factory for component with CLSID {CA0752B3-021C-4F99-82E3-2C0F19C5E953} failed due to the following error: 80040154."
WORKAROUND:
The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)
ROOTCAUSE
The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.