Retrieve public key by providing KeyID for encryption - c#

Can I retrieve public key by providing keyID.( I have imported the public key using kleopatra)
Note:
I am currently passing the public key file path to encrypt the stream.I am successfully encrypting the stream without any issues using BountyCastle nuget package.
I have tried this:
PgpPublicKeyRingBundle bun = new PgpPublicKeyRingBundle(new byte[200]);
var publicc = bun.GetPublicKey(long.Parse("12ERTY564"));
Update:
The above is test KeyID.

Related

Extracting PDB signature from DLL file

I have to extract PDB signature from both .pdb and .dll file.
That's the code I use to extract it from .pdb file. Unfortunately I haven't found similiar way of extracting it from a DLL.
public static string GetPdbSignature(string pdbFilePath)
{
using (var pdbFileStream = File.OpenRead(pdbFilePath))
{
var metadataProvider = MetadataReaderProvider.FromPortablePdbStream(pdbFileStream);
var metadataReader = metadataProvider.GetMetadataReader();
var id = new BlobContentId(metadataReader.DebugMetadataHeader.Id);
return $"{id.Guid.ToString("N")}ffffff";
}
}
I found out that a PeNet nuget package can be used to perform the extraction, yet I'd prefer to achieve that without installing external dependancies.
Also, I managed to find the desired data using a dotPeek (screen), but as I need to resolve the problem programatically it doesn't solve my issue either.
I'd apreciate any hint how to aproach that problem. Either by using some built in dotnet mechanism or by some smart low level byte extraction.
I managed to find an official Microsoft's package - Microsoft.Diagnostics.Tracing.TraceEvent that contains PEFile class allowing to extract the exact data I need.
public static string GetDllSignature(string dllFilePath)
{
var peFile = new PEFile.PEFile(dllFilePath);
peFile.GetPdbSignature(out string pdbName, out Guid pdbGuid, out int pdbAge);
return $"{pdbGuid.ToString("N")}ffffff";
}
UPDATE:
Actually there also is a PEReader class in System.Reflection.PortableExecutable namespace that makes the reading possible using only the system libraries. However it requires some knowledge of the portable executable format, as the PEReader does not provide an explicit, user-friendly method for extracting the signature, instead it just allows getting all kind of data that the PE file contains.
public static string GetDllSignatureV2(string dllFilePath)
{
using (var pdbStream = File.OpenRead(pdbPath))
using (var peReader = new PEReader(pdbStream))
{
var debugDirectory = peReader.ReadDebugDirectory().First(entry => entry.Type == DebugDirectoryEntryType.CodeView);
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(debugDirectory);
return $"{codeViewData.Guid.ToString("N").Replace("-", string.Empty)}FFFFFFFF".ToUpper();
}
}

Vs.Net C# Azure flle storage fails to add File for existing File Share

VS.NET C# fails to create file on Azure File Storage for Existing File share
I'm using Microsoft.WindowsAzure.Storage lib to access Azure File Storage API. My method creates File Share and uploads file. It works when File Share is created, but skips file upload when File Share exists.
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
public void SaveText( string fileName )
{
string accountName = "mylogs";
string key = #"dvjdjhsvdjfhvsjhdvfjhsvdfjhC2g==";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var share = storageAccount.CreateCloudFileClient().GetShareReference("test");
share.CreateIfNotExistsAsync().Wait();
var root = share.GetRootDirectoryReference();
root.GetFileReference(fileName).UploadTextAsync("mytext").Wait();
}
First SaveText(file1) call works fine, Share & "file1" got created.
Second SaveText(file2) call, no errors, no "file2" created.
Same user, same app.
I'm using the nuget package WindowsAzure.Storage, version 9.3.3, and with a console project(not .net core), it works fine.
Sample code as blow(just use yours):
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
namespace AzureFileTest
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.SaveText("file1"); //in the first call, file1 created and text uploads.
p.SaveText("file2"); //in the second call, file2 created and text uploads.
Console.WriteLine("done now");
Console.ReadLine();
}
public void SaveText(string fileName)
{
string accountName = "xxxxx";
string key = "xxxxxx";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var share = storageAccount.CreateCloudFileClient().GetShareReference("test");
share.CreateIfNotExistsAsync().Wait();
var root = share.GetRootDirectoryReference();
root.GetFileReference(fileName).UploadTextAsync("mytext").Wait();
}
}
}
Please let me know if any more issues, or any difference between the codes.

Get Sha256 public key from certificate

