/// <summary> /// A string extension method that encrypts the string. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="key">The key.</param> /// <returns>The encrypted string.</returns> /// <example> /// <code> /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_String_EncryptRSA /// { /// [TestMethod] /// public void EncryptRSA() /// { /// // Type /// string @this = "Fizz"; /// /// // Examples /// string value = @this.EncryptRSA("Buzz"); // return Encrypted string; /// /// // Unit Test /// Assert.AreEqual("Fizz", value.DecryptRSA("Buzz")); /// } /// } /// } /// </code> /// </example> public static string EncryptRSA(this string @this, string key) { var cspp = new CspParameters {KeyContainerName = key}; var rsa = new RSACryptoServiceProvider(cspp) {PersistKeyInCsp = true}; byte[] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(@this), true); return BitConverter.ToString(bytes); }
public static void CreateKey_LegacyProvider_RoundtripBlob() { const int KeySize = 512; CspParameters cspParameters = new CspParameters(PROV_RSA_FULL); byte[] blob; using (var rsa = new RSACryptoServiceProvider(KeySize, cspParameters)) { CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo; Assert.Equal(PROV_RSA_FULL, containerInfo.ProviderType); Assert.Equal(KeySize, rsa.KeySize); blob = rsa.ExportCspBlob(true); } using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(blob); CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo; // The provider information is not persisted in the blob Assert.Equal(PROV_RSA_AES, containerInfo.ProviderType); Assert.Equal(KeySize, rsa.KeySize); } }
/// <summary> /// Sign the XML String of SamlResponse /// </summary> /// <param name="xmlString"></param> /// <returns>Digital signed SamlReponse string</returns> public static String signSamlElement(String xmlString) { // Create a new CspParameters object to specify a key container. CspParameters cspParams = new CspParameters(); cspParams.Flags = CspProviderFlags.UseMachineKeyStore; // cspParams.KeyContainerName = "GOOGLE"; // cspParams.ProviderName = "HF"; string pb = "<RSAKeyValue><Modulus>wTI341fDKEG9mV9VDFRj/XKf5nZxfadISavENRbwPlKZBipYAi6zgVNPJ7nhSH4qdXqphOreXFFmwsg8JzxHLJRJ8yjIfiG3ORuRaHO0dpTslSQ4wz5qVroj4avI3m5pL6jFgtaWJkWlr7uzq4xrdKwu+wZiOaNNCFjqUo18ycE=</Modulus><Exponent>AQAB</Exponent><P>86FAPMQJey3PrI+PBPnMgn8xzR3qy/WBjUihKn+Fb9tP7GipWD9oi3tkdR/KZfBcvSoacDQqxMg8Y+aY90glGQ==</P><Q>ywFrg+GccDYsFwOZJsgzC8FXBQf9jalFbfuRdjrrH0Cd2JqHXC/nrpc7YB3qOORaWSuxWorGdN3+o42qszX26Q==</Q><DP>L3udDnrSsjxCfopYQIsDDegGZ8jN60SFJGkkaCkEc8GVuSjI4JczJAQ/lwhEJUwMdx3Om1G/iCzSgFIAPCnGeQ==</DP><DQ>HX0nUREE2IgF/5HWPXv3bk23hlOS0XE1VLSmfLYyUWfhhgVshEexL/tn9J5j17/UH//o0241ReS5iKibk0zTgQ==</DQ><InverseQ>IC++K/C2NT5w01BYp5dcB1sXmWH32oFB1bmgcAkwK2VbQm9a9Xt1YdXtMVUEkxln7Inciny8oEfwdDiUjc82KQ==</InverseQ><D>byvGnTvTQUcTIz6IYh/tqdpbyPI/PF8Wac49iY85j6NYCwQywI6/HJwj4GhGCsEPDasYATRl4Bm3WD6A3tMA4NUw/RYfdutL2vDXjYXZMETWnABeeTdPK9haPw/NrcvhWRkGqNyeHG1soqmrF/x/0Xh5EYTv4KtrIJrPpKFajAE=</D></RSAKeyValue>"; // Create a new RSA signing key and save it in the container. RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(); /* RSACryptoServiceProvider rsaKey; if (System.Web.HttpContext.Current == null) // WinForm rsaKey = new RSACryptoServiceProvider(); else // WebForm - Uses Machine store for keys rsaKey = new RSACryptoServiceProvider(cspParams); */ rsaKey.FromXmlString(pb); /* X509Certificate2 cert = new X509Certificate2(@"C:\certificate.pfx", ""); RSACryptoServiceProvider rsaKey = cert.PrivateKey as RSACryptoServiceProvider;*/ // Create a new XML document XmlDocument xmlDoc = new XmlDocument(); // Load an XML String into the XmlDocument object xmlDoc = Util.createXmlDom(xmlString); // Sign the XML document SignXml(xmlDoc, rsaKey); // convert XmlDocument to String /* MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, null); writer.Formatting = Formatting.Indented; xmlDoc.Save(writer); StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8); stream.Position = 0; string res = sr.ReadToEnd(); sr.Close(); stream.Close(); return res; * */ return xmlDoc.OuterXml; }
/// <summary> /// A string extension method that decrypt a string. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="key">The key.</param> /// <returns>The decrypted string.</returns> /// <example> /// <code> /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_String_DecryptRSA /// { /// [TestMethod] /// public void DecryptRSA() /// { /// // Type /// string @this = "7E-24-A5-CF-8E-7A-83-52-90-CA-81-6F-26-04-7C-E6-F4-25-47-26-A9-55-04-83-32-78-1A-C0-E4-5D-90-66-A6-E1-58-59-A8-48-E1-20-21-B9-FE-84-31-53-52-9B-45-E1-B2-93-71-92-DA-29-5B-99-D1-41-19-9C-3E-13-4B-2B-BC-08-94-31-A4-F9-B9-0A-04-2F-C6-78-B1-47-27-11-2C-E6-AF-BF-A8-F2-F3-F6-4E-CB-EB-79-5E-80-C6-A1-0A-D7-7C-F1-16-0E-41-14-4E-76-7E-9E-DD-61-BF-11-5E-62-79-2D-C4-11-D2-F6-3D-7F-DD-87-C4-4E"; /// /// // Examples /// string value = @this.DecryptRSA("Buzz"); // return "Fizz"; /// /// // Unit Test /// Assert.AreEqual("Fizz", value); /// } /// } /// } /// </code> /// </example> public static string DecryptRSA(this string @this, string key) { var cspp = new CspParameters {KeyContainerName = key}; var rsa = new RSACryptoServiceProvider(cspp) {PersistKeyInCsp = true}; string[] decryptArray = @this.Split(new[] {"-"}, StringSplitOptions.None); byte[] decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, NumberStyles.HexNumber)))); byte[] bytes = rsa.Decrypt(decryptByteArray, true); return Encoding.UTF8.GetString(bytes); }
public static void CreateKey() { CspParameters cspParameters = new CspParameters(PROV_DSS_DH); using (var dsa = new DSACryptoServiceProvider(cspParameters)) { CspKeyContainerInfo containerInfo = dsa.CspKeyContainerInfo; Assert.Equal(PROV_DSS_DH, containerInfo.ProviderType); } }
public static void CreateKey_LegacyProvider() { CspParameters cspParameters = new CspParameters(PROV_RSA_FULL); using (var rsa = new RSACryptoServiceProvider(cspParameters)) { CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo; Assert.Equal(PROV_RSA_FULL, containerInfo.ProviderType); } }
public static void DefaultProvider() { const int PROV_RSA_AES = 24; CspParameters cspParameters = new CspParameters(); // An awful lot of work goes into this calculation in the product code, // but on all supported operating systems PROV_RSA_AES should be the // conclusion: Assert.Equal(PROV_RSA_AES, cspParameters.ProviderType); }
public static void SetFlags_ValidatesInput() { CspParameters cspParameters = new CspParameters(); // Unmapped values (> 0xFF) throw Assert.Throws<ArgumentException>(() => cspParameters.Flags = (CspProviderFlags)0x0100); // Unmapped values (> 0xFF) throw, even when combined with known values. Assert.Throws<ArgumentException>( () => cspParameters.Flags = (CspProviderFlags)0x0100 | CspProviderFlags.NoPrompt); }
public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer1"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); }
public static string RSAEncrypt(string plaintext) { CspParameters param = new CspParameters(); param.KeyContainerName = "PowerGridIndia"; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param)) { byte[] plaindata = System.Text.Encoding.Default.GetBytes(plaintext); byte[] encryptdata = rsa.Encrypt(plaindata, false); string encryptstring = Convert.ToBase64String(encryptdata); return encryptstring; } }
public static string RSADecrypt(string encryptedString) { CspParameters param = new CspParameters(); param.KeyContainerName = "PowerGridIndia"; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param)) { int len = encryptedString.Length; encryptedString = encryptedString.Replace(" ", "+"); byte[] encryptdata = Convert.FromBase64String(encryptedString); byte[] decryptdata = rsa.Decrypt(encryptdata, false); string plaindata = System.Text.Encoding.Default.GetString(decryptdata); return plaindata; } }
public static void Main(String[] args) { try { // Create a new CspParameters object to specify // a key container. CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; // Create a new RSA signing key and save it in the container. RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams); // Create a new XML document. XmlDocument xmlDoc = new XmlDocument(); // Load an XML file into the XmlDocument object. xmlDoc.PreserveWhitespace = true; xmlDoc.Load("sadan_xml.xml"); // Verify the signature of the signed XML. Console.WriteLine("Verifying signature..."); bool result = VerifyXml(xmlDoc, rsaKey); // Display the results of the signature verification to // the console. if (result) { Console.WriteLine("The XML signature is valid."); } else { Console.WriteLine("The XML signature is not valid."); } } catch (Exception e) { Console.WriteLine(e.Message); } }
public PasswordDeriveBytes(byte[] password, byte[] salt, CspParameters cspParams) {}
public static void GenerateRootCertificate(string subjectName, DateTime expireOnUtc, out string password, out string pemValue, out byte[] cerData, out byte[] pkcs12Data) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); BigInteger serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotAfter(expireOnUtc); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA256WithRSA"); gen.SetPublicKey(subjectKeyPair.Public); var certificate = gen.Generate(subjectKeyPair.Private, random); var privateKeyPem = new StringBuilder(); var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem)); privateKeyPemWriter.WriteObject(certificate); privateKeyPemWriter.WriteObject(subjectKeyPair.Private); privateKeyPemWriter.Writer.Flush(); pemValue = privateKeyPem.ToString(); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.ImportParameters(rsaParameters); x509.PrivateKey = rsaKey; // Generating Random Numbers var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; var rnd = new Random(); var result = new string( Enumerable.Repeat(chars, 15) .Select(s => s[rnd.Next(s.Length)]) .ToArray()); password = result; cerData = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password); }
public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations, CspParameters cspParams) {}
static int Main(string[] args) { Header(); if (args.Length < 1) { Help(); return(1); } CspParameters csp = new CspParameters(); string pvkFilename = null; string spcFilename = null; int timestampRetry = 1; int timestampDelay = 0; bool sign = true; // to be signed string tbsFilename = args [args.Length - 1]; AuthenticodeFormatter af = new AuthenticodeFormatter(); int i = 0; while (i < args.Length - 1) { switch (args[i++]) { case "-spc": spcFilename = args [i++]; break; case "-v": pvkFilename = args [i++]; break; case "-a": af.Hash = args [i++]; break; case "-$": string auth = args [i++].ToLower(); switch (auth) { case "individual": af.Authority = Authority.Individual; break; case "commercial": af.Authority = Authority.Commercial; break; default: Console.WriteLine("Unknown authority {0}", auth); return(1); } break; case "-n": af.Description = args [i++]; break; case "-i": af.Url = new Uri(args [i++]); break; // timestamp options case "-t": af.TimestampUrl = new Uri(args [i++]); break; case "-tr": timestampRetry = Convert.ToInt32(args [i++]); break; case "-tw": timestampDelay = Convert.ToInt32(args [i++]) * 1000; break; case "-x": // only timestamp sign = false; break; // CSP provider options case "-k": csp.KeyContainerName = args [i++]; break; case "-p": csp.ProviderName = args [i++]; break; case "-y": csp.ProviderType = Convert.ToInt32(args [i++]); break; case "-ky": string key = args [i++]; switch (key) { case "signature": csp.KeyNumber = 0; break; case "exchange": csp.KeyNumber = 0; break; default: csp.KeyNumber = Convert.ToInt32(key); break; } break; case "-r": string location = args [i++]; switch (location) { case "localMachine": csp.Flags = CspProviderFlags.UseMachineKeyStore; break; case "currentUser": csp.Flags = CspProviderFlags.UseDefaultKeyContainer; break; default: Console.WriteLine("Unknown location {0}", location); return(1); } break; // unsupported options case "-j": case "-jp": Console.WriteLine("Unsupported option {0}", args[i - 1]); return(1); // other options case "-?": Help(); return(0); } } // no need to continue if we can't find the assembly // to be signed (and/or timestamped) if (!File.Exists(tbsFilename)) { Console.WriteLine("Couldn't find {0}.", tbsFilename); return(1); } if (sign) { RSA rsa = GetPrivateKey(pvkFilename, csp); if (rsa == null) { Console.WriteLine("No private key available to sign the assembly."); return(1); } af.RSA = rsa; X509CertificateCollection certs = GetCertificates(spcFilename); if ((certs == null) || (certs.Count == 0)) { Console.WriteLine("No certificates available to sign the assembly."); return(1); } af.Certificates.AddRange(certs); if (!af.Sign(tbsFilename)) { Console.WriteLine("Couldn't sign file '{0}'.", tbsFilename); return(1); } } else if (af.TimestampUrl != null) { bool ts = false; // only timestamp an already signed file for (int j = 0; j < timestampRetry && !ts; j++) { ts = af.Timestamp(tbsFilename); // wait (unless it's the last try) and retry if (!ts && (j < timestampRetry - 1)) { Console.WriteLine("Couldn't timestamp file '{0}', will retry in {1} ms", tbsFilename, timestampDelay); Thread.Sleep(timestampDelay); } } if (!ts) { Console.WriteLine("Couldn't timestamp file '{0}' after {1} retries.", tbsFilename, timestampRetry); return(1); } } else { Help(); return(1); } Console.WriteLine("Success"); return(0); }
// Generate a new rsa keypair public static void Keys(string publicKeyFileName, string privateKeyFileName) { // Variables CspParameters cspParams = null; RSACryptoServiceProvider rsaProvider = null; StreamWriter publicKeyFile = new StreamWriter(Path.Combine(@"C:\crypto\rsakeys", publicKeyFileName)); StreamWriter privateKeyFile = new StreamWriter(Path.Combine(@"C:\crypto\rsakeys", privateKeyFileName)); string publicKey = ""; string privateKey = ""; try { // Create a new key pair on target CSP cspParams = new CspParameters(); cspParams.ProviderType = 1; // PROV_RSA_FULL //cspParams.ProviderName; // CSP name cspParams.Flags = CspProviderFlags.UseArchivableKey; cspParams.KeyNumber = (int)KeyNumber.Exchange; rsaProvider = new RSACryptoServiceProvider(cspParams); // Export public key publicKey = rsaProvider.ToXmlString(false); // Write public key to file publicKeyFile.Write(publicKey); // Export private/public key pair privateKey = rsaProvider.ToXmlString(true); // Write private/public key pair to file privateKeyFile.Write(privateKey); //ToDo Logging } catch (Exception ex) { //ToDo Logging // Any errors? Show them } finally { // Do some clean up if needed if (publicKeyFile != null) { publicKeyFile.Close(); } if (privateKeyFile != null) { privateKeyFile.Close(); } } }
public static void NonExportable_Ephemeral() { CspParameters cspParameters = new CspParameters { Flags = CspProviderFlags.UseNonExportableKey, }; using (var rsa = new RSACryptoServiceProvider(cspParameters)) { // Ephemeral keys don't successfully request the exportable bit. Assert.ThrowsAny<CryptographicException>(() => rsa.CspKeyContainerInfo.Exportable); Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(true)); Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true)); } }
// This can be implemented with netcoreapp20 with the cert creation API. // * Open the parameters as RSACSP (RSA PKCS#1 signature was hard-coded in netfx) // * Which will fail on non-Windows // * Create a certificate with subject CN=CMS Signer Dummy Certificate // * Need to check against NetFx to find out what the NotBefore/NotAfter values are // * No extensions // // Since it would only work on Windows, it could also be just done as P/Invokes to // CertCreateSelfSignedCertificate on a split Windows/netstandard implementation. public CmsSigner(CspParameters parameters) => throw new PlatformNotSupportedException();
static void Main(string[] args) { ThreadPool.SetMinThreads(4, 4); ThreadPool.SetMaxThreads(8, 8); //----- CspParameters used in CryptService. CspParameters param = new CspParameters(); param.KeyContainerName = "ALAZ_ECHO_SERVICE"; RSACryptoServiceProvider serverKey = new RSACryptoServiceProvider(param); //----- Socket Server! OnEventDelegate FEvent = new OnEventDelegate(Event); SocketServer echoServer = new SocketServer(new EchoSocketService.EchoSocketService(FEvent)); echoServer.Delimiter = new byte[] { 0xAA, 0xFF }; echoServer.DelimiterType = DelimiterType.dtMessageTailExcludeOnReceive; echoServer.SocketBufferSize = 4096; echoServer.MessageBufferSize = 4096 * 4; echoServer.IdleCheckInterval = 60000; echoServer.IdleTimeOutValue = 120000; //----- Socket Listener! SocketListener listener = echoServer.AddListener("Commom Port - 8090", new IPEndPoint(IPAddress.Any, 8090)); listener.AcceptThreads = 3; listener.BackLog = 50; listener.CompressionType = CompressionType.ctNone; listener.EncryptType = EncryptType.etNone; listener.CryptoService = new EchoCryptService.EchoCryptService(); echoServer.Start(); Console.WriteLine("Started!"); Console.WriteLine("----------------------"); string s; do { int iot = 0; int wt = 0; s = Console.ReadLine(); if (s.Equals("g")) { ThreadPool.GetAvailableThreads(out wt, out iot); Console.WriteLine("IOT " + iot.ToString()); Console.WriteLine("WT " + wt.ToString()); } } while (s.Equals("g")); try { echoServer.Stop(); echoServer.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.Message); } echoServer = null; Console.WriteLine("Stopped!"); Console.WriteLine("----------------------"); Console.ReadLine(); }
/// <summary> /// Create an OSCA log file /// </summary> /// <param name="logFile">Pathname of log file</param> /// <param name="version">Log system version</param> /// <param name="cert">XML signing certificate</param> /// <param name="cspParam">CSP parameters for signing key</param> internal static void createLogFile(string logFile, string version, X509Certificate cert, CspParameters cspParam) { // Modified to allow cngCA to run without signatures XDocument log = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("CA Log File"), new XElement("OSCA", new XAttribute("version", version), new XElement("lastEvent", 0), new XElement("events") ) ); // Sign and save the file XmlSigning.SignXml(log, logFile, cert, cspParam); }
} // Main // Generate a new key pair static void Keys(string publicKeyFileName, string privateKeyFileName) { // Variables CspParameters cspParams = null; RSACryptoServiceProvider rsaProvider = null; StreamWriter publicKeyFile = null; StreamWriter privateKeyFile = null; string publicKey = ""; string privateKey = ""; try { // Create a new key pair on target CSP cspParams = new CspParameters(); cspParams.ProviderType = 1; // PROV_RSA_FULL //cspParams.ProviderName; // CSP name cspParams.Flags = CspProviderFlags.UseArchivableKey; cspParams.KeyNumber = (int)KeyNumber.Exchange; rsaProvider = new RSACryptoServiceProvider(cspParams); // Export public key publicKey = rsaProvider.ToXmlString(false); // Write public key to file publicKeyFile = File.CreateText(publicKeyFileName); publicKeyFile.Write(publicKey); // Export private/public key pair privateKey = rsaProvider.ToXmlString(true); // Write private/public key pair to file privateKeyFile = File.CreateText(privateKeyFileName); privateKeyFile.Write(privateKey); } catch (Exception ex) { // Any errors? Show them Console.WriteLine("Exception generating a new key pair! More info:"); Console.WriteLine(ex.Message); } finally { // Do some clean up if needed if (publicKeyFile != null) { publicKeyFile.Close(); } if (privateKeyFile != null) { privateKeyFile.Close(); } } } // Keys
static RSACryptoServiceProvider readRsaPrivate(byte[] data) { // From http://forums.l-space-design.com/blogs/day_of_the_developer/archive/2006/06/08/216.aspx string t = Str.AsciiEncoding.GetString(data); if (!t.StartsWith("-----BEGIN RSA PRIVATE KEY-----")) { throw new ArgumentException("Not an RSA Private Key"); } t = t.Substring("-----BEGIN RSA PRIVATE KEY-----".Length); t = t.Substring(0, t.IndexOf("----")); t = t.Replace("\r", "").Replace("\n", ""); byte[] byteArray = System.Convert.FromBase64String(t); System.IO.MemoryStream s = new MemoryStream(byteArray); BinaryReader binr = new BinaryReader(s, Str.AsciiEncoding); byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ byte bt = 0; ushort twobytes = 0; int elems = 0; RSAParameters result = new RSAParameters(); try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) { binr.ReadByte(); //advance 1 byte } else if (twobytes == 0x8230) { binr.ReadInt16(); //advance 2 bytes } else { return(null); } twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) //version number { return(null); } bt = binr.ReadByte(); if (bt != 0x00) { return(null); } //------ all private key components are Integer sequences ---- elems = getIntegerSize(binr); MODULUS = binr.ReadBytes(elems); elems = getIntegerSize(binr); E = binr.ReadBytes(elems); elems = getIntegerSize(binr); D = binr.ReadBytes(elems); elems = getIntegerSize(binr); P = binr.ReadBytes(elems); elems = getIntegerSize(binr); Q = binr.ReadBytes(elems); elems = getIntegerSize(binr); DP = binr.ReadBytes(elems); elems = getIntegerSize(binr); DQ = binr.ReadBytes(elems); elems = getIntegerSize(binr); IQ = binr.ReadBytes(elems); result.Modulus = MODULUS; result.Exponent = E; result.D = D; result.P = P; result.Q = Q; result.DP = DP; result.DQ = DQ; result.InverseQ = IQ; } catch (Exception) { return(null); } finally { binr.Close(); } CspParameters cp = new CspParameters(); cp.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cp); RSA.PersistKeyInCsp = false; RSA.ImportParameters(result); return(RSA); }
} // Encrypt // Decrypt a file static void Decrypt(string privateKeyFileName, string encryptedFileName, string plainFileName) { // Variables CspParameters cspParams = null; RSACryptoServiceProvider rsaProvider = null; StreamReader privateKeyFile = null; FileStream encryptedFile = null; StreamWriter plainFile = null; string privateKeyText = ""; string plainText = ""; byte[] encryptedBytes = null; byte[] plainBytes = null; try { // Select target CSP cspParams = new CspParameters(); cspParams.ProviderType = 1; // PROV_RSA_FULL //cspParams.ProviderName; // CSP name rsaProvider = new RSACryptoServiceProvider(cspParams); // Read private/public key pair from file privateKeyFile = File.OpenText(privateKeyFileName); privateKeyText = privateKeyFile.ReadToEnd(); // Import private/public key pair rsaProvider.FromXmlString(privateKeyText); // Read encrypted text from file encryptedFile = File.OpenRead(encryptedFileName); encryptedBytes = new byte[encryptedFile.Length]; encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length); // Decrypt text plainBytes = rsaProvider.Decrypt(encryptedBytes, false); // Write decrypted text to file plainFile = File.CreateText(plainFileName); plainText = Encoding.Unicode.GetString(plainBytes); plainFile.Write(plainText); } catch (Exception ex) { // Any errors? Show them Console.WriteLine("Exception decrypting file! More info:"); Console.WriteLine(ex.Message); } finally { // Do some clean up if needed if (privateKeyFile != null) { privateKeyFile.Close(); } if (encryptedFile != null) { encryptedFile.Close(); } if (plainFile != null) { plainFile.Close(); } } } // Decrypt
public static RSACryptoServiceProvider CreateRsaProviderFromPrivatePemKey(string pemPrivateKey) { // Extract base64 formated key var base64KeyStart = pemPrivateKey.IndexOf(RsaPrivateKeyHeader, StringComparison.Ordinal); var base64KeyEnd = pemPrivateKey.LastIndexOf(RsaPrivateKeyFooter, StringComparison.Ordinal); if (base64KeyStart < 0 || base64KeyEnd < 200) // TODO: Find better number { throw new Exception("Not a valied pem formated private key"); } var start = base64KeyStart + RsaPrivateKeyHeader.Length; var length = base64KeyEnd - start; var base64PemPrivateKey = Regex.Replace(pemPrivateKey.Substring(start, length), @"\r\n?|\n", ""); // Convert to RSACryptoServiceProvider var privateKeyBits = Convert.FromBase64String(base64PemPrivateKey); var cspPrms = new CspParameters { KeyContainerName = $"{Guid.NewGuid():N}", // Generate random name for key container Flags = CspProviderFlags.UseMachineKeyStore }; var rsa = new RSACryptoServiceProvider(cspPrms) { PersistKeyInCsp = false }; var rsaParameters = new RSAParameters(); using (var binaryReader = new BinaryReader(new MemoryStream(privateKeyBits))) { byte bt = 0; ushort twobytes = 0; twobytes = binaryReader.ReadUInt16(); if (twobytes == 0x8130) { binaryReader.ReadByte(); } else if (twobytes == 0x8230) { binaryReader.ReadInt16(); } else { throw new CryptoUtilsException("Unexpected value read binr.ReadUInt16()"); } twobytes = binaryReader.ReadUInt16(); if (twobytes != 0x0102) { throw new CryptoUtilsException("Unexpected version"); } bt = binaryReader.ReadByte(); if (bt != 0x00) { throw new CryptoUtilsException("Unexpected value read binr.ReadByte()"); } rsaParameters.Modulus = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); rsaParameters.Exponent = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); rsaParameters.D = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); rsaParameters.P = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); rsaParameters.Q = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); rsaParameters.DP = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); rsaParameters.DQ = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); rsaParameters.InverseQ = binaryReader.ReadBytes(GetIntegerSize(binaryReader)); } rsa.ImportParameters(rsaParameters); return(rsa); }
static int Main(string[] args) { // params and usage if (args.Length == 0 || args[0] == "?" || args[0] == "-?" || (args.Length != 2 && args.Length != 3)) { Console.WriteLine("By Honzajscz at 2019"); Console.WriteLine("Installs key pair from <pfx_infile> into a key container compatible for MSBuild."); Console.WriteLine("This utility is an alternative for command sn.exe -i <infile> <container>."); Console.WriteLine("It accepts password from command line and automatically generates a container name for <pxf_infile> if no container name is specified via the <container_name> argument."); Console.WriteLine(); Console.WriteLine("Usage:"); Console.WriteLine($"{Assembly.GetEntryAssembly().GetName().Name}.exe <pfx_infile> <pfx_password>"); Console.WriteLine($"{Assembly.GetEntryAssembly().GetName().Name}.exe <pfx_infile> <pfx_password> <container_name>"); Console.WriteLine(); return(-1); } string pfxPath = args[0]; string pfxPassword = args[1]; string pfxContainer = args.Length == 3 ? args[2] : ResolveKeySourceTask.ResolveAssemblyKey(pfxPath); if (ResolveKeySourceTask.IsContainerInstalled(pfxContainer)) { //Installs from infile in the specified key container. The key container resides in the strong name CSP. Console.Error.WriteLine($"The key pair is already installed in the strong name CSP key container '{pfxContainer}'."); Console.Error.WriteLine("To delete the key container run following command from the Developer Command Prompt:"); Console.Error.WriteLine($"sn.exe -d {pfxContainer}"); Console.Error.WriteLine(); Console.Error.WriteLine("To list all installed key containers run following command:"); Console.Error.WriteLine("certutil -csp \"Microsoft Strong Cryptographic Provider\" -key"); return(-2); } // open pfx and export its private key var pfxCert = new X509Certificate2(pfxPath, pfxPassword, X509KeyStorageFlags.Exportable); var pfxPrivateKey = pfxCert.PrivateKey as RSACryptoServiceProvider; var pfxCspBlob = pfxPrivateKey.ExportCspBlob(true); // create cryptographic service provider (CSP) and machine-wide persistent key container // more at https://stackoverflow.com/questions/2528186/what-exactly-is-a-key-container // and https://www.sysadmins.lv/blog-en/certutil-tips-and-tricks-query-cryptographic-service-providers-csp-and-ksp.aspx const string DotNetStrongSigningCSP = "Microsoft Strong Cryptographic Provider"; var cspParameters = new CspParameters(1, DotNetStrongSigningCSP, pfxContainer) { KeyNumber = (int)KeyNumber.Signature, // container used for signing Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseNonExportableKey }; using (var rsaCSP = new RSACryptoServiceProvider(cspParameters)) { rsaCSP.PersistKeyInCsp = true; rsaCSP.ImportCspBlob(pfxCspBlob); }; // output // This not an actual error - just avoiding output pollution. Console.Error.WriteLine($"The key pair has been installed into the strong name CSP key container '{pfxContainer}'."); // Write the container to the output Console.WriteLine(pfxContainer); return(0); }
public void ComputeSignature (CmsSigner signer, bool silent) { if (signer == null) throw new ArgumentNullException("signer"); if (ContentInfo.Content.Length == 0) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_Empty_Content")); if (SubjectIdentifierType.NoSignature == signer.SignerIdentifierType) { if (m_safeCryptMsgHandle != null && !m_safeCryptMsgHandle.IsInvalid) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer")); // First signer. Sign(signer, silent); return; } if (signer.Certificate == null) { if (silent) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound")); else signer.Certificate = PkcsUtils.SelectSignerCertificate(); } if (!signer.Certificate.HasPrivateKey) throw new CryptographicException(CAPI.NTE_NO_KEY); // CspParameters parameters = new CspParameters(); if (X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters) == false) throw new CryptographicException(SafeGetLastWin32Error()); KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) { // First signer. Sign(signer, silent); } else { // Co-signing. CoSign(signer, silent); } }
public static async Task <int> Sign(string fileName, IEnumerable <CommandOption> options) { var signOptions = SignOptions.FromOptions(fileName, options); X509Certificate2Collection includedCerts; var signingCert = signOptions.FindCert(out includedCerts); if (signingCert == null) { AnsiConsole.Error.WriteLine("Unable to find certificate that meets the specified criteria"); return(1); } AnsiConsole.Output.WriteLine("Signing file with: " + signingCert.SubjectName.CommonName()); // Load the private key if provided if (!string.IsNullOrEmpty(signOptions.CspName) && !string.IsNullOrEmpty(signOptions.KeyContainer)) { var parameters = new CspParameters() { ProviderType = 1, // PROV_RSA_FULL KeyNumber = (int)KeyNumber.Signature, ProviderName = signOptions.CspName, KeyContainerName = signOptions.KeyContainer }; signingCert.PrivateKey = new RSACryptoServiceProvider(parameters); } if (!signingCert.HasPrivateKey) { AnsiConsole.Error.WriteLine("Unable to find private key for certificate: " + signingCert.SubjectName.CommonName()); return(1); } // If the input file didn't provide any additional certs, set up a new collection var additionalCerts = new X509Certificate2Collection(); // Load any additional certs requested by the user if (!string.IsNullOrEmpty(signOptions.AddCertificatesFile)) { additionalCerts.Import(signOptions.AddCertificatesFile); } // Determine if we are signing a request or a file Signature sig = await Signature.TryDecodeAsync(fileName); if (sig == null) { sig = new Signature(SignaturePayload.Compute(fileName, Signature.DefaultDigestAlgorithmName)); } // Verify that the content is unsigned if (sig.IsSigned) { AnsiConsole.Error.WriteLine("File already signed: " + fileName); return(1); } // Sign the file sig.Sign(signingCert, includedCerts, additionalCerts); AnsiConsole.Output.WriteLine("Successfully signed."); if (!string.IsNullOrEmpty(signOptions.Timestamper)) { // Timestamp the signature AnsiConsole.Output.WriteLine("Transmitting signature to timestamping authority..."); sig.Timestamp(new Uri(signOptions.Timestamper), signOptions.TimestamperAlgorithm ?? Signature.DefaultDigestAlgorithmName); AnsiConsole.Output.WriteLine("Trusted timestamp applied to signature."); } // Write the signature AnsiConsole.Output.WriteLine("Signature saved to " + signOptions.Output); await sig.WriteAsync(signOptions.Output); return(0); }
public static void NamedKey_DefaultProvider() { const int KeySize = 2048; CspParameters cspParameters = new CspParameters { KeyContainerName = Guid.NewGuid().ToString(), }; using (new RsaKeyLifetime(cspParameters)) { byte[] privateBlob; string uniqueKeyContainerName; using (var rsa = new RSACryptoServiceProvider(KeySize, cspParameters)) { Assert.True(rsa.PersistKeyInCsp, "rsa.PersistKeyInCsp"); Assert.Equal(cspParameters.KeyContainerName, rsa.CspKeyContainerInfo.KeyContainerName); uniqueKeyContainerName = rsa.CspKeyContainerInfo.UniqueKeyContainerName; Assert.NotNull(uniqueKeyContainerName); Assert.NotEqual(string.Empty, uniqueKeyContainerName); privateBlob = rsa.ExportCspBlob(true); Assert.True(rsa.CspKeyContainerInfo.Exportable, "rsa.CspKeyContainerInfo.Exportable"); } // Fail if the key didn't persist cspParameters.Flags |= CspProviderFlags.UseExistingKey; using (var rsa = new RSACryptoServiceProvider(cspParameters)) { Assert.True(rsa.PersistKeyInCsp); Assert.Equal(KeySize, rsa.KeySize); Assert.Equal(uniqueKeyContainerName, rsa.CspKeyContainerInfo.UniqueKeyContainerName); byte[] blob2 = rsa.ExportCspBlob(true); Assert.Equal(privateBlob, blob2); } } }
public bool EnsureEnvironmentCertificatesPresence() { foreach (var storeEnvironmentCertificates in this.environmentCertificates) { StoreName storeName = storeEnvironmentCertificates.Key; TextLogger.LogInfo("Ensuring all environment certificates for certificate store {0}\\{1} are present in local environment.", StoreLocation.LocalMachine, storeName); int installedEnvironmentCertificates = 0; X509Store store = null; try { store = new X509Store(storeName, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); foreach (var environmentCertificateEntry in storeEnvironmentCertificates.Value) { bool environmentCertificateInstalled = false; X509Certificate2 environmentCertificate = environmentCertificateEntry.Value.Certificate; if (store.Certificates != null) { X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, environmentCertificate.Thumbprint, false); environmentCertificateInstalled = certificateCollection.Count > 0; } if (!environmentCertificateInstalled) { TextLogger.LogInfo( "{0} certificate with thumbprint {1}, subject {2} is being installed in certificate store {3}\\{4}.", environmentCertificate.HasPrivateKey ? "Private key" : "Public key", environmentCertificate.Thumbprint, environmentCertificate.Subject, StoreLocation.LocalMachine, storeName); store.Add(environmentCertificate); if (environmentCertificate.HasPrivateKey) { TextLogger.LogInfo( "Private key certificate with thumbprint {0}, subject {1} is being ACLed.", environmentCertificate.Thumbprint, environmentCertificate.Subject); // ACL private key part of a private key certificate to network service. RSACryptoServiceProvider cryptoServiceProvider = environmentCertificate.PrivateKey as RSACryptoServiceProvider; CspParameters cspParameters = new CspParameters(cryptoServiceProvider.CspKeyContainerInfo.ProviderType, cryptoServiceProvider.CspKeyContainerInfo.ProviderName, cryptoServiceProvider.CspKeyContainerInfo.KeyContainerName) { Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore, CryptoKeySecurity = cryptoServiceProvider.CspKeyContainerInfo.CryptoKeySecurity }; cspParameters.CryptoKeySecurity.AddAccessRule(new CryptoKeyAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null), CryptoKeyRights.FullControl | CryptoKeyRights.GenericRead, AccessControlType.Allow)); using (RSACryptoServiceProvider updatedCryptoServiceProvider = new RSACryptoServiceProvider(cspParameters)) { // Create a new RSACryptoServiceProvider with updated ACL rules to apply ACL changes. } } installedEnvironmentCertificates++; } } } catch (Exception e) { TextLogger.LogError("Failed to ensure all environment certificates for certificate store {0}\\{1} are present in local environment : {2}", StoreLocation.LocalMachine, storeName, e); return(false); } finally { if (store != null) { store.Close(); } } TextLogger.LogInfo("Certificate store {0}\\{1} : Successfully installed {2} environment certificates. All {3} environment certificates referred to in current configurations for the certificate store have been installed.", StoreLocation.LocalMachine, storeName, installedEnvironmentCertificates, storeEnvironmentCertificates.Value.Count); } return(true); }
internal RsaKeyLifetime(CspParameters cspParameters) { const CspProviderFlags CopyableFlags = CspProviderFlags.UseMachineKeyStore; _cspParameters = new CspParameters( cspParameters.ProviderType, cspParameters.ProviderName, cspParameters.KeyContainerName) { // If the test failed before creating the key, don't bother recreating it. Flags = (cspParameters.Flags & CopyableFlags) | CspProviderFlags.UseExistingKey, }; }
private unsafe void CounterSign(CmsSigner signer) { // Sanity check. Debug.Assert(signer != null); // CspParameters parameters = new CspParameters(); if (X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters) == false) { throw new CryptographicException(Marshal.GetLastWin32Error()); } KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); // Get the signer's index. uint index = (uint)PkcsUtils.GetSignerIndex(m_signedCms.GetCryptMsgHandle(), this, 0); // Create CMSG_SIGNER_ENCODE_INFO structure. SafeLocalAllocHandle pSignerEncodeInfo = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); SafeCryptProvHandle safeCryptProvHandle; CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer, out safeCryptProvHandle); try { // Marshal to unmanaged memory. Marshal.StructureToPtr(signerEncodeInfo, pSignerEncodeInfo.DangerousGetHandle(), false); // Counter sign. if (!CAPI.CryptMsgCountersign(m_signedCms.GetCryptMsgHandle(), index, 1, pSignerEncodeInfo.DangerousGetHandle())) { throw new CryptographicException(Marshal.GetLastWin32Error()); } // CAPI requires that the messge be re-encoded if any unauthenticated // attribute has been added. So, let's re-open it to decode to work // around this limitation. m_signedCms.ReopenToDecode(); } finally { Marshal.DestroyStructure(pSignerEncodeInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); pSignerEncodeInfo.Dispose(); // and don't forget to dispose of resources allocated for the structure. signerEncodeInfo.Dispose(); safeCryptProvHandle.Dispose(); } // Finally, add certs to bag of certs. PkcsUtils.AddCertsToMessage(m_signedCms.GetCryptMsgHandle(), m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); return; }
public Gost_R3410_2001_AsymmetricAlgorithm(CspParameters providerParameters) : base(providerParameters, DefaultKeySizeValue) { }
private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey, string signType) { byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading byte bt = 0; ushort twobytes = 0; int elems = 0; try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) { binr.ReadByte(); //advance 1 byte } else if (twobytes == 0x8230) { binr.ReadInt16(); //advance 2 bytes } else { return(null); } twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) //version number { return(null); } bt = binr.ReadByte(); if (bt != 0x00) { return(null); } //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); MODULUS = binr.ReadBytes(elems); elems = GetIntegerSize(binr); E = binr.ReadBytes(elems); elems = GetIntegerSize(binr); D = binr.ReadBytes(elems); elems = GetIntegerSize(binr); P = binr.ReadBytes(elems); elems = GetIntegerSize(binr); Q = binr.ReadBytes(elems); elems = GetIntegerSize(binr); DP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); DQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); IQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- CspParameters CspParameters = new CspParameters(); CspParameters.Flags = CspProviderFlags.UseMachineKeyStore; int bitLen = 1024; if ("RSA2".Equals(signType)) { bitLen = 2048; } RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(bitLen, CspParameters); RSAParameters RSAparams = new RSAParameters(); RSAparams.Modulus = MODULUS; RSAparams.Exponent = E; RSAparams.D = D; RSAparams.P = P; RSAparams.Q = Q; RSAparams.DP = DP; RSAparams.DQ = DQ; RSAparams.InverseQ = IQ; RSA.ImportParameters(RSAparams); return(RSA); } catch (Exception ex) { return(null); } finally { binr.Close(); } }
public CspKeyContainerInfo(CspParameters parameters) { throw new PlatformNotSupportedException(); }
static void Main(string[] args) { TcpListener server = new TcpListener(IPAddress.IPv6Any, 8080); TcpClient client = default(TcpClient); server.Start(); Console.WriteLine("Server has started..."); while (true) { client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); StreamReader reader = new StreamReader(stream); // Read 'intent' from client string intent = reader.ReadLine(); switch (intent) { case "Upload": string filename = decryptInfo(reader.ReadLine()); int size = Int32.Parse(reader.ReadLine()); string owner = decryptInfo(reader.ReadLine()); string share = decryptInfo(reader.ReadLine()); string originalfilename2 = reader.ReadLine(); Console.WriteLine("Encrypted filename: " + originalfilename2); string originalfilename = decryptInfo(originalfilename2); Console.WriteLine("Decrypted filename: " + originalfilename); string originalfileext = decryptInfo(reader.ReadLine()); string encryptedkey = reader.ReadLine(); string IV = reader.ReadLine(); uploadFiles(filename, size, share, owner, originalfilename, originalfileext, encryptedkey, IV); //stream.CopyTo(new FileStream(@"D:\filetransfer\" + filename, FileMode.Create, FileAccess.Write)); break; case "Retrieve": string retrievinguser = reader.ReadLine(); DataTable dt = retrieveFiles(retrievinguser); string xml = SerializeTableToString(dt); string userpubkey = getUserPubKey(retrievinguser); Console.WriteLine("pub key : " + userpubkey + "\n\n\n"); using (StreamWriter sw = new StreamWriter(stream)) { byte[] xmlarray = Encoding.UTF8.GetBytes(xml); byte[] key = new byte[32]; using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { rng.GetBytes(key); using (RijndaelManaged aes = new RijndaelManaged()) { aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.GenerateIV(); aes.Key = key; using (var mems = new MemoryStream()) { using (ICryptoTransform encryptor = aes.CreateEncryptor()) { using (var cryptostream = new CryptoStream(mems, encryptor, CryptoStreamMode.Write)) { cryptostream.Write(xmlarray, 0, xmlarray.Length); cryptostream.FlushFinalBlock(); using (RSACryptoServiceProvider rsaxml = new RSACryptoServiceProvider()) { byte[] encryptedxml = mems.ToArray(); rsaxml.FromXmlString(userpubkey); byte[] encryptedxmlkey = rsaxml.Encrypt(key, false); string base64xml = Convert.ToBase64String(encryptedxml); string base64key = Convert.ToBase64String(encryptedxmlkey); string base64IV = Convert.ToBase64String(aes.IV); sw.WriteLine(base64key); sw.WriteLine(base64IV); sw.WriteLine(base64xml); sw.Flush(); } } } } } } } break; case "Download": //Download files Console.WriteLine("Download request received"); string user = reader.ReadLine(); int filecount = Int32.Parse(reader.ReadLine()); Console.WriteLine("Downloading user: "******""; string owners = ""; string sharedGroups = ""; string pubkey = getUserPubKey(user); StreamWriter swd = new StreamWriter(stream); FileItem fi = new FileItem(); using (RSACryptoServiceProvider rsap = new RSACryptoServiceProvider()) { rsap.FromXmlString(pubkey); for (int i = 0; i < filecount; i++) { files = (reader.ReadLine()); owners = (reader.ReadLine()); sharedGroups = (reader.ReadLine()); fi = downloadFile(owners, files, sharedGroups); fi.EncKey = (decryptKey(owners, files, pubkey)); swd.WriteLine(Convert.ToBase64String(rsap.Encrypt(Encoding.UTF8.GetBytes(fi.hashedFilename), false))); swd.WriteLine(fi.IV); swd.WriteLine(Convert.ToBase64String(rsap.Encrypt(Encoding.UTF8.GetBytes(fi.Originalfilename), false))); swd.WriteLine(Convert.ToBase64String(rsap.Encrypt(Encoding.UTF8.GetBytes(fi.OriginalfileExt), false))); swd.WriteLine(fi.EncKey); swd.Flush(); addLogs(files, owners, user, sharedGroups); Console.WriteLine("Logs for {0} downloading {1} owned by {2} added successfully!", user, files, owners); } } break; case "Pubkey": Console.WriteLine("Server Pub Key request received"); CspParameters csp = new CspParameters(); csp.KeyContainerName = "EEKeys"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp); string pubkeyxml = rsa.ToXmlString(true); Console.WriteLine("Server Pub Key: " + pubkeyxml); using (StreamWriter streamwrite = new StreamWriter(stream)) { streamwrite.WriteLine(pubkeyxml); } break; case "Logs": //Retrieve name,owner,shared and use serializate dt to send back logs. string itemname = reader.ReadLine(); string itemgroup = reader.ReadLine(); string itemowner = reader.ReadLine(); string loguser = reader.ReadLine(); string loguserpubkey = getUserPubKey(loguser); string logxml = SerializeTableToString(retrieveLogs(itemname, itemowner, itemgroup)); Console.WriteLine(logxml); using (StreamWriter logsw = new StreamWriter(stream)) { byte[] xmlarray = Encoding.UTF8.GetBytes(logxml); byte[] key = new byte[32]; using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { rng.GetBytes(key); using (RijndaelManaged aes = new RijndaelManaged()) { aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.GenerateIV(); aes.Key = key; using (var mems = new MemoryStream()) { using (ICryptoTransform encryptor = aes.CreateEncryptor()) { using (var cryptostream = new CryptoStream(mems, encryptor, CryptoStreamMode.Write)) { cryptostream.Write(xmlarray, 0, xmlarray.Length); cryptostream.FlushFinalBlock(); using (RSACryptoServiceProvider rsaxml = new RSACryptoServiceProvider()) { byte[] encryptedxml = mems.ToArray(); rsaxml.FromXmlString(loguserpubkey); byte[] encryptedxmlkey = rsaxml.Encrypt(key, false); string base64xml = Convert.ToBase64String(encryptedxml); string base64key = Convert.ToBase64String(encryptedxmlkey); string base64IV = Convert.ToBase64String(aes.IV); logsw.WriteLine(base64key); logsw.WriteLine(base64IV); logsw.WriteLine(base64xml); logsw.Flush(); } } } } } } } break; } client.Close(); stream.Close(); } }
private T GetPrivateKey <T>(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm { if (!certificate.HasPrivateKey) { return(null); } SafeProvOrNCryptKeyHandle handle = GetCertificatePrivateKey( certificate, silent, preferNCrypt, out CryptKeySpec keySpec, out Exception exception); using (handle) { if (handle == null || handle.IsInvalid) { if (exception != null) { throw exception; } return(null); } if (keySpec == CryptKeySpec.CERT_NCRYPT_KEY_SPEC) { using (SafeNCryptKeyHandle keyHandle = new SafeNCryptKeyHandle(handle.DangerousGetHandle(), handle)) { CngKeyHandleOpenOptions options = CngKeyHandleOpenOptions.None; byte clrIsEphemeral = 0; Interop.NCrypt.ErrorCode errorCode = Interop.NCrypt.NCryptGetByteProperty(keyHandle, "CLR IsEphemeral", ref clrIsEphemeral, CngPropertyOptions.CustomProperty); if (errorCode == Interop.NCrypt.ErrorCode.ERROR_SUCCESS && clrIsEphemeral == 1) { options |= CngKeyHandleOpenOptions.EphemeralKey; } using (CngKey cngKey = CngKey.Open(keyHandle, options)) { if (typeof(T) == typeof(RSA)) { return((T)(object)new RSACng(cngKey)); } if (typeof(T) == typeof(ECDsa)) { return((T)(object)new ECDsaCng(cngKey)); } if (typeof(T) == typeof(DSA)) { return((T)(object)new DSACng(cngKey)); } Debug.Fail($"Unknown CNG key type request: {typeof(T).FullName}"); return(null); } } } // The key handle is for CAPI. // Our CAPI types don't allow usage from a handle, so we have a few choices: // 1) Extract the information we need to re-open the key handle. // 2) Re-implement {R|D}SACryptoServiceProvider // 3) PNSE. // 4) Defer to cert.Get{R|D}SAPrivateKey if not silent, throw otherwise. CspParameters cspParams = handle.GetProvParameters(); Debug.Assert((cspParams.Flags & CspProviderFlags.UseExistingKey) != 0); cspParams.KeyNumber = (int)keySpec; if (silent) { cspParams.Flags |= CspProviderFlags.NoPrompt; } if (typeof(T) == typeof(RSA)) { return((T)(object)new RSACryptoServiceProvider(cspParams)); } if (typeof(T) == typeof(DSA)) { return((T)(object)new DSACryptoServiceProvider(cspParams)); } Debug.Fail($"Unknown CAPI key type request: {typeof(T).FullName}"); return(null); } }
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 PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations, CspParameters cspParams) {}
// Constructors. public CspKeyContainerInfo(CspParameters parameters) { this.parameters = parameters; this.randomlyGenerated = true; }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, CspParameters cspParams) {}
/// <summary> /// Generates a new set of keys /// </summary> /// <returns></returns> public static RSAParameters CreateKeys() { CspParameters xCSP = new CspParameters(); RSACryptoServiceProvider xRSA = new RSACryptoServiceProvider(xCSP); return xRSA.ExportParameters(true); }
/// <summary> /// /// </summary> /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks> /// <param name="subjectName"></param> /// <returns></returns> public static void GenerateCertificate(string subjectName, DateTime expireOnUtc, byte[] issuingCertificate, string issuingCertificatePassword, out string password, out byte[] cerData, out byte[] pkcs12Data) { AsymmetricKeyParameter caPrivateKey; var caCert = ReadCertificateFromBytes(issuingCertificate, issuingCertificatePassword, out caPrivateKey); var caAuth = new AuthorityKeyIdentifierStructure(caCert); var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier()); // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; var rnd = new Random(); var result = new string( Enumerable.Repeat(chars, 15) .Select(s => s[rnd.Next(s.Length)]) .ToArray()); password = result; var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); var serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(caCert.IssuerDN); // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes()) gen.SetNotAfter(expireOnUtc); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA"); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); gen.SetPublicKey(subjectKeyPair.Public); //gen.AddExtension( // X509Extensions.ExtendedKeyUsage.Id, // false, // new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning })); //1.3.6.1.5.5.7.3.1 = server authentication //1.3.6.1.5.5.7.3.2 = client authentication //1.3.6.1.5.5.7.3.3 = code signing var certificate = gen.Generate(caPrivateKey); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.ImportParameters(rsaParameters); x509.PrivateKey = rsaKey; cerData = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password); }
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters);
private void RegisterSimpleButton_Click(object sender, EventArgs e) { string usernametxt = this.UsernameTextEdit.Text; string emailtxt = this.EmailTextEdit.Text; string passwordtxt = this.PwdTextEdit.Text; string sndpasswordtxt = this.SndPwdTextEdit.Text; bool checkflag = true; //验证用户名 if (String.IsNullOrEmpty(usernametxt)) { checkflag = false; XtraMessageBox.Show(String.Format("请输入用户名"), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (checkflag) { if (String.IsNullOrEmpty(emailtxt)) { checkflag = false; XtraMessageBox.Show(String.Format("请输入邮箱地址"), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { if (!checkEmail(emailtxt, out string tips)) { checkflag = false; XtraMessageBox.Show(tips, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } if (checkflag) { if (String.IsNullOrEmpty(passwordtxt)) { checkflag = false; XtraMessageBox.Show(String.Format("请输入密码"), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { if (passwordtxt != sndpasswordtxt) { checkflag = false; XtraMessageBox.Show(String.Format("两次密码不一致"), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } if (checkflag) { try { //检查结束 User newuser = new User() { Uid = emailtxt.Trim(), Name = usernametxt.Trim(), PwdHash = CommonHandle.sha256_hash(passwordtxt) }; CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = newuser.Uid; RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(2048, cspParams); newuser.PrivateKey = Convert.ToBase64String(RSAalg.ExportCspBlob(true)); newuser.PublicKey = Convert.ToBase64String(RSAalg.ExportCspBlob(false)); BaseDAL.InsertWithNoResult("InsertNewUser", newuser); if (XtraMessageBox.Show(String.Format("注册成功"), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { if (loginfrm != null) { loginfrm.Show(); this.Close(); } } } catch (Exception ex) { XtraMessageBox.Show(String.Format("注册失败" + ex.Message), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public static byte[] DecryptAndVerify(byte[] cipherData, string key, string rsaXmlPublicKey = null) { if (key == null) { throw new ArgumentNullException("key"); } if (cipherData == null) { throw new ArgumentNullException("cipherData"); } System.Diagnostics.Contracts.Contract.EndContractBlock(); byte[] rsaData; if (rsaXmlPublicKey != null) { using (var ms = new MemoryStream(cipherData)) { using (var br = new BinaryReader(ms)) { int rsaDataLength = br.ReadInt32(); int rsaSignDataLength = br.ReadInt32(); rsaData = br.ReadBytes(rsaDataLength); byte[] rsaSignData = br.ReadBytes(rsaSignDataLength); var csParameters = new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }; using (var rsa = new RSACryptoServiceProvider(RsaKeySize, csParameters)) { rsa.FromXmlString(rsaXmlPublicKey); if (!rsa.VerifyData(rsaData, CryptoConfig.MapNameToOID("MD5"), rsaSignData)) { throw new CryptographicException("Invalid signature for data"); } } } } } else { rsaData = cipherData; } using (var ms = new MemoryStream(rsaData, false)) { using (var br = new BinaryReader(ms)) { int dataLength = br.ReadInt32(); byte[] data = br.ReadBytes(dataLength); if (rsaXmlPublicKey == null) { int signLength = br.ReadInt32(); byte[] sign = br.ReadBytes(signLength); if (!Equals(GetSignature(data, key), sign)) { throw new CryptographicException("Invalid signature"); } } var plain = DecryptTDES(data, key, true); return(plain); } } }
public static void NamedKey_AlternateProvider() { const int KeySize = 512; CspParameters cspParameters = new CspParameters(PROV_RSA_FULL) { KeyContainerName = Guid.NewGuid().ToString(), }; using (new RsaKeyLifetime(cspParameters)) { byte[] privateBlob; string uniqueKeyContainerName; using (var rsa = new RSACryptoServiceProvider(KeySize, cspParameters)) { Assert.True(rsa.PersistKeyInCsp); Assert.Equal(PROV_RSA_FULL, rsa.CspKeyContainerInfo.ProviderType); privateBlob = rsa.ExportCspBlob(true); Assert.Equal(cspParameters.KeyContainerName, rsa.CspKeyContainerInfo.KeyContainerName); uniqueKeyContainerName = rsa.CspKeyContainerInfo.UniqueKeyContainerName; Assert.NotNull(uniqueKeyContainerName); Assert.NotEqual(string.Empty, uniqueKeyContainerName); } // Fail if the key didn't persist cspParameters.Flags |= CspProviderFlags.UseExistingKey; using (var rsa = new RSACryptoServiceProvider(cspParameters)) { Assert.True(rsa.PersistKeyInCsp); Assert.Equal(KeySize, rsa.KeySize); // Since we're specifying the provider explicitly it should still match. Assert.Equal(PROV_RSA_FULL, rsa.CspKeyContainerInfo.ProviderType); Assert.Equal(uniqueKeyContainerName, rsa.CspKeyContainerInfo.UniqueKeyContainerName); byte[] blob2 = rsa.ExportCspBlob(true); Assert.Equal(privateBlob, blob2); } } }
public CspKeyContainerInfo(CspParameters parameters) { throw GetPlatformNotSupported(); }
public static void NonExportable_Persisted() { CspParameters cspParameters = new CspParameters { KeyContainerName = Guid.NewGuid().ToString(), Flags = CspProviderFlags.UseNonExportableKey, }; using (new RsaKeyLifetime(cspParameters)) { using (var rsa = new RSACryptoServiceProvider(cspParameters)) { Assert.False(rsa.CspKeyContainerInfo.Exportable, "rsa.CspKeyContainerInfo.Exportable"); Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(true)); Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true)); } } }
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) { } }
static public DSA FromCapiPrivateKeyBlobDSA(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } DSAParameters dsap = new DSAParameters(); try { if ((blob[offset] != 0x07) || // PRIVATEKEYBLOB (0x07) (blob[offset + 1] != 0x02) || // Version (0x02) (blob[offset + 2] != 0x00) || // Reserved (word) (blob[offset + 3] != 0x00) || (ToUInt32LE(blob, offset + 8) != 0x32535344)) // DWORD magic { throw new CryptographicException("Invalid blob header"); } int bitlen = ToInt32LE(blob, offset + 12); int bytelen = bitlen >> 3; int pos = offset + 16; dsap.P = new byte[bytelen]; Buffer.BlockCopy(blob, pos, dsap.P, 0, bytelen); Array.Reverse(dsap.P); pos += bytelen; dsap.Q = new byte[20]; Buffer.BlockCopy(blob, pos, dsap.Q, 0, 20); Array.Reverse(dsap.Q); pos += 20; dsap.G = new byte[bytelen]; Buffer.BlockCopy(blob, pos, dsap.G, 0, bytelen); Array.Reverse(dsap.G); pos += bytelen; dsap.X = new byte[20]; Buffer.BlockCopy(blob, pos, dsap.X, 0, 20); Array.Reverse(dsap.X); pos += 20; dsap.Counter = ToInt32LE(blob, pos); pos += 4; dsap.Seed = new byte[20]; Buffer.BlockCopy(blob, pos, dsap.Seed, 0, 20); Array.Reverse(dsap.Seed); pos += 20; } catch (Exception e) { throw new CryptographicException("Invalid blob.", e); } #if NET_2_1 DSA dsa = (DSA)DSA.Create(); dsa.ImportParameters(dsap); #else DSA dsa = null; try { dsa = (DSA)DSA.Create(); dsa.ImportParameters(dsap); } catch (CryptographicException ce) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 try { CspParameters csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; dsa = new DSACryptoServiceProvider(csp); dsa.ImportParameters(dsap); } catch { // rethrow original, not the later, exception if this fails throw ce; } } #endif return(dsa); }
internal static bool GetPrivateKeyInfo(System.Security.Cryptography.SafeCertContextHandle safeCertContext, ref CspParameters parameters) { SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle; uint pcbData = 0; if (!CAPISafe.CertGetCertificateContextProperty(safeCertContext, 2, invalidHandle, ref pcbData)) { if (Marshal.GetLastWin32Error() != -2146885628) { throw new CryptographicException(Marshal.GetLastWin32Error()); } return(false); } invalidHandle = CAPI.LocalAlloc(0, new IntPtr((long)pcbData)); if (!CAPISafe.CertGetCertificateContextProperty(safeCertContext, 2, invalidHandle, ref pcbData)) { if (Marshal.GetLastWin32Error() != -2146885628) { throw new CryptographicException(Marshal.GetLastWin32Error()); } return(false); } CAPIBase.CRYPT_KEY_PROV_INFO crypt_key_prov_info = (CAPIBase.CRYPT_KEY_PROV_INFO)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(CAPIBase.CRYPT_KEY_PROV_INFO)); parameters.ProviderName = crypt_key_prov_info.pwszProvName; parameters.KeyContainerName = crypt_key_prov_info.pwszContainerName; parameters.ProviderType = (int)crypt_key_prov_info.dwProvType; parameters.KeyNumber = (int)crypt_key_prov_info.dwKeySpec; parameters.Flags = ((crypt_key_prov_info.dwFlags & 0x20) == 0x20) ? CspProviderFlags.UseMachineKeyStore : CspProviderFlags.NoFlags; invalidHandle.Dispose(); return(true); }
public CmsSigner (CspParameters parameters) : this () { }
static public RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } try { if ((blob[offset] != 0x06) || // PUBLICKEYBLOB (0x06) (blob[offset + 1] != 0x02) || // Version (0x02) (blob[offset + 2] != 0x00) || // Reserved (word) (blob[offset + 3] != 0x00) || (ToUInt32LE(blob, offset + 8) != 0x31415352)) // DWORD magic = RSA1 { throw new CryptographicException("Invalid blob header"); } // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...) // int algId = ToInt32LE (blob, offset+4); // DWORD bitlen int bitLen = ToInt32LE(blob, offset + 12); // DWORD public exponent RSAParameters rsap = new RSAParameters(); rsap.Exponent = new byte[3]; rsap.Exponent[0] = blob[offset + 18]; rsap.Exponent[1] = blob[offset + 17]; rsap.Exponent[2] = blob[offset + 16]; int pos = offset + 20; // BYTE modulus[rsapubkey.bitlen/8]; int byteLen = (bitLen >> 3); rsap.Modulus = new byte[byteLen]; Buffer.BlockCopy(blob, pos, rsap.Modulus, 0, byteLen); Array.Reverse(rsap.Modulus); #if NET_2_1 RSA rsa = RSA.Create(); rsa.ImportParameters(rsap); #else RSA rsa = null; try { rsa = RSA.Create(); rsa.ImportParameters(rsap); } catch (CryptographicException) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 CspParameters csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; rsa = new RSACryptoServiceProvider(csp); rsa.ImportParameters(rsap); } #endif return(rsa); } catch (Exception e) { throw new CryptographicException("Invalid blob.", e); } }
internal CspKeyContainerInfo(CspParameters parameters, bool random) { this.parameters = parameters; this.randomlyGenerated = random; }
static public RSA FromCapiPrivateKeyBlob(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } RSAParameters rsap = new RSAParameters(); try { if ((blob[offset] != 0x07) || // PRIVATEKEYBLOB (0x07) (blob[offset + 1] != 0x02) || // Version (0x02) (blob[offset + 2] != 0x00) || // Reserved (word) (blob[offset + 3] != 0x00) || (ToUInt32LE(blob, offset + 8) != 0x32415352)) // DWORD magic = RSA2 { throw new CryptographicException("Invalid blob header"); } // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...) // int algId = ToInt32LE (blob, offset+4); // DWORD bitlen int bitLen = ToInt32LE(blob, offset + 12); // DWORD public exponent byte[] exp = new byte[4]; Buffer.BlockCopy(blob, offset + 16, exp, 0, 4); Array.Reverse(exp); rsap.Exponent = Trim(exp); int pos = offset + 20; // BYTE modulus[rsapubkey.bitlen/8]; int byteLen = (bitLen >> 3); rsap.Modulus = new byte[byteLen]; Buffer.BlockCopy(blob, pos, rsap.Modulus, 0, byteLen); Array.Reverse(rsap.Modulus); pos += byteLen; // BYTE prime1[rsapubkey.bitlen/16]; int byteHalfLen = (byteLen >> 1); rsap.P = new byte[byteHalfLen]; Buffer.BlockCopy(blob, pos, rsap.P, 0, byteHalfLen); Array.Reverse(rsap.P); pos += byteHalfLen; // BYTE prime2[rsapubkey.bitlen/16]; rsap.Q = new byte[byteHalfLen]; Buffer.BlockCopy(blob, pos, rsap.Q, 0, byteHalfLen); Array.Reverse(rsap.Q); pos += byteHalfLen; // BYTE exponent1[rsapubkey.bitlen/16]; rsap.DP = new byte[byteHalfLen]; Buffer.BlockCopy(blob, pos, rsap.DP, 0, byteHalfLen); Array.Reverse(rsap.DP); pos += byteHalfLen; // BYTE exponent2[rsapubkey.bitlen/16]; rsap.DQ = new byte[byteHalfLen]; Buffer.BlockCopy(blob, pos, rsap.DQ, 0, byteHalfLen); Array.Reverse(rsap.DQ); pos += byteHalfLen; // BYTE coefficient[rsapubkey.bitlen/16]; rsap.InverseQ = new byte[byteHalfLen]; Buffer.BlockCopy(blob, pos, rsap.InverseQ, 0, byteHalfLen); Array.Reverse(rsap.InverseQ); pos += byteHalfLen; // ok, this is hackish but CryptoAPI support it so... // note: only works because CRT is used by default // http://bugzilla.ximian.com/show_bug.cgi?id=57941 rsap.D = new byte[byteLen]; // must be allocated if (pos + byteLen + offset <= blob.Length) { // BYTE privateExponent[rsapubkey.bitlen/8]; Buffer.BlockCopy(blob, pos, rsap.D, 0, byteLen); Array.Reverse(rsap.D); } } catch (Exception e) { throw new CryptographicException("Invalid blob.", e); } #if NET_2_1 RSA rsa = RSA.Create(); rsa.ImportParameters(rsap); #else RSA rsa = null; try { rsa = RSA.Create(); rsa.ImportParameters(rsap); } catch (CryptographicException ce) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 try { CspParameters csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; rsa = new RSACryptoServiceProvider(csp); rsa.ImportParameters(rsap); } catch { // rethrow original, not the later, exception if this fails throw ce; } } #endif return(rsa); }
public CspKeyContainerInfo(CspParameters parameters);
/// <summary> /// This helper function parses an RSA private key using the ASN.1 format /// </summary> /// <param name="privateKeyBytes">Byte array containing PEM string of private key.</param> /// <returns>An instance of <see cref="RSACryptoServiceProvider"/> rapresenting the requested private key. /// Null if method fails on retriving the key.</returns> public static RSACryptoServiceProvider DecodeRsaPrivateKey(byte[] privateKeyBytes) { MemoryStream ms = new MemoryStream(privateKeyBytes); BinaryReader rd = new BinaryReader(ms); try { byte byteValue; ushort shortValue; shortValue = rd.ReadUInt16(); switch (shortValue) { case 0x8130: // If true, data is little endian since the proper logical seq is 0x30 0x81 rd.ReadByte(); //advance 1 byte break; case 0x8230: rd.ReadInt16(); //advance 2 bytes break; default: Debug.Assert(false); // Improper ASN.1 format return(null); } shortValue = rd.ReadUInt16(); if (shortValue != 0x0102) // (version number) { Debug.Assert(false); // Improper ASN.1 format, unexpected version number return(null); } byteValue = rd.ReadByte(); if (byteValue != 0x00) { Debug.Assert(false); // Improper ASN.1 format return(null); } // The data following the version will be the ASN.1 data itself, which in our case // are a sequence of integers. // In order to solve a problem with instancing RSACryptoServiceProvider // via default constructor on .net 4.0 this is a hack CspParameters parms = new CspParameters(); parms.Flags = CspProviderFlags.NoFlags; parms.KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant(); parms.ProviderType = ((Environment.OSVersion.Version.Major > 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1))) ? 0x18 : 1; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(parms); RSAParameters rsAparams = new RSAParameters(); rsAparams.Modulus = rd.ReadBytes(Helpers.DecodeIntegerSize(rd)); // Argh, this is a pain. From emperical testing it appears to be that RSAParameters doesn't like byte buffers that // have their leading zeros removed. The RFC doesn't address this area that I can see, so it's hard to say that this // is a bug, but it sure would be helpful if it allowed that. So, there's some extra code here that knows what the // sizes of the various components are supposed to be. Using these sizes we can ensure the buffer sizes are exactly // what the RSAParameters expect. Thanks, Microsoft. RSAParameterTraits traits = new RSAParameterTraits(rsAparams.Modulus.Length * 8); rsAparams.Modulus = Helpers.AlignBytes(rsAparams.Modulus, traits.size_Mod); rsAparams.Exponent = Helpers.AlignBytes(rd.ReadBytes(Helpers.DecodeIntegerSize(rd)), traits.size_Exp); rsAparams.D = Helpers.AlignBytes(rd.ReadBytes(Helpers.DecodeIntegerSize(rd)), traits.size_D); rsAparams.P = Helpers.AlignBytes(rd.ReadBytes(Helpers.DecodeIntegerSize(rd)), traits.size_P); rsAparams.Q = Helpers.AlignBytes(rd.ReadBytes(Helpers.DecodeIntegerSize(rd)), traits.size_Q); rsAparams.DP = Helpers.AlignBytes(rd.ReadBytes(Helpers.DecodeIntegerSize(rd)), traits.size_DP); rsAparams.DQ = Helpers.AlignBytes(rd.ReadBytes(Helpers.DecodeIntegerSize(rd)), traits.size_DQ); rsAparams.InverseQ = Helpers.AlignBytes(rd.ReadBytes(Helpers.DecodeIntegerSize(rd)), traits.size_InvQ); rsa.ImportParameters(rsAparams); return(rsa); } catch (Exception) { Debug.Assert(false); return(null); } finally { rd.Close(); } }
public RSACryptoServiceProvider(CspParameters parameters);
internal CspKeyContainerInfo(CspParameters parameters, bool randomKeyContainer) { throw GetPlatformNotSupported(); }