public void WhenCreatingKeys_WithNoExport_ThenCreatesKeyContainer() { var containerName = $"{Guid.NewGuid()}"; Program.Main(new[] { WellKnownCommands.CREATE_KEYS, $"-{WellKnownCommandArguments.USERNAME}", _currentUser, $"-{WellKnownCommandArguments.CONTAINER_NAME}", containerName }); CspKeyContainerInfo info = new CspKeyContainerInfo(new CspParameters { KeyContainerName = containerName, Flags = CspProviderFlags.UseMachineKeyStore }); Assert.That(info.KeyContainerName, Is.EqualTo(containerName)); }
private static void showRSAProps(RSACryptoServiceProvider rsa) { Console.WriteLine("RSA CSP key information:"); CspKeyContainerInfo keyInfo = rsa.CspKeyContainerInfo; Console.WriteLine("Accessible property: " + keyInfo.Accessible); Console.WriteLine("Exportable property: " + keyInfo.Exportable); Console.WriteLine("HardwareDevice property: " + keyInfo.HardwareDevice); Console.WriteLine("KeyContainerName property: " + keyInfo.KeyContainerName); Console.WriteLine("KeyNumber property: " + keyInfo.KeyNumber.ToString()); Console.WriteLine("MachineKeyStore property: " + keyInfo.MachineKeyStore); Console.WriteLine("Protected property: " + keyInfo.Protected); Console.WriteLine("ProviderName property: " + keyInfo.ProviderName); Console.WriteLine("ProviderType property: " + keyInfo.ProviderType); Console.WriteLine("RandomlyGenerated property: " + keyInfo.RandomlyGenerated); Console.WriteLine("Removable property: " + keyInfo.Removable); Console.WriteLine("UniqueKeyContainerName property: " + keyInfo.UniqueKeyContainerName); }
/// <summary> /// Generates RSA asymmetric key in the configured key container if none exists /// </summary> public void CreateAsymKeyIfNotExists() { string assymKeyContainer = Config.GetValue(ConfigConstants.ASYM_KEY_PATH); CspParameters csp = new CspParameters() { KeyContainerName = assymKeyContainer, Flags = CspProviderFlags.UseMachineKeyStore }; CspKeyContainerInfo cspKeyContainer = new CspKeyContainerInfo(csp); if (!cspKeyContainer.Accessible) { int keySize = int.Parse(Config.GetValue(ConfigConstants.ASYM_KEY_SIZE_BITS)); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize, csp)) { rsa.PersistKeyInCsp = true; } } }
private RsaSecurityToken(RSACryptoServiceProvider rsa, bool ownsRsa) { if (rsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa"); } this.rsa = rsa; this.id = SecurityUniqueId.Create().Value; this.effectiveTime = DateTime.UtcNow; if (ownsRsa) { this.keyContainerInfo = rsa.CspKeyContainerInfo; rsa.PersistKeyInCsp = true; this.rsaHandle = GCHandle.Alloc(rsa); } else { GC.SuppressFinalize(this); } }
public static void ShowContainerInfo(CspKeyContainerInfo containerInfo) { string keyStore; Console.WriteLine(); if (containerInfo.MachineKeyStore) { keyStore = "Machine Store"; } else { keyStore = "User Store"; } Console.WriteLine("Key Store: {0}", keyStore); Console.WriteLine("Key Provider: {0}", containerInfo.ProviderName); Console.WriteLine("Key Container: \"{0}\"", containerInfo.KeyContainerName); Console.WriteLine("Generated: {0}", containerInfo.RandomlyGenerated); Console.WriteLine("Key Nubmer: {0}", containerInfo.KeyNumber); Console.WriteLine("Removable Key: {0}", containerInfo.Removable); }
public static CspKeyContainerInfo CreateCspKeyContainerInfo(CspParameters parameters, bool randomKeyContainer) { CspKeyContainerInfo result = null; if (_cspKeyContainerInfoConstructor == null) { lock (CspKeyContainerInfoConstructorSync) { if (_cspKeyContainerInfoConstructor == null) { _cspKeyContainerInfoConstructor = typeof(CspKeyContainerInfo).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(CspParameters), typeof(bool) }, null); } } } if (_cspKeyContainerInfoConstructor != null) { try { result = (CspKeyContainerInfo)_cspKeyContainerInfoConstructor.Invoke(new object[] { parameters, randomKeyContainer }); } catch (TargetInvocationException exception) { if (exception.InnerException != null) { throw exception.InnerException; } throw; } if (result.KeyNumber == ((KeyNumber)(-1))) { var containerPatameters = GetCspKeyContainerInfoPatameters(result); containerPatameters.KeyNumber = (int)KeyNumber.Exchange; } } return(result); }
void AddCertificatePrivateKeyAccess(X509Certificate2 cert) { if (cert != null && cert.HasPrivateKey) { try { AsymmetricAlgorithm key = cert.PrivateKey; // Only RSA provider is supported here if (key is RSACryptoServiceProvider) { RSACryptoServiceProvider prov = key as RSACryptoServiceProvider; CspKeyContainerInfo info = prov.CspKeyContainerInfo; CryptoKeySecurity keySec = info.CryptoKeySecurity; SecurityIdentifier ns = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); // Just add a rule, exisitng settings will be merged CryptoKeyAccessRule rule = new CryptoKeyAccessRule(ns, CryptoKeyRights.GenericRead, AccessControlType.Allow); keySec.AddAccessRule(rule); CommitCryptoKeySecurity(info, keySec); } } #pragma warning suppress 56500 catch (Exception e) { // CommitCryptoKeySecurity can actually throw any exception, // so the safest way here is to catch a generic exception while throw on critical ones if (Utilities.IsCriticalException(e)) { throw; } throw new WsatAdminException(WsatAdminErrorCode.CANNOT_UPDATE_PRIVATE_KEY_PERM, SR.GetString(SR.ErrorUpdateCertPrivateKeyPerm), e); } } }
private static CspParameters GetCspKeyContainerInfoPatameters(CspKeyContainerInfo cspKeyContainerInfo) { CspParameters result = null; if (_cspKeyContainerInfoPatametersField == null) { lock (CspKeyContainerInfoPatametersFieldSync) { if (_cspKeyContainerInfoPatametersField == null) { _cspKeyContainerInfoPatametersField = typeof(CspKeyContainerInfo).GetField("m_parameters", BindingFlags.Instance | BindingFlags.NonPublic); } } } if (_cspKeyContainerInfoPatametersField != null) { result = _cspKeyContainerInfoPatametersField.GetValue(cspKeyContainerInfo) as CspParameters; } return(result); }
// This is defense-in-depth. // Rsa finalizer can throw and bring down the process if in finalizer context. // This internal ctor is used by SM's IssuedSecurityTokenProvider. // If ownsRsa=true, this class will take ownership of the Rsa object and provides // a reliable finalizing/disposing of Rsa object. The GCHandle is used to ensure // order in finalizer sequence. RsaSecurityToken(RSACryptoServiceProvider rsa, bool ownsRsa) { if (rsa == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa"); } this.rsa = rsa; this.id = SecurityUniqueId.Create().Value; this.effectiveTime = DateTime.UtcNow; if (ownsRsa) { // This also key pair generation. // This must be called before PersistKeyInCsp to avoid a handle to go out of scope. this.keyContainerInfo = rsa.CspKeyContainerInfo; // We will handle key file deletion rsa.PersistKeyInCsp = true; this.rsaHandle = GCHandle.Alloc(rsa); } else { GC.SuppressFinalize(this); } }
public static void RSAtoPKCS12(RSACryptoServiceProvider rsa) { CspKeyContainerInfo keyContainerInfo = rsa.CspKeyContainerInfo; string keyContainerName = keyContainerInfo.KeyContainerName; uint keyNumber = (uint)keyContainerInfo.KeyNumber; string providerName = keyContainerInfo.ProviderName; uint cspflags = 0; string outfile = keyContainerName + ".p12"; byte[] pkcs12 = opensslkey.GetPkcs12((RSA)rsa, keyContainerName, providerName, keyNumber, cspflags); if (pkcs12 != null && opensslkey.verbose) { opensslkey.showBytes("\npkcs #12", pkcs12); } if (pkcs12 != null) { opensslkey.PutFileBytes(outfile, pkcs12, pkcs12.Length); Console.WriteLine("\nWrote pkc #12 file '{0}'\n", (object)outfile); } else { Console.WriteLine("\nProblem getting pkcs#12"); } }
public void AppendPrivateKeyInfo(StringBuilder sb) { #if NETNATIVE if (HasPrivateKey) { // Similar to the Unix implementation, in UWP merely acknowledge that there -is- a private key. sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Private Key]"); } #else CspKeyContainerInfo cspKeyContainerInfo = null; try { if (HasPrivateKey) { CspParameters parameters = GetPrivateKey(); cspKeyContainerInfo = new CspKeyContainerInfo(parameters); } } // We could not access the key container. Just return. catch (CryptographicException) { } if (cspKeyContainerInfo == null) { return; } sb.Append(Environment.NewLine + Environment.NewLine + "[Private Key]"); sb.Append(Environment.NewLine + " Key Store: "); sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User"); sb.Append(Environment.NewLine + " Provider Name: "); sb.Append(cspKeyContainerInfo.ProviderName); sb.Append(Environment.NewLine + " Provider type: "); sb.Append(cspKeyContainerInfo.ProviderType); sb.Append(Environment.NewLine + " Key Spec: "); sb.Append(cspKeyContainerInfo.KeyNumber); sb.Append(Environment.NewLine + " Key Container Name: "); sb.Append(cspKeyContainerInfo.KeyContainerName); try { string uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName; sb.Append(Environment.NewLine + " Unique Key Container Name: "); sb.Append(uniqueKeyContainer); } catch (CryptographicException) { } catch (NotSupportedException) { } bool b = false; try { b = cspKeyContainerInfo.HardwareDevice; sb.Append(Environment.NewLine + " Hardware Device: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Removable; sb.Append(Environment.NewLine + " Removable: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Protected; sb.Append(Environment.NewLine + " Protected: "); sb.Append(b); } catch (CryptographicException) { } catch (NotSupportedException) { } #endif // #if NETNATIVE / #else }
/// <summary> /// Set the private key object. The additional "publicKey" argument is used to validate that the private key corresponds to the existing publicKey. /// </summary> public void SetPrivateKey(AsymmetricAlgorithm privateKey, AsymmetricAlgorithm publicKey) { if (privateKey == null) { unsafe { if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, CertSetPropertyFlags.None, (CRYPT_KEY_PROV_INFO *)null)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } } else { // we do not support keys in non-CAPI storage for now. ICspAsymmetricAlgorithm asymmetricAlgorithm = privateKey as ICspAsymmetricAlgorithm; if (asymmetricAlgorithm == null) { throw new NotSupportedException(SR.NotSupported_InvalidKeyImpl); } if (asymmetricAlgorithm.CspKeyContainerInfo == null) { throw new ArgumentException("CspKeyContainerInfo"); } // check that the public key in the certificate corresponds to the private key passed in. // // note that it should be legal to set a key which matches in every aspect but the usage // i.e. to use a CALG_RSA_KEYX private key to match a CALG_RSA_SIGN public key. A // PUBLICKEYBLOB is defined as: // // BLOBHEADER publickeystruc // RSAPUBKEY rsapubkey // BYTE modulus[rsapubkey.bitlen/8] // // To allow keys which differ by key usage only, we skip over the BLOBHEADER of the key, // and start comparing bytes at the RSAPUBKEY structure. unsafe { // This cast is safe because via our contract with our caller, "publicKey" is the Key property of a PublicKey object that this Pal class manufactured in the first place. // Since we manufactured the PublicKey, we know the real types of the object. ICspAsymmetricAlgorithm cspPublicKey = (ICspAsymmetricAlgorithm)publicKey; byte[] array1 = cspPublicKey.ExportCspBlob(false); byte[] array2 = asymmetricAlgorithm.ExportCspBlob(false); if (array1 == null || array2 == null || array1.Length != array2.Length || array1.Length <= sizeof(BLOBHEADER)) { throw new CryptographicUnexpectedOperationException(SR.Cryptography_X509_KeyMismatch); } for (int index = sizeof(BLOBHEADER); index < array1.Length; index++) { if (array1[index] != array2[index]) { throw new CryptographicUnexpectedOperationException(SR.Cryptography_X509_KeyMismatch); } } } unsafe { CspKeyContainerInfo keyContainerInfo = asymmetricAlgorithm.CspKeyContainerInfo; fixed(char *pKeyContainerName = keyContainerInfo.KeyContainerName, pProviderName = keyContainerInfo.ProviderName) { CRYPT_KEY_PROV_INFO keyProvInfo = new CRYPT_KEY_PROV_INFO() { pwszContainerName = pKeyContainerName, pwszProvName = pProviderName, dwProvType = keyContainerInfo.ProviderType, dwFlags = keyContainerInfo.MachineKeyStore ? CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET : CryptAcquireContextFlags.None, cProvParam = 0, rgProvParam = IntPtr.Zero, dwKeySpec = (int)(keyContainerInfo.KeyNumber), }; if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, CertSetPropertyFlags.None, &keyProvInfo)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } } } }
internal static X509Certificate2 CopyWithPersistedCapiKey(X509Certificate2 publicCert, CspKeyContainerInfo keyContainerInfo) { if (string.IsNullOrEmpty(keyContainerInfo.KeyContainerName)) { return(null); } X509Certificate2 publicPrivate = new X509Certificate2(publicCert.RawData); var keyProvInfo = new X509Native.CRYPT_KEY_PROV_INFO(); keyProvInfo.pwszContainerName = keyContainerInfo.KeyContainerName; keyProvInfo.pwszProvName = keyContainerInfo.ProviderName; keyProvInfo.dwProvType = keyContainerInfo.ProviderType; keyProvInfo.dwKeySpec = (int)keyContainerInfo.KeyNumber; keyProvInfo.dwFlags = keyContainerInfo.MachineKeyStore ? X509Native.CRYPT_MACHINE_KEYSET : 0; using (SafeCertContextHandle certificateContext = X509Native.GetCertificateContext(publicPrivate)) { if (!X509Native.SetCertificateKeyProvInfo(certificateContext, ref keyProvInfo)) { int hr = Marshal.GetLastWin32Error(); publicPrivate.Dispose(); throw new CryptographicException(hr); } } return(publicPrivate); }
public void ReadClientCertificate(X509Certificate2 certificate, byte[] clientCertBytes) { try { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //To make sure that a key container has been created, we are calling the SignData() method byte[] encData = rsa.SignData(clientCertBytes, new SHA1CryptoServiceProvider()); CspKeyContainerInfo keyInfo = rsa.CspKeyContainerInfo; string str = keyInfo.ProviderName; ViewBag.ProviderName = str; ViewBag.ClientCertSubject = certificate.Subject; ViewBag.ClientCertIssuer = certificate.Issuer; ViewBag.ClientCertThumbprint = certificate.Thumbprint.ToString(); ViewBag.ClientCertIssueDate = " FROM : " + certificate.NotBefore.ToUniversalTime().ToString("dd/MM/yyyy HH:mm"); ViewBag.ClientCertExpiryDate = " TO : " + certificate.NotAfter.ToUniversalTime().ToString("dd/MM/yyyy HH:mm"); ViewBag.ClientCertVersion = certificate.Version; ViewBag.PublicKeyAlgorithm = certificate.PublicKey.EncodedKeyValue.Oid.FriendlyName; if (certificate.PublicKey.Key.KeyExchangeAlgorithm == null) { throw new NotSupportedException("Private key does not support key exchange"); } ViewBag.KeyExchangeAlgorithm = certificate.PublicKey.Key.KeyExchangeAlgorithm; ViewBag.KeySize = certificate.PublicKey.Key.KeySize; ViewBag.SignatureAlgorithm = certificate.SignatureAlgorithm.FriendlyName; //Reading the optional field Enhanced Key Usage X509EnhancedKeyUsageExtension ekuExtension = (X509EnhancedKeyUsageExtension)certificate.Extensions["Enhanced Key Usage"]; if (ekuExtension != null) { ViewBag.EkuExtension = ekuExtension.EnhancedKeyUsages; ViewBag.EkuExtensionCount = ekuExtension.EnhancedKeyUsages.Count; } else { ViewBag.EkuExtension = "NULL"; } //Reading the optional field Key Usage X509KeyUsageExtension kuExtension = (X509KeyUsageExtension)certificate.Extensions["Key Usage"]; if (kuExtension != null) { ViewBag.KuExtension = kuExtension.KeyUsages; } else { ViewBag.KuExtension = "NULL"; } //X509Extension crlDistributionPoints = (X509Extension)certificate.Extensions["CRL Distribution Points"]; //if(crlDistributionPoints!=null) //{ // byte[] crlBytes = crlDistributionPoints.RawData; // AsnEncodedData asndata = new AsnEncodedData(crlDistributionPoints.Oid, crlDistributionPoints.RawData); // X509Certificate2 x509 = new X509Certificate2(); // x509.Import(crlBytes); // ViewBag.CrlDistributionPoints = crlDistributionPoints.Oid.Value.ToString(); //} //else //{ // ViewBag.CrlDistributionPoints = "Not Available"; //} } catch (Exception ex) { errorString = ex.ToString(); } }
private void AppendPrivateKeyInfo(StringBuilder sb) { CspKeyContainerInfo info = null; try { if (this.HasPrivateKey) { CspParameters parameters = new CspParameters(); if (GetPrivateKeyInfo(this.m_safeCertContext, ref parameters)) { info = new CspKeyContainerInfo(parameters); } } } catch (SecurityException) { } catch (CryptographicException) { } if (info != null) { sb.Append(Environment.NewLine + Environment.NewLine + "[Private Key]"); sb.Append(Environment.NewLine + " Key Store: "); sb.Append(info.MachineKeyStore ? "Machine" : "User"); sb.Append(Environment.NewLine + " Provider Name: "); sb.Append(info.ProviderName); sb.Append(Environment.NewLine + " Provider type: "); sb.Append(info.ProviderType); sb.Append(Environment.NewLine + " Key Spec: "); sb.Append(info.KeyNumber); sb.Append(Environment.NewLine + " Key Container Name: "); sb.Append(info.KeyContainerName); try { string uniqueKeyContainerName = info.UniqueKeyContainerName; sb.Append(Environment.NewLine + " Unique Key Container Name: "); sb.Append(uniqueKeyContainerName); } catch (CryptographicException) { } catch (NotSupportedException) { } bool hardwareDevice = false; try { hardwareDevice = info.HardwareDevice; sb.Append(Environment.NewLine + " Hardware Device: "); sb.Append(hardwareDevice); } catch (CryptographicException) { } try { hardwareDevice = info.Removable; sb.Append(Environment.NewLine + " Removable: "); sb.Append(hardwareDevice); } catch (CryptographicException) { } try { hardwareDevice = info.Protected; sb.Append(Environment.NewLine + " Protected: "); sb.Append(hardwareDevice); } catch (CryptographicException) { } catch (NotSupportedException) { } } }
public void AppendPrivateKeyInfo(StringBuilder sb) { CspKeyContainerInfo cspKeyContainerInfo = null; try { if (HasPrivateKey) { CspParameters parameters = GetPrivateKey(); cspKeyContainerInfo = new CspKeyContainerInfo(parameters); } } // We could not access the key container. Just return. catch (CryptographicException) { } if (cspKeyContainerInfo == null) { return; } sb.Append(Environment.NewLine + Environment.NewLine + "[Private Key]"); sb.Append(Environment.NewLine + " Key Store: "); sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User"); sb.Append(Environment.NewLine + " Provider Name: "); sb.Append(cspKeyContainerInfo.ProviderName); sb.Append(Environment.NewLine + " Provider type: "); sb.Append(cspKeyContainerInfo.ProviderType); sb.Append(Environment.NewLine + " Key Spec: "); sb.Append(cspKeyContainerInfo.KeyNumber); sb.Append(Environment.NewLine + " Key Container Name: "); sb.Append(cspKeyContainerInfo.KeyContainerName); try { String uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName; sb.Append(Environment.NewLine + " Unique Key Container Name: "); sb.Append(uniqueKeyContainer); } catch (CryptographicException) { } catch (NotSupportedException) { } bool b = false; try { b = cspKeyContainerInfo.HardwareDevice; sb.Append(Environment.NewLine + " Hardware Device: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Removable; sb.Append(Environment.NewLine + " Removable: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Protected; sb.Append(Environment.NewLine + " Protected: "); sb.Append(b); } catch (CryptographicException) { } catch (NotSupportedException) { } }
private void showRSAProps(RSACryptoServiceProvider rsa) { CspKeyContainerInfo cspKeyContainerInfo = rsa.CspKeyContainerInfo; }
static void Main(string[] args) { Settings.Load(); Settings.Save(); proxy = new Net.Proxy(8877); _handler += new EventHandler(Handler); SetConsoleCtrlHandler(_handler, true); for (int i = 0; i < args.Length; i++) { var group = Regex.Match(args[i], "[-]{1,2}(.*)").Groups[1]; if (group.Success) { switch (group.Value) { case "nopatch": PatchPublicKey = false; break; case "showconsole": showConsole = true; break; } } } logger.WriteLine("Made by FailedShack"); SetConsoleVisibility(showConsole); Application.EnableVisualStyles(); if (Settings.ShowUpdateNag) { Task.Run(async() => { JObject release; try { release = await GithubUtil.GetRelease("FailedShack", "USBHelperLauncher", "latest"); } catch { return; } string newVersion = (string)release["tag_name"]; string version = GetVersion(); if (newVersion.CompareTo(version) > 0) { var updateNag = new CheckboxDialog("New version found: " + newVersion + "\nCurrent version: " + version + "\nDo you want to open the download site?", "Do not show this again.", "Update Checker", MessageBoxButtons.YesNo, MessageBoxIcon.Information); DialogResult result = updateNag.ShowDialog(); if (result == DialogResult.Yes) { Process.Start((string)release["html_url"]); } Settings.ShowUpdateNag = !updateNag.Checked; Settings.Save(); } }); } string hostsFile = GetHostsFile(); if (File.Exists(hostsFile)) { try { Hosts = Hosts.Load(hostsFile); } catch (Exception e) { MessageBox.Show("Could not load hosts file: " + e.Message, "Malformed hosts file", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Hosts = new Hosts(); if (Settings.ShowHostsWarning) { var hostsWarning = new CheckboxDialog( "It appears you don't currently have a hosts redirector file. This file may be required to route obsolete hostnames to their correct destination.\n" + "If you intended to use this feature, make sure a file named 'hosts.json' is located in the same directory as this executable.\n" + "You may also use the built-in editor located in the Advanced section in the tray icon's context menu.", "Do not show this again.", "Hosts file missing", MessageBoxButtons.OK, MessageBoxIcon.Warning); hostsWarning.ShowDialog(); Settings.ShowHostsWarning = !hostsWarning.Checked; Settings.Save(); } } try { database.LoadFromDir(Path.Combine(GetLauncherPath(), "data")); } catch (FileNotFoundException e) { MessageBox.Show(e.Message + "\nMake sure this file is under the data directory.", "Initialization error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } if (!File.Exists("ver") || !File.Exists("WiiU_USB_Helper.exe")) { MessageBox.Show("Could not find Wii U USB Helper, please make sure this executable is in the correct folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } helperVersion = File.ReadAllLines("ver")[0]; int revision = int.Parse(helperVersion.Substring(helperVersion.LastIndexOf('.') + 1)); if (helperVersion.StartsWith("0.6.1")) { // Workaround to allow it to launch if (revision >= 653) { string installPath = GetInstallPath(); string lastTitles = Path.Combine(installPath, "lasttitles"); if (revision > 653) { string installConfPath = GetInstallConfPath(); Directory.CreateDirectory(installConfPath); File.Create(Path.Combine(installConfPath, "user.config")).Close(); } if (!File.Exists(lastTitles)) { Directory.CreateDirectory(installPath); StringBuilder sb = new StringBuilder(); // Rev. 653 minimums: 3 lines, single character each // Revs. 654 & 655 minimums: 25 lines, 16 chars each for (int lines = 0; lines != 25; lines++) { sb.Append('0', 16).AppendLine(); } File.WriteAllText(lastTitles, sb.ToString()); } } } // Ensure that the cached title key JSON files are valid string[] toCheck = { "3FFFD23A80F800ABFCC436A5EC8F7F0B94C728A4", "9C6DD14B8E3530B701BC4F1B77345DADB0C32020" }; foreach (string file in toCheck) { string path = Path.Combine(GetInstallPath(), file); if (File.Exists(path)) { try { JToken.Parse(File.ReadAllText(path)); } catch (JsonReaderException) { File.Delete(path); logger.WriteLine(string.Format("Removed bad cache file: {0}", file)); } } } // Make sure that FiddlerCore's key container can be accessed string keyContainerName = FiddlerApplication.Prefs.GetStringPref("fiddler.certmaker.bc.KeyContainerName", "FiddlerBCKey"); try { CspParameters cspParams = new CspParameters { KeyContainerName = keyContainerName }; var _ = new CspKeyContainerInfo(cspParams).UniqueKeyContainerName; // this will throw an exception if the container cannot be accessed } catch (CryptographicException) { byte[] hash; using (MD5 md5 = MD5.Create()) { hash = md5.ComputeHash(Encoding.ASCII.GetBytes(keyContainerName.ToLower() + "\0")); } var reader = new BinaryReader(new MemoryStream(hash)); var sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.AppendFormat("{0:x8}", reader.ReadInt32()); } string hashString = sb.ToString(); string userSID = WindowsIdentity.GetCurrent().User.ToString(); string rsaPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Crypto", "RSA", userSID); string keyContainer = Directory.GetFiles(rsaPath).Where(n => Path.GetFileName(n).ToLower().StartsWith(hashString)).FirstOrDefault(); if (keyContainer != null) { File.Delete(keyContainer); logger.WriteLine(string.Format("Removed broken key container (Name: \"{0}\", Hash: {1}).", keyContainerName, hashString)); } } if (!CertMaker.rootCertExists() && !CertMaker.createRootCert()) { MessageBox.Show("Creation of the interception certificate failed.", "Unable to generate certificate.", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } string executable = Path.Combine(GetLauncherPath(), "WiiU_USB_Helper.exe"); var running = Process.GetProcessesByName("Patched").FirstOrDefault(p => p.GetMainModuleFileName().StartsWith(GetLauncherPath(), StringComparison.OrdinalIgnoreCase)); if (running != default(Process)) { DialogResult result = MessageBox.Show("An instance of Wii U USB Helper is already running.\nWould you like to close it?", "Already running", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (result == DialogResult.No) { Environment.Exit(0); } running.Kill(); } proxy.Start(); ServiceHost host = new ServiceHost(typeof(LauncherService), new Uri("net.pipe://localhost/LauncherService")); host.AddServiceEndpoint(typeof(ILauncherService), new NetNamedPipeBinding(), ""); host.Open(); // Patching ProgressDialog dialog = new ProgressDialog(); dialog.SetStyle(ProgressBarStyle.Marquee); dialog.GetProgressBar().MarqueeAnimationSpeed = 30; dialog.SetHeader("Injecting..."); new Thread(() => { dialog.ShowDialog(); }).Start(); var injector = new ModuleInitInjector(executable); executable = Path.Combine(GetLauncherPath(), "Patched.exe"); injector.Inject(executable); logger.WriteLine("Injected module initializer."); if (PatchPublicKey) { dialog.Invoke(new Action(() => dialog.SetHeader("Patching..."))); RSAPatcher patcher = new RSAPatcher(executable); string xml; using (var rsa = new RSACryptoServiceProvider(2048)) { rsaParams = rsa.ExportParameters(true); xml = rsa.ToXmlString(false); } var builder = new StringBuilder(); var element = XElement.Parse(xml); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }; using (var xmlWriter = XmlWriter.Create(builder, settings)) { element.Save(xmlWriter); } patcher.SetPublicKey(builder.ToString()); logger.WriteLine("Patched public key."); } else { logger.WriteLine("Patching has been disabled."); } dialog.Invoke(new Action(() => dialog.Close())); // Time to launch Wii U USB Helper sessionStart = DateTime.UtcNow; process = StartProcess(executable, helperVersion); if (Settings.DisableOptionalPatches) { logger.WriteLine("Optional patches have been disabled."); } ContextMenu trayMenu = new ContextMenu(); MenuItem dlEmulator = new MenuItem("Download Emulator"); foreach (EmulatorConfiguration.Emulator emulator in Enum.GetValues(typeof(EmulatorConfiguration.Emulator))) { EmulatorConfiguration config = EmulatorConfiguration.GetConfiguration(emulator); dlEmulator.MenuItems.Add(config.GetName(), (sender, e) => OnDownloadEmulator(config)); } MenuItem advanced = new MenuItem("Advanced"); advanced.MenuItems.Add("Toggle Console", OnVisibilityChange); advanced.MenuItems.Add("Clear Install", OnClearInstall); advanced.MenuItems.Add("Generate Donation Key", OnGenerateKey).Enabled = PatchPublicKey; advanced.MenuItems.Add("Hosts Editor", OnOpenHostsEditor); advanced.MenuItems.Add("Export Sessions", OnExportSessions); trayMenu.MenuItems.Add("Exit", OnExit); trayMenu.MenuItems.Add("Check for Updates", OnUpdateCheck); trayMenu.MenuItems.Add("Report Issue", OnDebugMessage); trayMenu.MenuItems.Add(dlEmulator); trayMenu.MenuItems.Add(advanced); trayIcon = new NotifyIcon { Text = "Wii U USB Helper Launcher", Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath), ContextMenu = trayMenu, Visible = true }; backgroundThread = new Thread(() => { Thread.CurrentThread.IsBackground = true; while (!process.HasExited) { try { Thread.Sleep(30); } catch (ThreadInterruptedException) { } } Cleanup(); Application.Exit(); }); backgroundThread.Start(); Application.Run(); }
public void AppendPrivateKeyInfo(StringBuilder sb) { if (!HasPrivateKey) { return; } // UWP, Windows CNG persisted, and Windows Ephemeral keys will all acknowledge that // a private key exists, but detailed printing is limited to Windows CAPI persisted. // (This is the same thing we do in Unix) sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Private Key]"); CspKeyContainerInfo cspKeyContainerInfo = null; try { CspParameters parameters = GetPrivateKeyCsp(); if (parameters != null) { cspKeyContainerInfo = new CspKeyContainerInfo(parameters); } } // We could not access the key container. Just return. catch (CryptographicException) { } // Ephemeral keys will not have container information. if (cspKeyContainerInfo == null) { return; } sb.Append(Environment.NewLine + " Key Store: "); sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User"); sb.Append(Environment.NewLine + " Provider Name: "); sb.Append(cspKeyContainerInfo.ProviderName); sb.Append(Environment.NewLine + " Provider type: "); sb.Append(cspKeyContainerInfo.ProviderType); sb.Append(Environment.NewLine + " Key Spec: "); sb.Append(cspKeyContainerInfo.KeyNumber); sb.Append(Environment.NewLine + " Key Container Name: "); sb.Append(cspKeyContainerInfo.KeyContainerName); try { string uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName; sb.Append(Environment.NewLine + " Unique Key Container Name: "); sb.Append(uniqueKeyContainer); } catch (CryptographicException) { } catch (NotSupportedException) { } bool b = false; try { b = cspKeyContainerInfo.HardwareDevice; sb.Append(Environment.NewLine + " Hardware Device: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Removable; sb.Append(Environment.NewLine + " Removable: "); sb.Append(b); } catch (CryptographicException) { } try { b = cspKeyContainerInfo.Protected; sb.Append(Environment.NewLine + " Protected: "); sb.Append(b); } catch (CryptographicException) { } catch (NotSupportedException) { } }
public static void Main(String[] args) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); try { // Note: In cases where a random key is generated, // a key container is not created until you call // a method that uses the key. This example calls // the Encrypt method before calling the // CspKeyContainerInfo property so that a key // container is created. // Create some data to encrypt and display it. string data = "Here is some data to encrypt."; Console.WriteLine("Data to encrypt: " + data); // Convert the data to an array of bytes and // encrypt it. byte[] byteData = Encoding.ASCII.GetBytes(data); byte[] encData = rsa.Encrypt(byteData, false); // Display the encrypted value. Console.WriteLine("Encrypted Data: " + Encoding.ASCII.GetString(encData)); Console.WriteLine(); Console.WriteLine("CspKeyContainerInfo information:"); Console.WriteLine(); // Create a new CspKeyContainerInfo object. CspKeyContainerInfo keyInfo = rsa.CspKeyContainerInfo; // Display the value of each property. Console.WriteLine("Accessible property: " + keyInfo.Accessible); Console.WriteLine("Exportable property: " + keyInfo.Exportable); Console.WriteLine("HardwareDevice property: " + keyInfo.HardwareDevice); Console.WriteLine("KeyContainerName property: " + keyInfo.KeyContainerName); Console.WriteLine("KeyNumber property: " + keyInfo.KeyNumber.ToString()); Console.WriteLine("MachineKeyStore property: " + keyInfo.MachineKeyStore); Console.WriteLine("Protected property: " + keyInfo.Protected); Console.WriteLine("ProviderName property: " + keyInfo.ProviderName); Console.WriteLine("ProviderType property: " + keyInfo.ProviderType); Console.WriteLine("RandomlyGenerated property: " + keyInfo.RandomlyGenerated); Console.WriteLine("Removable property: " + keyInfo.Removable); Console.WriteLine("UniqueKeyContainerName property: " + keyInfo.UniqueKeyContainerName); } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { // Clear the key. rsa.Clear(); } }
internal static ExchangeCertificateValidity ValidateExchangeCertificate(X509Certificate2 cert, bool ignoreAccessible) { if (cert == null) { throw new ArgumentNullException("cert"); } if (!cert.HasPrivateKey) { return(ExchangeCertificateValidity.PrivateKeyMissing); } string keyAlgorithm = cert.GetKeyAlgorithm(); bool flag = string.Equals(keyAlgorithm, WellKnownOid.X957Sha1Dsa.Value, StringComparison.OrdinalIgnoreCase); if (!string.Equals(keyAlgorithm, WellKnownOid.RsaRsa.Value, StringComparison.OrdinalIgnoreCase) && !flag) { return(ExchangeCertificateValidity.KeyAlgorithmUnsupported); } foreach (X509Extension x509Extension in cert.Extensions) { try { X509KeyUsageExtension x509KeyUsageExtension = x509Extension as X509KeyUsageExtension; if (x509KeyUsageExtension != null) { X509KeyUsageFlags keyUsages = x509KeyUsageExtension.KeyUsages; bool flag2 = false; if (keyUsages == X509KeyUsageFlags.None) { flag2 = true; } else if ((keyUsages & (X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.DigitalSignature)) != X509KeyUsageFlags.None) { flag2 = true; } if (!flag2) { return(ExchangeCertificateValidity.SigningNotSupported); } } } catch (CryptographicException) { return(ExchangeCertificateValidity.KeyUsageCorrupted); } try { X509EnhancedKeyUsageExtension x509EnhancedKeyUsageExtension = x509Extension as X509EnhancedKeyUsageExtension; if (x509EnhancedKeyUsageExtension != null && x509EnhancedKeyUsageExtension.EnhancedKeyUsages.Count > 0 && x509EnhancedKeyUsageExtension.EnhancedKeyUsages[WellKnownOid.PkixKpServerAuth.Value] == null) { return(ExchangeCertificateValidity.PkixKpServerAuthNotFoundInEnhancedKeyUsage); } } catch (CryptographicException) { return(ExchangeCertificateValidity.EnhancedKeyUsageCorrupted); } } if (TlsCertificateInfo.IsCNGProvider(cert)) { return(ManageExchangeCertificate.CheckCNGSettings(cert)); } AsymmetricAlgorithm privateKey; try { privateKey = cert.PrivateKey; } catch (CryptographicException) { return(ExchangeCertificateValidity.PrivateKeyNotAccessible); } ICspAsymmetricAlgorithm cspAsymmetricAlgorithm = privateKey as ICspAsymmetricAlgorithm; if (cspAsymmetricAlgorithm == null) { return(ExchangeCertificateValidity.PrivateKeyUnsupportedAlgorithm); } CspKeyContainerInfo cspKeyContainerInfo = cspAsymmetricAlgorithm.CspKeyContainerInfo; if (cspKeyContainerInfo.Protected) { return(ExchangeCertificateValidity.CspKeyContainerInfoProtected); } if (cspKeyContainerInfo.HardwareDevice && cspKeyContainerInfo.Removable) { return(ExchangeCertificateValidity.CspKeyContainerInfoRemovableDevice); } if (!ignoreAccessible && !cspKeyContainerInfo.Accessible) { return(ExchangeCertificateValidity.CspKeyContainerInfoNotAccessible); } switch (cspKeyContainerInfo.KeyNumber) { case KeyNumber.Exchange: case KeyNumber.Signature: { AsymmetricAlgorithm key = cert.PublicKey.Key; if (key.KeySize < 1024) { return(ExchangeCertificateValidity.PublicKeyUnsupportedSize); } return(ExchangeCertificateValidity.Valid); } default: return(ExchangeCertificateValidity.CspKeyContainerInfoUnknownKeyNumber); } }