Currently, am working on client server application(Chat) am implementing security for server and clients, few of the client is written in java SMACK library, they are using TLS Pining for JAVA it needs sha2 hash [https://github.com/Flowdalic/java-pinning][1]
Server is implemented using C#, I have certificate on server side how can I get the sha2 public key with below format from the certificate, below is my code.
cer =new X509Certificate2(ConfigurationManager.AppSettings["CertificateName"],"123456");
string hellow= cer.GetCertHashString(); //it will return sha1 hash
what I need is the below format and sha2-256 key from the certificate
SHA2-256 key
83:F9:17:1E:06:A3:13:11:88:89:F7:D7:93:02:BD:1B:7A:20:42:EE:0C:FD:02:9A:BF:8D:D0:6F:FA:6C:D9:D3
I have found the solution for my question, let me share.
If you want to get certificate's SHA256 thumbprint, you have to do some manual work. Built-in Thumbprint property is SHA1 only.
Yo have to use a SHA256 class and compute hash over certificate's content:
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace MyNamespace {
class MyClass {
public static String GetSha2Thumbprint(X509Certificate2 cert) {
Byte[] hashBytes;
using (var hasher = new SHA256Managed()) {
hashBytes = hasher.ComputeHash(cert.RawData);
}
return BitConverter.ToString(hashBytes).Replace("-", ":");
}
}
}

'PrivateKey' does not have a definition for 'CreateFromFile'

I am trying to implement a solution into my application that mirrors the answer in this post
I have a similar scenario where I have an HttpListener and Grapevine based application running on an Ubuntu server that I need to get working with HTTPS using Mono and I am trying to create and include the relevant keys to allow HTTPS
The problem I am having is the last line of the solution,
key = PrivateKey.CreateFromFile (pvk_file).RSA;
When I try the same Visual Studio shows an error/text highlighted red, 'PrivateKey' does not have a definition for 'CreateFromFile'
Am I using the wrong libraries or is something else the issue with my code itself?
My code, cut down to the relevant method.
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using java.security;
public class ConfigureCertificates
{
private readonly string _dirName;
private readonly string _path;
private readonly string _port;
private readonly string _certFile;
public ConfigureCertificates(string port)
{
_dirName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
_path = Path.Combine(_dirName, ".mono");
_path = Path.Combine(_path, "httplistener");
_port = port;
_certFile = Path.Combine(_path, String.Format("{0}.cer", _port));
}
public void SetUpCerts()
{
if (!File.Exists(_certFile))
throw new Exception("Certificate file not found");
string pvkFile = Path.Combine(_path, String.Format("{0}.pvk", _port));
if (!File.Exists(pvkFile))
throw new Exception("Private key not found");
var cert = new X509Certificate2(_certFile);
var key = PrivateKey.CreateFromFile(pvkFile).RSA; // Error occurs here
}
}
You have a naming clash - in other words there is another class called PrivateKey that doesn't have the method you require. A quick Google hunt indicates the correct class is in the Mono.Security.Authenticode namespace. So you will need to reference the full path:
Mono.Security.Authenticode.PrivateKey.CreateFromFile(...)
You may also need to add the Mono.Security package if you don't already have it.

Application level Encryption

I had tried to encrypt the web config, using different ProtectionProviders but these methods will not full-fill the security.As i can decrypt the file easily from another application:
The Method i used for encryption:
public void EncryptConnString()
{
Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection(section);
if (confStrSect != null)
{
confStrSect.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
confStrSect.SectionInformation.ForceSave = true;
confg.Save(ConfigurationSaveMode.Full);
}
}
If i copied the encrypted appSettings to another application and call the method for decryption. this will give the original data, If i attach the encrypted config file with any other application and call the method for decryption, it will get easily decrypted.
That means; If anyone can access the config file can easily get the
values, through decryption.
So here my question is that; How can i encrypt the web.config with a password? or else provide an application level encryption(restrict other application to decrypt the file).
The method used for decryption:
public void DecryptConnString()
{
Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection(section);
if (confStrSect != null)
{
confStrSect.SectionInformation.UnprotectSection();
confStrSect.SectionInformation.ForceSave = true;
confg.Save(ConfigurationSaveMode.Full);
}
}
I had tried with the following ProtectionProviders:
MyUserDataProtectionConfigurationProvider
DataProtectionConfigurationProvider
RSAProtectedConfigurationProvider
Note: I have to do this programmatically so that aspnet_regiis will not help me

Categories

Resources