// Sign an XML file and save the signature in a new file. This method does not // save the public key within the XML file. This file cannot be verified unless // the verifying code has the key with which it was signed. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key) { // Create a new XML document. XmlDocument doc = new XmlDocument(); // Load the passed XML file using its name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); if (doc.FirstChild is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); }
public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; }
public override void SetKey(AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException(nameof(key)); _rsaKey = (RSA)key; }
public void DecodeTest() { RSA rsa = new RSA(); var data = rsa.Decode(@"<RSAKeyValue><Modulus>nX8JqOtKsttNSx5XMxQ8UIprhvbbXy3yTMU04S69ZInQYFUFHas1HWEp26QUL4LIJ6CQ+698r12KbDZh7MOT7HV3Ia/aQ34Oge7AVOX0Y0E+95f7gxcb9pllsUD2lFos/FW0LuoBicxwFojcLuuc3tUoElD2oGFZ2OusBoDjEMk=</Modulus><Exponent>AQAB</Exponent><P>zf5IwDrilxz7IZCkdDvgKHlRDg22QRgD5RoCR4HmTxD6nbWESXBCdXUW5H8CgSgEJoYL4OJ4NSa3LUMnEiTZWQ==</P><Q>w7rXm3C7IS6NKoD1zrFF/wNuBr+esfsysu7XXAGxTrSt4QjSNCv1cWVYuCbSP4HPg5tor1XfUKldiTSyVoOU8Q==</Q><DP>Tmv+WmCQnyMDYHXmhfG9lusItqb1ubZg1TmfoIWNnpBCOQQ/xo2cX4ciHf9UfsMzQU9K+mR9iw6gMfUczMWGkQ==</DP><DQ>r+rDlEKq/fTQDg6gXyh3p+9WOZyKLp9+ftIqH9ipmvrLeQGrpBaKYGPdbI3/0/KBJ2FLoqNEtkOy/Pmu/BEBkQ==</DQ><InverseQ>brHt8NacSwbVIEshmrfaXoIuIirTfV2aP4hPmVvs4mQXDwRTZpv5oabczdtwyYFMKm2yWTo+OtpB9renIJ4oog==</InverseQ><D>WdF8MdBV3mCA2Qkpk6DDsO7v2Z1oiARM/Ykt2gnsyqxpoLZ732qnNOUXmQIe3OWJvkesx0xSIDSJX6M3/22eKsPMtTdMDxAUXIdxfFDDLQ5GnDH7oSa9srpUN0a8r/PGPaMGu3E96xGyYequKIf76W+VK1wjaKuDCtmIsvrxXYE=</D></RSAKeyValue>", "ctTiZYcYrYCczhYYq7smP1S32biNPDjxHA9hBJ0JVvPSCBoO+LV8zd/eOTXbL1m3r1+0l3PjlYd28WqnwP7Hsjcj1FfEOvlu/KmfKlk2o+DtdCTrFXhrM8v2HxLsXjdRH4g+dAUND2DwXXRxVP7c2YCNyrsU/wznIMwIBZKbBMk="); Assert.IsTrue(data == "你好,yz"); }
public virtual ANSYSWriter GeneraAnsysWriter(string particulaName,RSA owner) { ANSYSWriter ansysReturn = null; tempInfo = pinfo.GetInfoParticulas(particulaName); assem = GestorEnsamblados.GetAssemblyByName(tempInfo.EnsambladoDibujable, tempInfo.PathDibujable); ansysReturn=(ANSYSWriter)assem.CreateInstance(tempInfo.AnsysWriterName, true, BindingFlags.CreateInstance, null, new object[] {owner}, null, null); return ansysReturn; }
public mainForm() { aes = new AES(); rsa = new RSA(); encoding = new UTF8Encoding(); InitializeComponent(); cmbEncryptionType.SelectedIndex = 0; }
public ANSYSWriter(RSA rsaTarget) { rsa = rsaTarget; if(!Directory.Exists(Application.StartupPath+"\\ANSYSOut")) Directory.CreateDirectory(Application.StartupPath+"\\ANSYSOut"); path=Application.StartupPath+"\\ANSYSOut"; fileName="batch.txt"; datosParametro=true; }
public HabboCrypto(BigInteger n, BigInteger e, BigInteger d) { this.DH = new DiffieHellman(200); this.RSA = new RSA(n, e, d, 0, 0, 0, 0, 0); this.RC4 = new RC4(); this.Initialized = false; }
static void Main(string[] args) { RSA rsa = new RSA(); int input = 98; uint ASCII = Convert.ToUInt32((uint)input); Console.WriteLine("Przed: " + ASCII); uint encrypted = rsa.encrypt(ASCII); Console.WriteLine("Zakodowane: " + encrypted); ASCII = rsa.decrpyt(encrypted); Console.WriteLine("Odkodowane: " + ASCII); Console.ReadKey(); }
public void GenerateKeyTest() { RSA rsa = new RSA(); var key = rsa.GenerateKey(); // 每次生成不一样,此处指记录执行单元测试时的key //publickey //<RSAKeyValue><Modulus>nX8JqOtKsttNSx5XMxQ8UIprhvbbXy3yTMU04S69ZInQYFUFHas1HWEp26QUL4LIJ6CQ+698r12KbDZh7MOT7HV3Ia/aQ34Oge7AVOX0Y0E+95f7gxcb9pllsUD2lFos/FW0LuoBicxwFojcLuuc3tUoElD2oGFZ2OusBoDjEMk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue> //privatekey //<RSAKeyValue><Modulus>nX8JqOtKsttNSx5XMxQ8UIprhvbbXy3yTMU04S69ZInQYFUFHas1HWEp26QUL4LIJ6CQ+698r12KbDZh7MOT7HV3Ia/aQ34Oge7AVOX0Y0E+95f7gxcb9pllsUD2lFos/FW0LuoBicxwFojcLuuc3tUoElD2oGFZ2OusBoDjEMk=</Modulus><Exponent>AQAB</Exponent><P>zf5IwDrilxz7IZCkdDvgKHlRDg22QRgD5RoCR4HmTxD6nbWESXBCdXUW5H8CgSgEJoYL4OJ4NSa3LUMnEiTZWQ==</P><Q>w7rXm3C7IS6NKoD1zrFF/wNuBr+esfsysu7XXAGxTrSt4QjSNCv1cWVYuCbSP4HPg5tor1XfUKldiTSyVoOU8Q==</Q><DP>Tmv+WmCQnyMDYHXmhfG9lusItqb1ubZg1TmfoIWNnpBCOQQ/xo2cX4ciHf9UfsMzQU9K+mR9iw6gMfUczMWGkQ==</DP><DQ>r+rDlEKq/fTQDg6gXyh3p+9WOZyKLp9+ftIqH9ipmvrLeQGrpBaKYGPdbI3/0/KBJ2FLoqNEtkOy/Pmu/BEBkQ==</DQ><InverseQ>brHt8NacSwbVIEshmrfaXoIuIirTfV2aP4hPmVvs4mQXDwRTZpv5oabczdtwyYFMKm2yWTo+OtpB9renIJ4oog==</InverseQ><D>WdF8MdBV3mCA2Qkpk6DDsO7v2Z1oiARM/Ykt2gnsyqxpoLZ732qnNOUXmQIe3OWJvkesx0xSIDSJX6M3/22eKsPMtTdMDxAUXIdxfFDDLQ5GnDH7oSa9srpUN0a8r/PGPaMGu3E96xGyYequKIf76W+VK1wjaKuDCtmIsvrxXYE=</D></RSAKeyValue> Assert.IsTrue(key != null); }
public RSADibujable(RSAConfiguration config,ParticulaInfo pInfo,ITracker track) { aleatpart=(bool)config.Valores["colorParticulaAleatorio"]; showNumber=(bool)config.Valores["mostrarNumeros"]; colorParticula=(float[])config.Valores["colorParticulas"]; idVisualizarPlanesOn=Gl.glGenLists(1); idVisualizarPlanesOff=Gl.glGenLists(1); xmlreader = new XmlParticulaReader((string)config.Valores["particulaXml"]); //ParticulaInfo xmlInfo = pInfo; rsa=new GestorAlgoritmo().CreaRSA(config,pInfo,track); // if(((string)config.Valores["rsaClase"])=="RSAAdvanced") // { // if((((string)config.Valores["parametroVariable"])=="cantidadParticulas")) // { // rsa = new RSAAdvanced((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],(int)config.Valores["cantidadParticulas"], pInfo,track); // } // else // { // if(((object[])config.Valores["parametros"]).Length!=pInfo.InfoParametro.Cantidad)throw new Exception("Error"); // object[] auxArray=(object[])config.Valores["parametros"]; // rsa = new RSAAdvanced((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],auxArray, pInfo,track); // } // } // else // { // if((((string)config.Valores["parametroVariable"])=="cantidadParticulas")) // { // rsa=new RSA((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],(int)config.Valores["cantidadParticulas"], pInfo,track); // } // else // { // if(((object[])config.Valores["parametros"]).Length!=pInfo.InfoParametro.Cantidad)throw new Exception("Error"); // object[] auxArray=(object[])config.Valores["parametros"]; // rsa = new RSA((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],auxArray, pInfo,track); // } // } spheresInBox =(bool)config.Valores["spheresInBox"]; gestorDib = new GestorDibujables(xmlreader); ParticulaDibujable.SetOwner(this); NumerosDibujables.SetOwner(this); cuboDib = new CuboDibujable(this, (float[])config.Valores["colorCubo"], new float[] { 0, 0, 0, 0 }); planosAClipear = new double[6][] { new double[4] { 1, 0, 0, rsa.Cubo.PuntoInicial.X }, new double[4] { 0, 1, 0, rsa.Cubo.PuntoInicial.Y }, new double[4] { 0, 0, 1, rsa.Cubo.PuntoInicial.Z }, new double[4] { -1, 0, 0, rsa.Cubo.PuntoInicial.X + rsa.Cubo.Lado }, new double[4] { 0, -1, 0, rsa.Cubo.PuntoInicial.Y + rsa.Cubo.Lado }, new double[4] { 0, 0, -1, rsa.Cubo.PuntoInicial.Z + rsa.Cubo.Lado } }; numdib = new NumerosDibujables[rsa.particulas.Length]; ansyswriter = gestorDib.GeneraAnsysWriter(pInfo.Nombre, this.rsa); this.Recompile(); }
// Sign an XML file.This document cannot be verified unless the verifying code has the key with which it was signed. public static void SignXml(XmlDocument doc, RSA key) { // Create a SignedXml object SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document signedXml.KeyInfo = new KeyInfo(); signedXml.KeyInfo.AddClause(new RSAKeyValue(key)); signedXml.SigningKey = key; // Create a reference to be signed Reference reference = new Reference(""); // reference.Uri = ""; // Add an enveloped transformation to the reference XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Set the KeyInfo to the SignedXml object // KeyInfo ki = new KeyInfo(); // ki.AddClause(new RSAKeyValue(key)); // signedXml.SigningKey = key; // signedXml.KeyInfo = ki; // Add the reference to the SignedXml object signedXml.AddReference(reference); // Compute the signature signedXml.ComputeSignature(); // Get the XML representation of the signature and save it to an XmlElement object. // XmlElement xmlDigitalSignature = signedXml.GetXml(); // Append the element to the XML document // doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); doc.DocumentElement.PrependChild(signedXml.GetXml()); }
private static void RSAEncrypt2() { // RSA examples RSA rsa = new RSA(); RSACryptoServiceProvider serviceProvider = new RSACryptoServiceProvider(); //Export the key information to an RSAParameters object. //Pass false to export the public key information or pass //true to export public and private key information. //RSAParameters RSAParams = RSA.ExportParameters(false); //Encrypt data UnicodeEncoding bytConvertor = new UnicodeEncoding(); byte[] plainData = bytConvertor.GetBytes("Sample data"); byte[] enData = rsa.Encrypt(plainData, serviceProvider.ExportParameters(false)); Console.WriteLine("Encrypted Output: {0}", bytConvertor.GetString(enData)); byte[] deData = rsa.Decrypt(enData, serviceProvider.ExportParameters(true)); Console.WriteLine("Decrypted Output: {0}", bytConvertor.GetString(deData)); }
// Verify the signature of an XML file against an asymmetric // algorithm and return the result. public static Boolean VerifyXml(XmlDocument Doc, RSA Key) { // Check arguments. if (Doc == null) throw new ArgumentException("Doc"); if (Key == null) throw new ArgumentException("Key"); // Create a new SignedXml object and pass it // the XML document class. SignedXml signedXml = new SignedXml(Doc); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = Doc.GetElementsByTagName("Signature"); // Throw an exception if no signature was found. if (nodeList.Count <= 0) { throw new CryptographicException("Verification failed: No Signature was found in the document."); } // This example only supports one signature for // the entire XML document. Throw an exception // if more than one signature was found. if (nodeList.Count >= 2) { throw new CryptographicException("Verification failed: More that one signature was found for the document."); } // Load the first <signature> node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(Key); }
public RSAKeyValue (RSA key) { rsa = key; }
/********************* * Encryption methods * Lifted from: * http://www.go-mono.com/docs/index.aspx?link=M%3aSystem.Security.Cryptography.RSACryptoServiceProvider.Encrypt(System.Byte%5b%5d%2cSystem.Boolean) * http://www.go-mono.com/docs/index.aspx?link=M%3aSystem.Security.Cryptography.RSACryptoServiceProvider.Decrypt(System.Byte%5b%5d%2cSystem.Boolean) * respectively *********************/ private byte[] Encrypt(RSA rsa, byte[] input) { // by default this will create a 128 bits AES (Rijndael) object SymmetricAlgorithm sa = SymmetricAlgorithm.Create (); ICryptoTransform ct = sa.CreateEncryptor (); byte[] encrypt = ct.TransformFinalBlock (input, 0, input.Length); RSAPKCS1KeyExchangeFormatter fmt = new RSAPKCS1KeyExchangeFormatter (rsa); byte[] keyex = fmt.CreateKeyExchange (sa.Key); // return the key exchange, the IV (public) and encrypted data byte[] result = new byte [keyex.Length + sa.IV.Length + encrypt.Length]; Buffer.BlockCopy (keyex, 0, result, 0, keyex.Length); Buffer.BlockCopy (sa.IV, 0, result, keyex.Length, sa.IV.Length); Buffer.BlockCopy (encrypt, 0, result, keyex.Length + sa.IV.Length, encrypt.Length); return result; }
internal RSASha1Pkcs1SignatureGenerator(RSA rsa) { _realRsaGenerator = X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1); }
public override void SetKey(AsymmetricAlgorithm key) { base.SetKey(key); m_rsaKey = (RSA)key; }
public static void AssociatePersistedKey_CAPIviaCNG_RSA(int provType, KeyNumber keyNumber) { const string KeyName = nameof(AssociatePersistedKey_CAPIviaCNG_RSA); CspParameters cspParameters = new CspParameters(provType) { KeyNumber = (int)keyNumber, KeyContainerName = KeyName, Flags = CspProviderFlags.UseNonExportableKey, }; using (RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(cspParameters)) { rsaCsp.PersistKeyInCsp = false; // Use SHA-1 because the FULL and SCHANNEL providers can't handle SHA-2. HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; var generator = new RSASha1Pkcs1SignatureGenerator(rsaCsp); byte[] signature; CertificateRequest request = new CertificateRequest( $"CN={KeyName}-{provType}-{keyNumber}", rsaCsp, hashAlgorithm); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, generator, now, now.AddDays(1), new byte[1])) using (X509Certificate2 withPrivateKey = cert.CopyWithPrivateKey(rsaCsp)) using (RSA rsa = withPrivateKey.GetRSAPrivateKey()) { // `rsa` will be an RSACng wrapping the CAPI key, which means it does not expose the // KeyNumber from CAPI. Assert.IsAssignableFrom <RSACng>(rsa); request = new CertificateRequest( $"CN={KeyName}-{provType}-{keyNumber}-again", rsa, hashAlgorithm); X509Certificate2 cert2 = request.Create( request.SubjectName, generator, now, now.AddDays(1), new byte[1]); using (cert2) using (X509Certificate2 withPrivateKey2 = cert2.CopyWithPrivateKey(rsaCsp)) using (RSA rsa2 = withPrivateKey2.GetRSAPrivateKey()) { signature = rsa2.SignData( Array.Empty <byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.True( rsaCsp.VerifyData( Array.Empty <byte>(), signature, hashAlgorithm, RSASignaturePadding.Pkcs1)); } } // Some certs have disposed, did they delete the key? cspParameters.Flags = CspProviderFlags.UseExistingKey; using (RSACryptoServiceProvider stillPersistedKey = new RSACryptoServiceProvider(cspParameters)) { byte[] signature2 = stillPersistedKey.SignData( Array.Empty <byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.Equal(signature, signature2); } } }
public MerchantApiClient(string merchantId, string userId, RSA privateKey) { auth = new MerchantApiKeyAuth(merchantId, userId, privateKey); }
private static RSA CreateRsaFromPublicKey(string publicKeyString) { byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; byte[] x509key; byte[] seq = new byte[15]; int x509size; x509key = Convert.FromBase64String(publicKeyString); x509size = x509key.Length; using (var mem = new MemoryStream(x509key)) { using (var binr = new BinaryReader(mem)) { byte bt = 0; ushort twobytes = 0; twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) { binr.ReadByte(); } else if (twobytes == 0x8230) { binr.ReadInt16(); } else { return(null); } seq = binr.ReadBytes(15); if (!CompareBytearrays(seq, SeqOID)) { return(null); } twobytes = binr.ReadUInt16(); if (twobytes == 0x8103) { binr.ReadByte(); } else if (twobytes == 0x8203) { binr.ReadInt16(); } else { return(null); } bt = binr.ReadByte(); if (bt != 0x00) { return(null); } twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) { binr.ReadByte(); } else if (twobytes == 0x8230) { binr.ReadInt16(); } else { return(null); } twobytes = binr.ReadUInt16(); byte lowbyte = 0x00; byte highbyte = 0x00; if (twobytes == 0x8102) { lowbyte = binr.ReadByte(); } else if (twobytes == 0x8202) { highbyte = binr.ReadByte(); lowbyte = binr.ReadByte(); } else { return(null); } byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; int modsize = BitConverter.ToInt32(modint, 0); int firstbyte = binr.PeekChar(); if (firstbyte == 0x00) { binr.ReadByte(); modsize -= 1; } byte[] modulus = binr.ReadBytes(modsize); if (binr.ReadByte() != 0x02) { return(null); } int expbytes = (int)binr.ReadByte(); byte[] exponent = binr.ReadBytes(expbytes); var rsa = RSA.Create(); var rsaKeyInfo = new RSAParameters { Modulus = modulus, Exponent = exponent }; rsa.ImportParameters(rsaKeyInfo); return(rsa); } } }
private static IEnumerable <JsonWebKey> ExtractJsonWebKeys(Table table) { var builder = new JsonWebKeyBuilder(); var jwks = new List <JsonWebKey>(); foreach (var record in table.Rows) { var type = record["Type"]; var kid = record["Kid"]; var algName = record["AlgName"]; JsonWebKey jwk = null; switch (type) { case "SIG": if (algName.StartsWith("ES")) { using (var ec = new ECDsaCng()) { jwk = builder.NewSign(kid, new[] { KeyOperations.Sign, KeyOperations.Verify }).SetAlg(ec, algName).Build(); } } else if (algName.StartsWith("HS")) { using (var hmac = new HMACSHA256()) { jwk = builder.NewSign(kid, new[] { KeyOperations.Sign, KeyOperations.Verify }).SetAlg(hmac, algName).Build(); } } else { using (var rsa = RSA.Create()) { jwk = builder.NewSign(kid, new[] { KeyOperations.Sign, KeyOperations.Verify }).SetAlg(rsa, algName).Build(); } } break; case "ENC": using (var rsa = RSA.Create()) { jwk = builder.NewEnc(kid, new[] { KeyOperations.Encrypt, KeyOperations.Decrypt }).SetAlg(rsa, algName).Build(); } break; } jwks.Add(jwk); } return(jwks); }
// ficheroClavePublica: archivo donde guardara la clave publica // ficheroClavePrivada: archivo donde guardara la clave privada public static Byte[] GenerarClavesRSA(int keySize = 2048) { string directorioTemporal = Path.GetTempPath(); if (string.IsNullOrEmpty(directorioTemporal)) { throw new ArgumentNullException("directorioTemporal {ServicioSeguridad - Path.GetTempPath()}"); } string idOperacion = DateTime.Now.Ticks.ToString(); DirectoryInfo dirTemp = new DirectoryInfo(directorioTemporal); DirectoryInfo dirClaves = dirTemp.CreateSubdirectory(idOperacion); string ficheroClavePublica = Path.Combine(dirClaves.FullName, "publica.key"); string ficheroClavePrivada = Path.Combine(dirClaves.FullName, "privada.key"); string ficheroZip = ""; Byte[] zipClaves = null; var rsa = RSA.Create(); rsa.KeySize = keySize; try { using (var fs = File.Create(ficheroClavePublica)) { using (var pem = new PemWriter(fs)) { pem.WritePublicKey(rsa); } } using (var fs = File.Create(ficheroClavePrivada)) { using (var pem = new PemWriter(fs)) { pem.WritePrivateKey(rsa); } } ficheroZip = Path.Combine(dirTemp.FullName, $"claves_{idOperacion}.zip"); ZipFile.CreateFromDirectory(dirClaves.FullName, ficheroZip); zipClaves = File.ReadAllBytes(ficheroZip); } catch (Exception ex) { //log.Error($"ERR SERVICIOSEGURIDAD (GenerarClaves) - {ex.Message}"); Console.WriteLine($"ERR SERVICIOSEGURIDAD (GenerarClaves) - {ex.Message}"); } finally { if (Directory.Exists(dirClaves.FullName)) { dirClaves.Delete(true); } if (!string.IsNullOrEmpty(ficheroZip) && File.Exists(ficheroZip)) { File.Delete(ficheroZip); } } return(zipClaves); }
public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate, RSA privateKey) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } if (privateKey == null) { throw new ArgumentNullException(nameof(privateKey)); } if (certificate.HasPrivateKey) { throw new InvalidOperationException(SR.GetString(SR.Cryptography_Cert_AlreadyHasPrivateKey)); } using (RSA publicKey = GetRSAPublicKey(certificate)) { if (publicKey == null) { throw new ArgumentException(SR.GetString(SR.Cryptography_PrivateKey_WrongAlgorithm)); } RSAParameters currentParameters = publicKey.ExportParameters(false); RSAParameters newParameters = privateKey.ExportParameters(false); if (!currentParameters.Modulus.SequenceEqual(newParameters.Modulus) || !currentParameters.Exponent.SequenceEqual(newParameters.Exponent)) { throw new ArgumentException(SR.GetString(SR.Cryptography_PrivateKey_DoesNotMatch), nameof(privateKey)); } } RSACng rsaCng = privateKey as RSACng; X509Certificate2 newCert = null; if (rsaCng != null) { newCert = CertificateExtensionsCommon.CopyWithPersistedCngKey(certificate, rsaCng.Key); } if (newCert == null) { RSACryptoServiceProvider rsaCsp = privateKey as RSACryptoServiceProvider; if (rsaCsp != null) { newCert = CertificateExtensionsCommon.CopyWithPersistedCapiKey(certificate, rsaCsp.CspKeyContainerInfo); } } if (newCert == null) { RSAParameters parameters = privateKey.ExportParameters(true); using (PinAndClear.Track(parameters.D)) using (PinAndClear.Track(parameters.P)) using (PinAndClear.Track(parameters.Q)) using (PinAndClear.Track(parameters.DP)) using (PinAndClear.Track(parameters.DQ)) using (PinAndClear.Track(parameters.InverseQ)) using (rsaCng = new RSACng()) { rsaCng.ImportParameters(parameters); newCert = CertificateExtensionsCommon.CopyWithEphemeralCngKey(certificate, rsaCng.Key); } } Debug.Assert(newCert != null); Debug.Assert(!ReferenceEquals(certificate, newCert)); Debug.Assert(!certificate.HasPrivateKey); Debug.Assert(newCert.HasPrivateKey); return(newCert); }
public RSA CreateRsaProviderFromPublicKey(string publicKeyString) { // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; byte[] seq = new byte[15]; var x509Key = Convert.FromBase64String(publicKeyString); // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ using (MemoryStream mem = new MemoryStream(x509Key)) { using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading { byte bt = 0; ushort twobytes = 0; 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); } seq = binr.ReadBytes(15); //read the Sequence OID if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct { return(null); } twobytes = binr.ReadUInt16(); if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) { binr.ReadByte(); //advance 1 byte } else if (twobytes == 0x8203) { binr.ReadInt16(); //advance 2 bytes } else { return(null); } bt = binr.ReadByte(); if (bt != 0x00) //expect null byte next { return(null); } 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(); byte lowbyte = 0x00; byte highbyte = 0x00; if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81) { lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus } else if (twobytes == 0x8202) { highbyte = binr.ReadByte(); //advance 2 bytes lowbyte = binr.ReadByte(); } else { return(null); } byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order int modsize = BitConverter.ToInt32(modint, 0); int firstbyte = binr.PeekChar(); if (firstbyte == 0x00) { //if first byte (highest order) of modulus is zero, don't include it binr.ReadByte(); //skip this null byte modsize -= 1; //reduce modulus buffer size by 1 } byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data { return(null); } int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values) byte[] exponent = binr.ReadBytes(expbytes); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- var rsa = RSA.Create(); RSAParameters rsaKeyInfo = new RSAParameters { Modulus = modulus, Exponent = exponent }; rsa.ImportParameters(rsaKeyInfo); return(rsa); } } }
//private const int port = FSKeyCommon.Properties.Settings.Default.serverPort; public static bool SetupSSLCert() { //Check For Existing Cert: X509Store store; X509Certificate2 rootCert = null; store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); bool rootCertFound = false; foreach (X509Certificate2 c in store.Certificates) { if (c.FriendlyName == KEY_FN) { if (Convert.ToDateTime(c.GetExpirationDateString()) < DateTime.Now.AddYears(1)) //Cert About to Expire REmove It. { store.Remove(c); } else if (rootCertFound) //Clear Duplicate Root Certs { store.Remove(c); } else { rootCert = c; rootCertFound = true; } } } store.Close(); //Grab Personal Cert X509Certificate2 serviceCert = null; store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); foreach (X509Certificate2 c in store.Certificates) { if (c.FriendlyName == KEY_FN) { if (Convert.ToDateTime(c.GetExpirationDateString()) < DateTime.Now.AddYears(1)) //Cert About to Expire. Remove it. { store.Remove(c); } else if (rootCert == null) //No Root Cert Found. Delete All Personal Certs { store.Remove(c); } else if (rootCert.PublicKey != c.PublicKey) //Doesn't Match our root cert { serviceCert = c; break; } } } store.Close(); //Delete Root Cert if No Matching Service Cert if ((rootCert != null) && (serviceCert == null)) { store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Remove(rootCert); store.Close(); rootCert = null; } //Create New Certs if Needed if (rootCert == null) { String DNSname = System.Net.Dns.GetHostName(); var rsa = RSA.Create(2048); // generate asymmetric key pair var req = new CertificateRequest("CN=Freeside Technology Spaces LLC", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); req.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment, false)); req.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); //Build SAN SubjectAlternativeNameBuilder SANBuilder = new SubjectAlternativeNameBuilder(); SANBuilder.AddDnsName(DNSname); req.CertificateExtensions.Add(SANBuilder.Build()); //Create Cert rootCert = req.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow).AddDays(-5), new DateTimeOffset(DateTime.UtcNow).AddYears(20)); rootCert.FriendlyName = "FS Key Server SSL Cert (v0.1)"; byte[] rootCertBytes = rootCert.Export(X509ContentType.Pfx); serviceCert = new X509Certificate2(rootCertBytes, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); //Add To Root if Not There Already store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(rootCert); store.Close(); store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(serviceCert); store.Close(); } GuidAttribute g = (GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]; byte[] sslHash = Enumerable.Range(0, serviceCert.Thumbprint.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(serviceCert.Thumbprint.Substring(x, 2), 16)) .ToArray(); //Bind SSL Cert To Port try { Microsoft.Web.Administration.NativeMethods.DeleteCertificateBinding(new IPEndPoint(IPAddress.Any, Properties.Settings.Default.serverPort)); } catch { } Microsoft.Web.Administration.NativeMethods.BindCertificate(new IPEndPoint(IPAddress.Any, Properties.Settings.Default.serverPort), sslHash, "MY", new Guid(g.Value)); //REsult 0 = Success, 183 = Already Exists return(true); }
/// <summary> /// Generate custom X509Certificate2 like pfx /// </summary> #region GenerateCustomX509Certificate2 public static X509Certificate2 GenerateCustomX509Certificate2(string commonName, string password, string friendlyName = null, string[] dnsNames = null, DateTime?expirationBefore = null, DateTime?expirationAfter = null, bool isCertificateAuthority = false, string countryCode = "US", string organization = "JCCE", string[] organizationalUnits = null) { var sanBuilder = new SubjectAlternativeNameBuilder(); if (dnsNames == null) { sanBuilder.AddIpAddress(IPAddress.Loopback); sanBuilder.AddIpAddress(IPAddress.IPv6Loopback); sanBuilder.AddDnsName("localhost"); sanBuilder.AddDnsName(Environment.MachineName); } else { foreach (var dnsName in dnsNames) { sanBuilder.AddDnsName(dnsName); } } if (countryCode.Length != 2) { countryCode = "US"; } if (organizationalUnits == null) { organizationalUnits = new[] { "Copyright (c), " + DateTime.UtcNow.ToString("yyyy") + " JCCE" } } ; var dn = new StringBuilder(); dn.Append("CN=\"" + commonName.Replace("\"", "\"\"") + "\""); foreach (var ou in organizationalUnits) { dn.Append(",OU=\"" + ou.Replace("\"", "\"\"") + "\""); } dn.Append(",O=\"" + organization.Replace("\"", "\"\"") + "\""); dn.Append(",C=" + countryCode.ToUpper()); dn.Append(",C=" + "JP"); var strDn = dn.ToString(); var distinguishedName = new X500DistinguishedName(strDn); X509Certificate2 cert; using (var rsa = RSA.Create(2048)) { var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var usages = X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature; if (isCertificateAuthority) { usages = usages | X509KeyUsageFlags.KeyCertSign; } request.CertificateExtensions.Add(new X509KeyUsageExtension(usages, false)); request.CertificateExtensions.Add( new X509EnhancedKeyUsageExtension( new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); request.CertificateExtensions.Add(sanBuilder.Build()); if (isCertificateAuthority) { request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 1, true)); } if (expirationAfter == null) { expirationAfter = DateTime.UtcNow.AddDays(-1).AddYears(10); } if (expirationBefore == null) { expirationBefore = DateTime.UtcNow; } var certificate = request.CreateSelfSigned(new DateTimeOffset(expirationBefore.Value), new DateTimeOffset(expirationAfter.Value)); if (friendlyName == null) { friendlyName = commonName; } certificate.FriendlyName = friendlyName; cert = new X509Certificate2(certificate.Export(X509ContentType.Pfx, password), password, X509KeyStorageFlags.Exportable); // If need certificate pfx file // File.WriteAllBytes(path, certificate.Export(X509ContentType.Pkcs12, Password)); } return(cert); }
public InfoCardRSAPKCS1KeyExchangeDeformatter(AsymmetricAlgorithm key) : base(key) { m_rsaKey = (RSA)key; }
// Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key) { // Check the arguments. if (FileName == null) { throw new ArgumentNullException("FileName"); } if (SignedFileName == null) { throw new ArgumentNullException("SignedFileName"); } if (Key == null) { throw new ArgumentNullException("Key"); } // Create a new XML document. XmlDocument doc = new XmlDocument(); // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Load the passed XML file using it's name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Get the signature object from the SignedXml object. Signature XMLSignature = signedXml.Signature; // Create a reference to be signed. Pass "" // to specify that all of the current XML // document should be signed. Reference reference = new Reference(""); // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((RSA)Key)); // Add the KeyInfo object to the Reference object. XMLSignature.KeyInfo = keyInfo; // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); if (doc.FirstChild is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); }
public StressServer(Configuration configuration) { ServerUri = configuration.ServerUri; (string scheme, string hostname, int port) = ParseServerUri(configuration.ServerUri); IWebHostBuilder host = new WebHostBuilder(); host = host.ConfigureServices(service => { service.AddRouting(); }) // Use Kestrel, and configure it for HTTPS with a self-signed test certificate. .UseKestrel(ko => { // conservative estimation based on https://github.com/aspnet/AspNetCore/blob/caa910ceeba5f2b2c02c47a23ead0ca31caea6f0/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs#L204 ko.Limits.MaxRequestLineSize = Math.Max(ko.Limits.MaxRequestLineSize, configuration.MaxRequestUriSize + 100); ko.Limits.MaxRequestHeaderCount = Math.Max(ko.Limits.MaxRequestHeaderCount, configuration.MaxRequestHeaderCount); ko.Limits.MaxRequestHeadersTotalSize = Math.Max(ko.Limits.MaxRequestHeadersTotalSize, configuration.MaxRequestHeaderTotalSize); ko.Limits.Http2.MaxStreamsPerConnection = configuration.ServerMaxConcurrentStreams ?? ko.Limits.Http2.MaxStreamsPerConnection; ko.Limits.Http2.MaxFrameSize = configuration.ServerMaxFrameSize ?? ko.Limits.Http2.MaxFrameSize; ko.Limits.Http2.InitialConnectionWindowSize = configuration.ServerInitialConnectionWindowSize ?? ko.Limits.Http2.InitialConnectionWindowSize; ko.Limits.Http2.MaxRequestHeaderFieldSize = configuration.ServerMaxRequestHeaderFieldSize ?? ko.Limits.Http2.MaxRequestHeaderFieldSize; switch (hostname) { case "+": case "*": ko.ListenAnyIP(port, ConfigureListenOptions); break; default: IPAddress iPAddress = Dns.GetHostAddresses(hostname).First(); ko.Listen(iPAddress, port, ConfigureListenOptions); break; } void ConfigureListenOptions(ListenOptions listenOptions) { if (scheme == "https") { // Create self-signed cert for server. using (RSA rsa = RSA.Create()) { var certReq = new CertificateRequest("CN=contoso.com", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); } listenOptions.UseHttps(cert); } } else { listenOptions.Protocols = configuration.HttpVersion == new Version(2, 0) ? HttpProtocols.Http2 : HttpProtocols.Http1; } } }) // Output only warnings and errors from Kestrel .ConfigureLogging(log => log.AddFilter("Microsoft.AspNetCore", level => configuration.LogAspNet ? level >= LogLevel.Warning : false)) // Set up how each request should be handled by the server. .Configure(app => { var routeBuilder = new RouteBuilder(app); MapRoutes(routeBuilder); app.UseRouter(routeBuilder.Build()); }); // Handle command-line arguments. _eventListener = configuration.LogPath == null ? null : (configuration.LogPath == "console" ? (EventListener) new ConsoleHttpEventListener() : (EventListener) new LogHttpEventListener(configuration.LogPath)); SetUpJustInTimeLogging(); _webHost = host.Build(); _webHost.Start(); }
/// <summary> /// Generates a UniqueID based off the Issuer's key and the PPID. /// </summary> /// <param name="authzContext">The Authorization Context</param> /// <returns>A unique ID for this user at this web site.</returns> internal static string GetUniqueName(AuthorizationContext authzContext) { Requires.NotNull(authzContext, "authzContext"); Claim uniqueIssuerClaim = null; Claim uniqueUserClaim = null; foreach (ClaimSet cs in authzContext.ClaimSets) { Claim currentIssuerClaim = GetUniqueRsaClaim(cs.Issuer); foreach (Claim c in cs.FindClaims(ClaimTypes.PPID, Rights.PossessProperty)) { if (null == currentIssuerClaim) { // Found a claim in a ClaimSet with no RSA issuer. return(null); } if (null == uniqueUserClaim) { uniqueUserClaim = c; uniqueIssuerClaim = currentIssuerClaim; } else if (!uniqueIssuerClaim.Equals(currentIssuerClaim)) { // Found two of the desired claims with different // issuers. No unique name. return(null); } else if (!uniqueUserClaim.Equals(c)) { // Found two of the desired claims with different // values. No unique name. return(null); } } } // No claim of the desired type was found if (null == uniqueUserClaim) { return(null); } // Unexpected resource type string claimValue = uniqueUserClaim.Resource as string; if (null == claimValue) { return(null); } // Unexpected resource type for RSA RSA rsa = uniqueIssuerClaim.Resource as RSA; if (null == rsa) { return(null); } return(ComputeCombinedId(rsa, claimValue)); }
public override string ToString(bool verbose) { if (verbose == false || Pal == null) { return(ToString()); } StringBuilder sb = new StringBuilder(); // Version sb.AppendLine("[Version]"); sb.Append(" V"); sb.Append(Version); // Subject sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Subject]"); sb.Append(" "); sb.Append(SubjectName.Name); string simpleName = GetNameInfo(X509NameType.SimpleName, false); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } string emailName = GetNameInfo(X509NameType.EmailName, false); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } string upnName = GetNameInfo(X509NameType.UpnName, false); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } string dnsName = GetNameInfo(X509NameType.DnsName, false); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Issuer sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.Append(IssuerName.Name); simpleName = GetNameInfo(X509NameType.SimpleName, true); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } emailName = GetNameInfo(X509NameType.EmailName, true); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } upnName = GetNameInfo(X509NameType.UpnName, true); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } dnsName = GetNameInfo(X509NameType.DnsName, true); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Serial Number sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); sb.AppendLine(SerialNumber); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(NotBefore)); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(NotAfter)); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.AppendLine(Thumbprint); // Signature Algorithm sb.AppendLine(); sb.AppendLine("[Signature Algorithm]"); sb.Append(" "); sb.Append(SignatureAlgorithm.FriendlyName); sb.Append('('); sb.Append(SignatureAlgorithm.Value); sb.AppendLine(")"); // Public Key sb.AppendLine(); sb.Append("[Public Key]"); // It could throw if it's some user-defined CryptoServiceProvider try { PublicKey pubKey = PublicKey; sb.AppendLine(); sb.Append(" "); sb.Append("Algorithm: "); sb.Append(pubKey.Oid.FriendlyName); // So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys try { sb.AppendLine(); sb.Append(" "); sb.Append("Length: "); using (RSA pubRsa = this.GetRSAPublicKey()) { if (pubRsa != null) { sb.Append(pubRsa.KeySize); } } } catch (NotSupportedException) { } sb.AppendLine(); sb.Append(" "); sb.Append("Key Blob: "); sb.AppendLine(pubKey.EncodedKeyValue.Format(true)); sb.Append(" "); sb.Append("Parameters: "); sb.Append(pubKey.EncodedParameters.Format(true)); } catch (CryptographicException) { } // Private key Pal.AppendPrivateKeyInfo(sb); // Extensions X509ExtensionCollection extensions = Extensions; if (extensions.Count > 0) { sb.AppendLine(); sb.AppendLine(); sb.Append("[Extensions]"); foreach (X509Extension extension in extensions) { try { sb.AppendLine(); sb.Append("* "); sb.Append(extension.Oid.FriendlyName); sb.Append('('); sb.Append(extension.Oid.Value); sb.Append("):"); sb.AppendLine(); sb.Append(" "); sb.Append(extension.Format(true)); } catch (CryptographicException) { } } } sb.AppendLine(); return(sb.ToString()); }
public void SetUp() { rsa = new NonAbstractRSAForUnitTests(); }
public MerchantApiKeyAuth(string merchantId, string userId, RSA privateKey) { this.merchantId = merchantId; this.userId = userId; signer = new RSAPKCS1SignatureFormatter(privateKey); }
public static byte[] Encrypt(byte[] data) { using var rsa = RSA.Create(); rsa.ImportSubjectPublicKeyInfo(publicKey, out int bytesRead); return(rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1)); }
private static void VerifyPrivateKey(RSA rsa) { byte[] hash = new byte[20]; byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig); }
public static void GenerateNewKeys(int keySize = DefaultKeySize) { using var rsa = RSA.Create(keySize); publicKey = rsa.ExportSubjectPublicKeyInfo(); privateKey = rsa.ExportRSAPrivateKey(); }
public void EncodeTest() { RSA rsa = new RSA(); var data = rsa.Encode(@"<RSAKeyValue><Modulus>nX8JqOtKsttNSx5XMxQ8UIprhvbbXy3yTMU04S69ZInQYFUFHas1HWEp26QUL4LIJ6CQ+698r12KbDZh7MOT7HV3Ia/aQ34Oge7AVOX0Y0E+95f7gxcb9pllsUD2lFos/FW0LuoBicxwFojcLuuc3tUoElD2oGFZ2OusBoDjEMk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>", "你好,yz"); Assert.IsTrue(!string.IsNullOrEmpty(data)); }
private async Task <(SecurityKeyInfo[], SigningCredentials)> GetOrCreateKeyAsync() { if (cachedKey != null && cachedKeyInfo != null) { return(cachedKeyInfo, cachedKey); } var key = await Collection.Find(x => x.Id == "Default").FirstOrDefaultAsync(); RsaSecurityKey securityKey; if (key == null) { securityKey = new RsaSecurityKey(RSA.Create(2048)) { KeyId = CryptoRandom.CreateUniqueId(16) }; key = new MongoDbKey { Id = "Default", Key = securityKey.KeyId }; if (securityKey.Rsa != null) { var parameters = securityKey.Rsa.ExportParameters(includePrivateParameters: true); key.Parameters = MongoDbKeyParameters.Create(parameters); } else { key.Parameters = MongoDbKeyParameters.Create(securityKey.Parameters); } try { await Collection.InsertOneAsync(key); return(CreateCredentialsPair(securityKey)); } catch (MongoWriteException ex) { if (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey) { key = await Collection.Find(x => x.Id == "Default").FirstOrDefaultAsync(); } else { throw; } } } if (key == null) { throw new InvalidOperationException("Cannot read key."); } securityKey = new RsaSecurityKey(key.Parameters.ToParameters()) { KeyId = key.Key }; return(CreateCredentialsPair(securityKey)); }
public RSAKeyValue () { rsa = (RSA)RSA.Create (); }
public static void AssinaComCertificado(List <ICrlClient> crlList, byte[] File, out byte[] SignFile, CertSimples cert, int X, int Y, int Pagina, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-256", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "") { int Largura = 140; int Altura = 63; MemoryStream ArquivoOrigem = new MemoryStream(File); PdfReader pdfReader = new PdfReader(ArquivoOrigem); MemoryStream signedPdf = new MemoryStream(); StampingProperties osp = new StampingProperties(); osp.UseAppendMode(); PdfSigner objStamper = new PdfSigner(pdfReader, signedPdf, osp); ITSAClient tsaClient = null; IOcspClient ocspClient = null; ConfiguraAparencia(objStamper, cert, X, Y, Largura, Altura, Pagina, Rotation, Contact, Reason, Location, Creator, Tipo, Cargo, CREACRM); Org.BouncyCastle.X509.X509Certificate vert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificado); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] Arraychain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) }; X509CertificateParser objCP = new X509CertificateParser(); RSACryptoServiceProvider rsa; RSACryptoServiceProvider Provider; IExternalSignature externalSignature; if (cert.Certificado.PrivateKey is RSACryptoServiceProvider) { rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } else { RSA rsaTeste = cert.Certificado.GetRSAPrivateKey(); rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } if (AddTimeStamper) { tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass); } OCSPVerifier ocspVerifier = new OCSPVerifier(null, null); ocspClient = new OcspClientBouncyCastle(ocspVerifier); if (AplicaPolitica) { SignaturePolicyInfo spi = getPolitica(); objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES, spi); } else { objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES); } try { SignFile = signedPdf.ToArray(); try { signedPdf.Close(); signedPdf.Dispose(); } catch { } } catch (Exception ex) { SignFile = null; throw ex; } try { signedPdf.Close(); } catch (Exception ex) { } pdfReader.Close(); }
private byte[] Decrypt(RSA rsa, byte[] input) { // by default this will create a 128 bits AES (Rijndael) object SymmetricAlgorithm sa = SymmetricAlgorithm.Create (); byte[] keyex = new byte [rsa.KeySize >> 3]; Buffer.BlockCopy (input, 0, keyex, 0, keyex.Length); RSAPKCS1KeyExchangeDeformatter def = new RSAPKCS1KeyExchangeDeformatter (rsa); byte[] key = def.DecryptKeyExchange (keyex); byte[] iv = new byte [sa.IV.Length]; Buffer.BlockCopy (input, keyex.Length, iv, 0, iv.Length); ICryptoTransform ct = sa.CreateDecryptor (key, iv); byte[] decrypt = ct.TransformFinalBlock (input, keyex.Length + iv.Length, input.Length - (keyex.Length + iv.Length)); return decrypt; }
/// <summary> /// RSA with SHA-384 signatures /// </summary> /// <param name="RSA">RSA cryptogaphic service provider.</param> public RsaSha384(RSA RSA) : base(RSA) { }
// Constructors. public RSACryptoProvider(RSA.RSACrypto clientProvider) { this.ClientProvider = clientProvider; }
public static void FromXmlString(this RSA rsa, string xmlString) { var parameters = new RSAParameters(); var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlString); if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue")) { foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { switch (node.Name) { case "Modulus": parameters.Modulus = Convert.FromBase64String(node.InnerText); break; case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break; case "P": parameters.P = Convert.FromBase64String(node.InnerText); break; case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break; case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break; case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break; case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break; case "D": parameters.D = Convert.FromBase64String(node.InnerText); break; } } } else { throw new Exception("Invalid XML RSA key."); } rsa.ImportParameters(parameters); }
/* * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * otherPrimeInfos OtherPrimeInfos OPTIONAL * } */ static public RSA DecodeRSA(byte[] keypair) { ASN1 privateKey = new ASN1(keypair); if (privateKey.Tag != 0x30) { throw new CryptographicException("invalid private key format"); } ASN1 version = privateKey[0]; if (version.Tag != 0x02) { throw new CryptographicException("missing version"); } if (privateKey.Count < 9) { throw new CryptographicException("not enough key parameters"); } RSAParameters param = new RSAParameters(); // note: MUST remove leading 0 - else MS wont import the key param.Modulus = RemoveLeadingZero(privateKey[1].Value); int keysize = param.Modulus.Length; int keysize2 = (keysize >> 1); // half-size // size must be normalized - else MS wont import the key param.D = Normalize(privateKey[3].Value, keysize); param.DP = Normalize(privateKey[6].Value, keysize2); param.DQ = Normalize(privateKey[7].Value, keysize2); param.Exponent = RemoveLeadingZero(privateKey[2].Value); param.InverseQ = Normalize(privateKey[8].Value, keysize2); param.P = Normalize(privateKey[4].Value, keysize2); param.Q = Normalize(privateKey[5].Value, keysize2); RSA rsa = null; try { rsa = RSA.Create(); rsa.ImportParameters(param); } catch (CryptographicException) { #if MONOTOUCH // there's no machine-wide store available for iOS so we can drop the dependency on // CspParameters (which drops other things, like XML key persistance, unless used elsewhere) throw; #else // 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(param); #endif } return(rsa); }
public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName) { // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (ElementToEncrypt == null) { throw new ArgumentNullException("ElementToEncrypt"); } if (EncryptionElementID == null) { throw new ArgumentNullException("EncryptionElementID"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } if (KeyName == null) { throw new ArgumentNullException("KeyName"); } //////////////////////////////////////////////// // Find the specified element in the XmlDocument // object and create a new XmlElemnt object. //////////////////////////////////////////////// XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; // Throw an XmlException if the element was not found. if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } ////////////////////////////////////////////////// // Create a new instance of the EncryptedXml class // and use it to encrypt the XmlElement with the // a new random symmetric key. ////////////////////////////////////////////////// // Create a 256 bit Rijndael key. RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); //////////////////////////////////////////////// // Construct an EncryptedData object and populate // it with the desired encryption information. //////////////////////////////////////////////// EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.Id = EncryptionElementID; // Create an EncryptionMethod element so that the // receiver knows which algorithm to use for decryption. edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Encrypt the session key and add it to an EncryptedKey element. EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); // Set the KeyInfo element to specify the // name of the RSA key. // Create a new KeyInfo element. edElement.KeyInfo = new KeyInfo(); // Create a new KeyInfoName element. KeyInfoName kin = new KeyInfoName(); // Specify a name for the key. kin.Value = KeyName; // Add the KeyInfoName element to the // EncryptedKey object. ek.KeyInfo.AddClause(kin); // Create a new DataReference element // for the KeyInfo element. This optional // element specifies which EncryptedData // uses this key. An XML document can have // multiple EncryptedData elements that use // different keys. DataReference dRef = new DataReference(); // Specify the EncryptedData URI. dRef.Uri = "#" + EncryptionElementID; // Add the DataReference to the EncryptedKey. ek.AddReference(dRef); // Add the encrypted key to the // EncryptedData object. edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; //////////////////////////////////////////////////// // Replace the element from the original XmlDocument // object with the EncryptedData element. //////////////////////////////////////////////////// EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); }
public ANSYSWriterEsfera(RSA rsaTarget) : base(rsaTarget) { }
static int Main(string[] args) { if (args.Length < 1) { Header(); Console.WriteLine("ERROR: Missing output filename {0}", Environment.NewLine); Help(); return(-1); } string fileName = args [args.Length - 1]; // default values byte[] sn = Guid.NewGuid().ToByteArray(); string subject = defaultSubject; string issuer = defaultIssuer; DateTime notBefore = DateTime.Now; DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z RSA issuerKey = (RSA)RSA.Create(); issuerKey.FromXmlString(MonoTestRootAgency); RSA subjectKey = (RSA)RSA.Create(); bool selfSigned = false; string hashName = "SHA512"; CspParameters subjectParams = new CspParameters(); CspParameters issuerParams = new CspParameters(); BasicConstraintsExtension bce = null; ExtendedKeyUsageExtension eku = null; SubjectAltNameExtension alt = null; string p12file = null; string p12pwd = null; X509Certificate issuerCertificate = null; Header(); try { int i = 0; while (i < args.Length) { switch (args [i++]) { // Basic options case "-#": // Serial Number sn = BitConverter.GetBytes(Convert.ToInt32(args [i++])); break; case "-n": // Subject Distinguish Name subject = args [i++]; break; case "-$": // (authenticode) commercial or individual // CRITICAL KeyUsageRestriction extension // hash algorithm string usageRestriction = args [i++].ToLower(); switch (usageRestriction) { case "commercial": case "individual": Console.WriteLine("WARNING: Unsupported deprecated certification extension KeyUsageRestriction not included"); // Console.WriteLine ("WARNING: ExtendedKeyUsage for codesigning has been included."); break; default: Console.WriteLine("Unsupported restriction " + usageRestriction); return(-1); } break; // Extended Options case "-a": // hash algorithm switch (args [i++].ToLower()) { case "sha512": hashName = "SHA512"; break; case "sha256": hashName = "SHA256"; break; case "sha1": Console.WriteLine("WARNING: SHA1 is not safe for this usage."); hashName = "SHA1"; break; case "md5": Console.WriteLine("WARNING: MD5 is not safe for this usage."); hashName = "MD5"; break; default: Console.WriteLine("Unsupported hash algorithm"); break; } break; case "-b": // Validity / notBefore notBefore = DateTime.Parse(args [i++] + " 23:59:59", CultureInfo.InvariantCulture); break; case "-cy": // basic constraints - autority or end-entity switch (args [i++].ToLower()) { case "authority": if (bce == null) { bce = new BasicConstraintsExtension(); } bce.CertificateAuthority = true; break; case "end": // do not include extension bce = null; break; case "both": Console.WriteLine("ERROR: No more supported in X.509"); return(-1); default: Console.WriteLine("Unsupported certificate type"); return(-1); } break; case "-d": // CN private extension ? Console.WriteLine("Unsupported option"); break; case "-e": // Validity / notAfter notAfter = DateTime.Parse(args [i++] + " 23:59:59", CultureInfo.InvariantCulture); break; case "-eku": // extendedKeyUsage extension char[] sep = { ',' }; string[] purposes = args [i++].Split(sep); if (eku == null) { eku = new ExtendedKeyUsageExtension(); } foreach (string purpose in purposes) { eku.KeyPurpose.Add(purpose); } break; case "-h": // pathLength (basicConstraints) // MS use an old basicConstrains (2.5.29.10) which // allows both CA and End-Entity. This is no // more supported with 2.5.29.19. if (bce == null) { bce = new BasicConstraintsExtension(); bce.CertificateAuthority = true; } bce.PathLenConstraint = Convert.ToInt32(args [i++]); break; case "-alt": if (alt == null) { string [] dnsNames = File.ReadAllLines(args [i++]); alt = new SubjectAltNameExtension(null, dnsNames, null, null); } break; case "-ic": issuerCertificate = LoadCertificate(args [i++]); issuer = issuerCertificate.SubjectName; break; case "-in": issuer = args [i++]; break; case "-iv": // TODO password PrivateKey pvk = PrivateKey.CreateFromFile(args [i++]); issuerKey = pvk.RSA; break; case "-l": // link (URL) // spcSpAgencyInfo private extension Console.WriteLine("Unsupported option"); break; case "-m": // validity period (in months) notAfter = notBefore.AddMonths(Convert.ToInt32(args [i++])); break; case "-nscp": // Netscape's private extensions - NetscapeCertType // BasicContraints - End Entity Console.WriteLine("Unsupported option"); break; case "-r": selfSigned = true; break; case "-sc": // subject certificate ? renew ? Console.WriteLine("Unsupported option"); break; // Issuer CspParameters options case "-ik": issuerParams.KeyContainerName = args [i++]; break; case "-iky": // select a key in the provider string ikn = args [i++].ToLower(); switch (ikn) { case "signature": issuerParams.KeyNumber = 0; break; case "exchange": issuerParams.KeyNumber = 1; break; default: issuerParams.KeyNumber = Convert.ToInt32(ikn); break; } break; case "-ip": issuerParams.ProviderName = args [i++]; break; case "-ir": switch (args [i++].ToLower()) { case "localmachine": issuerParams.Flags = CspProviderFlags.UseMachineKeyStore; break; case "currentuser": issuerParams.Flags = CspProviderFlags.UseDefaultKeyContainer; break; default: Console.WriteLine("Unknown key store for issuer"); return(-1); } break; case "-is": Console.WriteLine("Unsupported option"); return(-1); case "-iy": issuerParams.ProviderType = Convert.ToInt32(args [i++]); break; // Subject CspParameters Options case "-sk": subjectParams.KeyContainerName = args [i++]; break; case "-sky": // select a key in the provider string skn = args [i++].ToLower(); switch (skn) { case "signature": subjectParams.KeyNumber = 0; break; case "exchange": subjectParams.KeyNumber = 1; break; default: subjectParams.KeyNumber = Convert.ToInt32(skn); break; } break; case "-sp": subjectParams.ProviderName = args [i++]; break; case "-sr": switch (args [i++].ToLower()) { case "localmachine": subjectParams.Flags = CspProviderFlags.UseMachineKeyStore; break; case "currentuser": subjectParams.Flags = CspProviderFlags.UseDefaultKeyContainer; break; default: Console.WriteLine("Unknown key store for subject"); return(-1); } break; case "-ss": Console.WriteLine("Unsupported option"); return(-1); case "-sv": string pvkFile = args [i++]; if (File.Exists(pvkFile)) { PrivateKey key = PrivateKey.CreateFromFile(pvkFile); subjectKey = key.RSA; } else { PrivateKey key = new PrivateKey(); key.RSA = subjectKey; key.Save(pvkFile); } break; case "-sy": subjectParams.ProviderType = Convert.ToInt32(args [i++]); break; // Mono Specific Options case "-p12": p12file = args [i++]; p12pwd = args [i++]; break; // Other options case "-?": Help(); return(0); case "-!": ExtendedHelp(); return(0); default: if (i != args.Length) { Console.WriteLine("ERROR: Unknown parameter"); Help(); return(-1); } break; } } // serial number MUST be positive if ((sn [0] & 0x80) == 0x80) { sn [0] -= 0x80; } if (selfSigned) { if (subject != defaultSubject) { issuer = subject; issuerKey = subjectKey; } else { subject = issuer; subjectKey = issuerKey; } } if (subject == null) { throw new Exception("Missing Subject Name"); } X509CertificateBuilder cb = new X509CertificateBuilder(3); cb.SerialNumber = sn; cb.IssuerName = issuer; cb.NotBefore = notBefore; cb.NotAfter = notAfter; cb.SubjectName = subject; cb.SubjectPublicKey = subjectKey; // extensions if (bce != null) { cb.Extensions.Add(bce); } if (eku != null) { cb.Extensions.Add(eku); } if (alt != null) { cb.Extensions.Add(alt); } // signature cb.Hash = hashName; byte[] rawcert = cb.Sign(issuerKey); if (p12file == null) { WriteCertificate(fileName, rawcert); } else { PKCS12 p12 = new PKCS12(); p12.Password = p12pwd; ArrayList list = new ArrayList(); // we use a fixed array to avoid endianess issues // (in case some tools requires the ID to be 1). list.Add(new byte [4] { 1, 0, 0, 0 }); Hashtable attributes = new Hashtable(1); attributes.Add(PKCS9.localKeyId, list); p12.AddCertificate(new X509Certificate(rawcert), attributes); if (issuerCertificate != null) { p12.AddCertificate(issuerCertificate); } p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes); p12.SaveToFile(p12file); } Console.WriteLine("Success"); return(0); } catch (Exception e) { Console.WriteLine("ERROR: " + e.ToString()); Help(); } return(1); }
public void OneCert_TwoKeys_FirstWins(bool correctKeyFirst) { string pw = nameof(OneCert_TwoKeys_FirstWins); // Build the PFX in the normal Windows style, except the private key doesn't match. using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, s_exportableImportFlags)) using (RSA key = cert.GetRSAPrivateKey()) using (RSA unrelated = RSA.Create(key.KeySize)) { Pkcs12Builder builder = new Pkcs12Builder(); Pkcs12SafeContents keyContents = new Pkcs12SafeContents(); Pkcs12SafeContents certContents = new Pkcs12SafeContents(); Pkcs12SafeBag keyBag; Pkcs12SafeBag keyBag2; Pkcs12SafeBag certBag = certContents.AddCertificate(cert); if (correctKeyFirst) { keyBag = keyContents.AddShroudedKey(key, pw, s_windowsPbe); keyBag2 = keyContents.AddShroudedKey(unrelated, pw, s_windowsPbe); } else { keyBag = keyContents.AddShroudedKey(unrelated, pw, s_windowsPbe); keyBag2 = keyContents.AddShroudedKey(key, pw, s_windowsPbe); } keyBag.Attributes.Add(s_keyIdOne); keyBag2.Attributes.Add(s_keyIdOne); certBag.Attributes.Add(s_keyIdOne); builder.AddSafeContentsUnencrypted(keyContents); builder.AddSafeContentsEncrypted(certContents, pw, s_windowsPbe); builder.SealWithoutIntegrity(); byte[] pfxBytes = builder.Encode(); // On macOS the cert will come back with HasPrivateKey being false when the // incorrect key comes first if (!correctKeyFirst && OperatingSystem.IsMacOS()) { using (var publicCert = new X509Certificate2(cert.RawData)) { ReadPfx( pfxBytes, pw, publicCert); } return; } // The RSA "self-test" should pass when the correct key is first, // and fail when the unrelated key is first. Action <X509Certificate2> followup = CheckKeyConsistency; if (!correctKeyFirst) { followup = CheckKeyConsistencyFails; } ReadPfx( pfxBytes, pw, cert, followup); } }
public static byte[] Decrypt(byte[] data) { using var rsa = RSA.Create(); rsa.ImportRSAPrivateKey(privateKey, out int bytesRead); return(rsa.Decrypt(data, RSAEncryptionPadding.Pkcs1)); }
public virtual void ReInit(RSAConfiguration config,ParticulaInfo pInfo,ITracker track) { aleatpart=(bool)config.Valores["colorParticulaAleatorio"]; showNumber=(bool)config.Valores["mostrarNumeros"]; for(int i=0;i<colorParticula.Length;i++ ) colorParticula[i]=((float[])config.Valores["colorParticulas"])[i]; // idVisualizarPlanesOn=Gl.glGenLists(1); // idVisualizarPlanesOff=Gl.glGenLists(1); xmlreader.Path=(string)config.Valores["particulaXml"]; //ParticulaInfo xmlInfo = xmlreader.GetInfoParticulas((string)config.Valores["particulaInicial"]); if(((string)config.Valores["rsaClase"])=="RSAAdvanced") { if((((string)config.Valores["parametroVariable"])=="cantidadParticulas")) { rsa = new RSAAdvanced((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],(int)config.Valores["cantidadParticulas"], pInfo,track); } else { if(((object[])config.Valores["parametros"]).Length!=pInfo.InfoParametro.Cantidad)throw new Exception("Error"); object[] auxArray=(object[])config.Valores["parametros"]; rsa = new RSAAdvanced((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],auxArray, pInfo,track); } } else { if((((string)config.Valores["parametroVariable"])=="cantidadParticulas")) { rsa=new RSA((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],(int)config.Valores["cantidadParticulas"], pInfo,track); } else { if(((object[])config.Valores["parametros"]).Length!=pInfo.InfoParametro.Cantidad)throw new Exception("Error"); object[] auxArray=(object[])config.Valores["parametros"]; rsa = new RSA((double)config.Valores["ladoCubo"], (double)config.Valores["fraccionVolumetrica"],auxArray, pInfo,track); } } spheresInBox =(bool)config.Valores["spheresInBox"]; gestorDib.Xml=xmlreader; ParticulaDibujable.SetOwner(this); NumerosDibujables.SetOwner(this); cuboDib.Color=(float[])config.Valores["colorCubo"]; //planosAClipear = new double[6][] { new double[4] { 1, 0, 0, rsa.Cubo.PuntoInicial.X }, new double[4] { 0, 1, 0, rsa.Cubo.PuntoInicial.Y }, new double[4] { 0, 0, 1, rsa.Cubo.PuntoInicial.Z }, new double[4] { -1, 0, 0, rsa.Cubo.PuntoInicial.X + rsa.Cubo.Lado }, new double[4] { 0, -1, 0, rsa.Cubo.PuntoInicial.Y + rsa.Cubo.Lado }, new double[4] { 0, 0, -1, rsa.Cubo.PuntoInicial.Z + rsa.Cubo.Lado } }; numdib = new NumerosDibujables[rsa.particulas.Length]; ansyswriter = gestorDib.GeneraAnsysWriter(pInfo.Nombre, this.rsa); this.Recompile(); }
public static AsymmetricCipherKeyPair GetRsaKeyPair( RSA rsa) { return(GetRsaKeyPair(rsa.ExportParameters(true))); }
private static void VerifyKey_RSA(RSA rsa) { RSAParameters rsaParameters = rsa.ExportParameters(false); byte[] expectedModulus = ( "E8AF5CA2200DF8287CBC057B7FADEEEB76AC28533F3ADB407DB38E33E6573FA5" + "51153454A5CFB48BA93FA837E12D50ED35164EEF4D7ADB137688B02CF0595CA9" + "EBE1D72975E41B85279BF3F82D9E41362B0B40FBBE3BBAB95C759316524BCA33" + "C537B0F3EB7EA8F541155C08651D2137F02CBA220B10B1109D772285847C4FB9" + "1B90B0F5A3FE8BF40C9A4EA0F5C90A21E2AAE3013647FD2F826A8103F5A935DC" + "94579DFB4BD40E82DB388F12FEE3D67A748864E162C4252E2AAE9D181F0E1EB6" + "C2AF24B40E50BCDE1C935C49A679B5B6DBCEF9707B280184B82A29CFBFA90505" + "E1E00F714DFDAD5C238329EBC7C54AC8E82784D37EC6430B950005B14F6571C5").HexToByteArray(); byte[] expectedExponent = new byte[] { 0x01, 0x00, 0x01 }; Assert.Equal(expectedModulus, rsaParameters.Modulus); Assert.Equal(expectedExponent, rsaParameters.Exponent); }
public static RsaKeyParameters GetRsaPublicKey( RSA rsa) { return(GetRsaPublicKey(rsa.ExportParameters(false))); }
// Verify the signature of an XML file against an asymetric // algorithm and return the result. public static Boolean VerifyXmlFile(String Name, RSA Key) { // Create a new XML document. XmlDocument xmlDocument = new XmlDocument(); // Load the passed XML file into the document. xmlDocument.Load(Name); // Create a new SignedXml object and pass it // the XML document class. SignedXml signedXml = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(Key); }
public RSAEncryptedXml(XmlDocument document, RSA rsaKey) : base(document) { privateKey = rsaKey; }