Skip to content

Commit

Permalink
Init upload
Browse files Browse the repository at this point in the history
  • Loading branch information
sbidy authored Jun 26, 2017
1 parent 54e0262 commit ee53828
Show file tree
Hide file tree
Showing 21 changed files with 1,545 additions and 0 deletions.
28 changes: 28 additions & 0 deletions KeyManagerUI.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KeyManagerUI", "KeyManagerUI\KeyManagerUI.csproj", "{20ADD178-ADF3-4589-AD7B-EE38E02E861D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KeePassKeyManager", "..\KeePassKeyManager\KeePassKeyManager\KeePassKeyManager.csproj", "{709F0DBB-5776-408B-9D0C-D03875084F1A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{20ADD178-ADF3-4589-AD7B-EE38E02E861D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{20ADD178-ADF3-4589-AD7B-EE38E02E861D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{20ADD178-ADF3-4589-AD7B-EE38E02E861D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{20ADD178-ADF3-4589-AD7B-EE38E02E861D}.Release|Any CPU.Build.0 = Release|Any CPU
{709F0DBB-5776-408B-9D0C-D03875084F1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{709F0DBB-5776-408B-9D0C-D03875084F1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{709F0DBB-5776-408B-9D0C-D03875084F1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{709F0DBB-5776-408B-9D0C-D03875084F1A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
256 changes: 256 additions & 0 deletions KeyManagerUI/Certmanager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Windows.Forms;

namespace KeyManagerUI
{
class Certmanager
{
public X509Certificate2Collection applied_certs;
private HashSet<string> _not_applied_certs = new HashSet<string>();
public HashSet<string> not_applied_certs
{
get { return _not_applied_certs; }
}
public Certmanager ()
{
applied_certs = new X509Certificate2Collection();
}

/// <summary>
/// Encrypt data for the specified set of certificates.
/// Adapted from http://msdn.microsoft.com/en-us/library/bb924547.aspx
/// </summary>
/// <param name="msg">Data to encrypt</param>
/// <param name="recipientCerts">Certificates to encrypt for</param>
/// <returns>Encrypted blob</returns>
public byte[] EncryptMsg(Byte[] msg, X509Certificate2Collection recipientCerts)
{
// Place the message in a ContentInfo object.
// This is required to build an EnvelopedCms object.
ContentInfo contentInfo = new ContentInfo(msg);

recipientCerts = checkCerts(recipientCerts);

// Instantiate an EnvelopedCms object with the ContentInfo
// above.
// Has default SubjectIdentifierType IssuerAndSerialNumber.
// Has default ContentEncryptionAlgorithm property value
// RSA_DES_EDE3_CBC.
EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);

// Formulate a CmsRecipient object collection that
// represent information about the recipients
// to encrypt the message for.
if (recipientCerts.Count > 0)
{
CmsRecipientCollection recips = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, recipientCerts);

// Encrypt the message for the recipient.
envelopedCms.Encrypt(recips);

// The encoded EnvelopedCms message contains the message
// ciphertext and the information about each recipient
// that the message was enveloped for.
return envelopedCms.Encode();
}
return null;
}
/// <summary>
/// Decrypt a message using a private key available on the system.
/// </summary>
/// <param name="encodedEnvelopedCms">Encrypted blob</param>
/// <returns>Decrypted data, or null if there was an error</returns>
public byte[] DecryptMsg(byte[] encodedEnvelopedCms)
{
// Prepare object in which to decode and decrypt.
EnvelopedCms envelopedCms = new EnvelopedCms();

// Decode the message.
envelopedCms.Decode(encodedEnvelopedCms);

X509Store myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
myStore.Open(OpenFlags.ReadOnly);
envelopedCms.Decrypt(myStore.Certificates);
myStore.Close();

// The decrypted message occupies the ContentInfo property
// after the Decrypt method is invoked.
return envelopedCms.ContentInfo.Content;
}

public void getRecipient(byte[] encodedEnvelopedCms)
{
_not_applied_certs = new HashSet<string>();
// Prepare object in which to decode and decrypt.
EnvelopedCms envelopedCms = new EnvelopedCms();
// Decode the message.
envelopedCms.Decode(encodedEnvelopedCms);

RecipientInfoCollection recips = envelopedCms.RecipientInfos;

foreach (RecipientInfo info in recips)
{
X509IssuerSerial serial = (X509IssuerSerial)info.RecipientIdentifier.Value;
X509Certificate2Collection found_certs = FindCerts(serial.SerialNumber.ToString());

if (found_certs.Count == 0)
_not_applied_certs.Add(serial.SerialNumber.ToString());

applied_certs.AddRange(found_certs);
}
applied_certs = removeDuplicates(applied_certs);
}
/// <summary>
/// Search for certificates in the local cert stores
/// </summary>
/// <param name="serialNumber">The certificate serial number</param>
/// <returns>A collection of X509 certificates</returns>
public X509Certificate2Collection FindCerts(string serialNumber)
{
X509Store addrBookStore = new X509Store(StoreName.AddressBook, StoreLocation.CurrentUser);
addrBookStore.Open(OpenFlags.ReadOnly);

X509Store myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
myStore.Open(OpenFlags.ReadOnly);

X509Certificate2Collection allCerts = addrBookStore.Certificates;
allCerts.AddRange(myStore.Certificates);

addrBookStore.Close();
myStore.Close();

var matchingCertificates = allCerts.Find(X509FindType.FindBySerialNumber, serialNumber, true);

return matchingCertificates;
}
/// <summary>
/// Deletes the duplicates entry's in a X509Certifacte2Collection
/// </summary>
/// <param name="source">The input collection</param>
/// <returns>Output collection without duplicates</returns>
private X509Certificate2Collection removeDuplicates(X509Certificate2Collection source)
{
X509Certificate2Collection output = new X509Certificate2Collection();
HashSet<string> serials = new HashSet<string>();

foreach (X509Certificate2 cert in source)
{
serials.Add(cert.SerialNumber);
}

foreach (string sn in serials)
{
foreach (X509Certificate2 cert in source)
{
if (cert.SerialNumber == sn && (output.Contains(cert) == false))
{
output.Add(cert);
}
}
}
return output;
}
/// <summary>
/// Shows the certificate UI and adds the selected certificates to the applied cert collection
/// </summary>
public void addFromStore()
{
X509Store addrBookStore = new X509Store(StoreName.AddressBook, StoreLocation.CurrentUser);
addrBookStore.Open(OpenFlags.ReadOnly);

X509Store myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
myStore.Open(OpenFlags.ReadOnly);

X509Certificate2Collection allCerts = addrBookStore.Certificates;
allCerts.AddRange(myStore.Certificates);

addrBookStore.Close();
myStore.Close();

X509Certificate2Collection fcollection = allCerts.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
fcollection = fcollection.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.KeyEncipherment, false);
X509Certificate2Collection store_certs = X509Certificate2UI.SelectFromCollection(fcollection, "SelectEncCert", "SelectEncCertLong", X509SelectionFlag.MultiSelection);

applied_certs.AddRange(store_certs);
}
/// <summary>
/// Checks the certificate for revocation and validity --- DEPRECATED: NOT USED ????!!!!
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private X509Certificate2Collection checkCerts(X509Certificate2Collection certs_to_check)
{
X509Certificate2Collection scollection = new X509Certificate2Collection();
scollection.AddRange(certs_to_check);

if (scollection == null || scollection.Count < 1)
{
return null;
}

// validate certificates
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;

X509Certificate2Collection toRemove = new X509Certificate2Collection();
foreach (X509Certificate2 cert in scollection)
{
bool chainRc = false;
chainRc = chain.Build(cert);

if (!chainRc)
{
// certificate is invalid ... keep it?
StringBuilder reason = new StringBuilder();
for (int index = 0; index < chain.ChainStatus.Length; index++)
{
reason.AppendLine(chain.ChainStatus[index].StatusInformation);
}
DialogResult decision = MessageBox.Show("Certificate:\n"+cert.SubjectName.Name+"\n\ncan't validated - add anyway?\nReasons:"+reason, "Error",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button3);
if (decision == DialogResult.Cancel)
{
return null;
}
if (decision == DialogResult.No)
{
toRemove.Insert(0, cert);
}
}
scollection = removeDuplicates(scollection);
}

foreach (X509Certificate2 cert in toRemove)
{
scollection.Remove(cert);
}

if (scollection.Count < 1)
{
return null;
}

return scollection;
}
/// <summary>
/// Checks if one of the pub keys are matched to a user private key
/// </summary>
/// <param name="collection"></param>
/// <returns>Returns true if a pub-priv key match exists</returns>
public bool checkIfPrivKeyExists(X509Certificate2Collection collection)
{
bool havePrivateKey = false;
foreach (X509Certificate2 cert in collection)
{
havePrivateKey |= cert.HasPrivateKey;
}
return havePrivateKey;
}
}
}
83 changes: 83 additions & 0 deletions KeyManagerUI/KeyManagerUI.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{20ADD178-ADF3-4589-AD7B-EE38E02E861D}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KeyManagerUI</RootNamespace>
<AssemblyName>KeyManagerUI</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>false</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="KeePass">
<HintPath>..\..\..\..\..\..\..\Program Files (x86)\KeePass Password Safe 2\KeePass.exe</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Security" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Certmanager.cs" />
<Compile Include="KeyManagerUIClass.cs" />
<Compile Include="KeyManagerUIForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="KeyManagerUIForm.Designer.cs">
<DependentUpon>KeyManagerUIForm.cs</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="KeyManagerUIForm.resx">
<DependentUpon>KeyManagerUIForm.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
Loading

0 comments on commit ee53828

Please sign in to comment.