public byte[] Decoder(byte[] input) { byte[] decoder = new byte[] {}; int k = rsa.KeySize / 8; byte[] buffer = new byte[k]; rsa.ImportParameters(privatKey); while (input.Length > 0) { if (input.Length > k) { buffer = Program.SubBytes(input, 0, k); input = Program.SubBytes(input, k + 1); } else { buffer = Program.SubBytes(input, 0); input = new byte[] {}; } decoder = Program.ConcatByte(decoder, rsa.Decrypt(buffer, false)); } return(decoder); }
public static string Decrypt(string input, string key) { System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(key); return(System.Text.Encoding.UTF8.GetString(rsa.Decrypt(ByteArrayFromString(input), false))); }
public static byte[] DecryptData(System.Security.Cryptography.RSACryptoServiceProvider full_rsa, byte[] data) { System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.MemoryStream(data)); int encryptedkeylength = br.ReadInt32(); int aeskeylength = br.ReadInt32(); int aesivlength = br.ReadInt32(); byte[] encryptedaeskey = br.ReadBytes(encryptedkeylength); byte[] encrypteddata = br.ReadBytes((int)(data.Length - br.BaseStream.Position)); br.Close(); byte[] decryptedkey = full_rsa.Decrypt(encryptedaeskey, false); br = new System.IO.BinaryReader(new System.IO.MemoryStream(decryptedkey)); using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create()) { byte[] aeskey = br.ReadBytes(aeskeylength); byte[] aesiv = br.ReadBytes(aesivlength); System.Security.Cryptography.ICryptoTransform decryptor = myAes.CreateDecryptor(aeskey, aesiv); using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(csEncrypt)) { bw.Write(encrypteddata); } return(msDecrypt.ToArray()); } } } }
/// <summary> /// 解密 /// </summary> public static string RSADecrypt(string ciphertext) { System.Security.Cryptography.CspParameters param = new System.Security.Cryptography.CspParameters(); param.KeyContainerName = MY_TOKEN; using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(param)) { byte[] encryptdata = Convert.FromBase64String(ciphertext); byte[] decryptdata = rsa.Decrypt(encryptdata, false); return(System.Text.Encoding.Default.GetString(decryptdata)); } }
private byte[] RestoreFromTransport(List <byte[]> parts, System.Security.Cryptography.RSACryptoServiceProvider encryptor) { var list = new List <byte[]>(); foreach (var item in parts) { list.Add(encryptor.Decrypt(item, true)); } return(dodSON.Core.Common.ByteArrayHelper.RestoreByteArray(list)); }
public static byte[] RSADecrypt(byte[] input) { byte[] decrypted; using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(2048)) { rsa.PersistKeyInCsp = false; rsa.FromXmlString(privatekey); decrypted = rsa.Decrypt(input, false); } return(decrypted); }
public string Decrypt(string cipherText, string privateKey, bool padding) { var cipherBytes = Convert.FromBase64String(cipherText); using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(4096)) { rsa.FromXmlString(privateKey); var plainBytes = rsa.Decrypt(cipherBytes, padding); var plainText = System.Text.Encoding.ASCII.GetString(plainBytes); return(plainText); } }
/// <summary> /// Restores data by decrypting and joining all of the parts together. /// </summary> /// <param name="parts">A list of byte arrays encrypted and split into smaller chucks.</param> /// <param name="xmlPrivateKey">An XML string representation of a Private Key.</param> /// <returns>A byte array decrypted and reassembled from the <paramref name="parts"/>.</returns> public static byte[] RestoreFromTransport(List <byte[]> parts, string xmlPrivateKey) { var list = new List <byte[]>(); // create encryptor from private key System.Security.Cryptography.RSACryptoServiceProvider transportEncryptor = new System.Security.Cryptography.RSACryptoServiceProvider(DefaultRSAKeyLengthInBits); transportEncryptor.FromXmlString(xmlPrivateKey); // foreach (var item in parts) { list.Add(transportEncryptor.Decrypt(item, true)); } return(Common.ByteArrayHelper.RestoreByteArray(list)); }
//------------------------------------------------- public static string RsaDecrypt(string s, string key) { var encryptedBytes = System.Convert.FromBase64String(s); var doOaepPadding = false; var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(1024); // Import the RSA Key information. rsa.FromXmlString(key); // Export RSA key to RSAParameters and include: // false - Only public key required for encryption. // true - Private key required for decryption. // Encrypt the passed byte array and specify OAEP padding. var decryptedBytes = rsa.Decrypt(encryptedBytes, doOaepPadding); var decryptedString = System.Text.Encoding.UTF8.GetString(decryptedBytes); return decryptedString; }
public byte[] Decrypt(byte[] inputDataBytes, System.Security.Cryptography.RSAParameters rsaParameters) { byte[] decryptedData; //Create a new instance of RSACryptoServiceProvider. using (System.Security.Cryptography.RSACryptoServiceProvider csp = new System.Security.Cryptography.RSACryptoServiceProvider()) { // Import public key information. csp.ImportParameters(rsaParameters); // Decrypt the passed byte array and specify OAEP padding. // OAEP padding is only available on Microsoft Windows XP or later. decryptedData = csp.Decrypt(inputDataBytes, false); } return(decryptedData); }
public static string Decrypt(string privateKey, byte[] encryptedBytes) { System.Security.Cryptography.CspParameters cspParams = new System.Security.Cryptography.CspParameters { ProviderType = 1 }; System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey)); byte[] plainBytes = rsaProvider.Decrypt(encryptedBytes, false); string plainText = System.Text.Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length); return(plainText); }
/*複合化*/ public static string Decrypt(string str, string containerName) { //CspParametersオブジェクトの作成 System.Security.Cryptography.CspParameters cp = new System.Security.Cryptography.CspParameters(); //キーコンテナ名を指定する cp.KeyContainerName = containerName; //CspParametersを指定してRSACryptoServiceProviderオブジェクトを作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cp); //復号化する byte[] data = System.Convert.FromBase64String(str); byte[] decryptedData = rsa.Decrypt(data, false); return(System.Text.Encoding.UTF8.GetString(decryptedData)); }
/// <summary> /// 秘密鍵を使って文字列を復号化する /// </summary> /// <param name="str">Encryptメソッドにより暗号化された文字列</param> /// <param name="privateKey">復号化に必要な秘密鍵(XML形式)</param> /// <returns>復号化された文字列</returns> public static string Decrypt(string str, string privateKey) { //RSACryptoServiceProviderオブジェクトの作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); //秘密鍵を指定 rsa.FromXmlString(privateKey); //復号化する文字列をバイト配列に byte[] data = System.Convert.FromBase64String(str); //復号化する byte[] decryptedData = rsa.Decrypt(data, false); //結果を文字列に変換 return System.Text.Encoding.UTF8.GetString(decryptedData); }
public static string DecryptString(string inputString, int dwKeySize, string xmlString) { var rsaCryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(dwKeySize); rsaCryptoServiceProvider.FromXmlString(xmlString); int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ? (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4; int iterations = inputString.Length / base64BlockSize; var arrayList = new System.Collections.ArrayList(); for (int i = 0; i < iterations; i++) { byte[] encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i, base64BlockSize)); Array.Reverse(encryptedBytes); arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true)); } return(Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[])); }
public string Descriptografar(string chavePrivada, string criptografia) { System.Security.Cryptography.CspParameters config = new System.Security.Cryptography.CspParameters { ProviderType = 1 }; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(config); byte[] chavePrivadaBytes = Convert.FromBase64String(chavePrivada); rsa.ImportCspBlob(chavePrivadaBytes); byte[] criptografiaBytes = Convert.FromBase64String(criptografia); byte[] mensagemBytes = rsa.Decrypt(criptografiaBytes, false); string mensagem = Encoding.UTF8.GetString(mensagemBytes); return(mensagem); }
public static UserInfo DecryptIzendaAuthenticationMessage(string encryptedMessage) { var rsaPrivateKey = ConfigurationManager.AppSettings["RSAPrivateKey"]; var cipher = new System.Security.Cryptography.RSACryptoServiceProvider(); //Decrypt using RSA private key in PEM format. var rsaParam = ConvertPemToXmlFormat(rsaPrivateKey); cipher.ImportParameters(rsaParam); //End var resultBytes = Convert.FromBase64String(encryptedMessage); var decryptedBytes = cipher.Decrypt(resultBytes, false); var decryptedData = System.Text.Encoding.UTF8.GetString(decryptedBytes); var result = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(decryptedData); return result; }
/// <summary> /// RSA解密 /// </summary> /// <param name="byteArr_EncryptedContent">加密的byteArr</param> /// <param name="privatekey">私钥(可空)</param> /// <returns>解密内容</returns> public static byte[] Decrypt(byte[] byteArr_EncryptedContent, string privatekey = "") { if (privatekey.IsNullOrEmpty()) { privatekey = sPrivatekey; } System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(privatekey); int keySize = rsa.KeySize / 8; byte[] buffer = new byte[keySize]; byte[] r = null; // 解密结果 using (System.IO.MemoryStream msInput = new System.IO.MemoryStream(byteArr_EncryptedContent)) { using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream()) { int readLen = msInput.Read(buffer, 0, keySize); while (readLen > 0) { byte[] dataToDecrypt = new byte[readLen]; Array.Copy ( sourceArray: buffer, sourceIndex: 0, destinationArray: dataToDecrypt, destinationIndex: 0, length: readLen ); byte[] decrypted = rsa.Decrypt(rgb: dataToDecrypt, fOAEP: false); msOutput.Write(decrypted, 0, decrypted.Length); readLen = msInput.Read(buffer, 0, keySize); } r = msOutput.ToArray(); // 获得全部加密结果 rsa.Clear(); } } return(r); }
//私钥解密函数 public string RSADecryptPrv(string privKey, string encstr) { try { System.Security.Cryptography.RSACryptoServiceProvider myrsa = new System.Security.Cryptography.RSACryptoServiceProvider(); //得到私钥 myrsa.FromXmlString(privKey); //把原来加密后的String转换成byte[] byte[] PlainTextBArray = Convert.FromBase64String(encstr); //使用.NET中的Decrypt方法解密 byte[] DypherTextBArray = myrsa.Decrypt(PlainTextBArray, false); //转换解密后的byte[],得到加密前的内容 string outstr = (new UnicodeEncoding()).GetString(DypherTextBArray); return(outstr); } catch (Exception ex) { throw ex; } }
/// <summary> /// Decrypts the Izenda authentication message /// </summary> /// <param name="encryptedMessage"></param> /// <returns> the decrypted user information.</returns> public static UserInfo DecryptIzendaAuthenticationMessage(string encryptedMessage) { var rsaPrivateKey = ConfigurationManager.AppSettings["RSAPrivateKey"]; var cipher = new System.Security.Cryptography.RSACryptoServiceProvider(); //Decrypt using RSA private key in PEM format. var rsaParam = ConvertPemToXmlFormat(rsaPrivateKey); cipher.ImportParameters(rsaParam); //End ////Decrypt using RSA private key in XML format //rsaPrivateKey = "<RSAKeyValue><Modulus>zFZQcdI6f2yIg4m8fn+UnlGPa8Klf01ZIIPH1S2YFKmJpPIRGas04b2RGp+HqV5jmB4w7ClroK9kotuWKg1ySqaMOtg+n5cL/lbgx3j3LYFFsX9TZTwi+MBUpO9fBwBWs2Qly/fVziv4FY0p3YXBJOs/vZZNR5lwhw/dysF6LvU=</Modulus><Exponent>AQAB</Exponent><P>9XAmacVdbLsZOJdq11GvXnVpoeWmEI/52oLQ/3wUpBnDekNvspOMtle8G/7dKR3mm+qenkruTFxnDpfVV53G4w==</P><Q>1SFhB7AFT+/ehxDLgwdWEdBFRdkQzEbzNmk1lKgvZf8amipAw4n7DEjSoyqIXqXXr5DdyqSUDARylWnfzADCRw==</Q><DP>Bcsm7Po+sVFdUAuq9vgzpowo+Sxdlih/4luSKWW5awI8rgcnfNSkzq0VgKesesr85ZNNOTlVlLHdsOd+nrnXtw==</DP><DQ>RUqr3C77GykWRP1N3RS2g+Ydj37p+jAbBJaiB+nCNzwALx0Ln0ct6qmGaev7GCJ9BCRqJ2bohxuvESqxywZ4Iw==</DQ><InverseQ>zjfxF1xREc1TNjbFVUX0Bv+MaUZlqEszLH60WChxL7ArVka5DNbPsY889UMvWuM0/zymfIUlJcxHbMU9dmbuOg==</InverseQ><D>CevO8BfS+0jbv/c6DbJIFv/CxOqoemvY/fkoBLO4BJjOtBGEvwhPAv7fQrmoLpMEpuggW/cO4LhjXHzo55XLjLoRjBBbiPbZayaAeptP9oYMyBNwBp9d49taawXm7nxiOC8sszkzJ0gKFeN+plTQruDm+HspaGBmUHdCMlJ9zak=</D></RSAKeyValue>"; //cipher.FromXmlString(rsaPrivateKey); ////End Decrypt using RSA private key in XML format var resultBytes = Convert.FromBase64String(encryptedMessage); var decryptedBytes = cipher.Decrypt(resultBytes, false); var decryptedData = System.Text.Encoding.UTF8.GetString(decryptedBytes); var result = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfo>(decryptedData); return(result); }
public static string Decrypt(string stringToDecrypt, string key) { string result = null; if (string.IsNullOrEmpty(stringToDecrypt)) { //throw new ArgumentException("An empty string value cannot be encrypted."); } if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key."); } try { System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters(); cspp.KeyContainerName = key; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp); rsa.PersistKeyInCsp = true; string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, StringSplitOptions.None); byte[] decryptByteArray = Array.ConvertAll <string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber)))); byte[] bytes = rsa.Decrypt(decryptByteArray, true); result = System.Text.UTF8Encoding.UTF8.GetString(bytes); } catch (Exception ex) { throw new Exception(ex.Message); } finally { // no need for further processing } return(result); }
public static UserInfo DecryptIzendaAuthenticationMessage(string encryptedMessage) { string rsaPrivateKey = ""; try { string framework = Assembly .GetEntryAssembly()? .GetCustomAttribute <System.Runtime.Versioning.TargetFrameworkAttribute>()? .FrameworkName; if (framework.Contains("core", StringComparison.OrdinalIgnoreCase)) { IConfigurationRoot cb = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false) .Build(); rsaPrivateKey = cb.GetValue <string>("AppSettings:Settings:rsaPrivateKey"); } else { rsaPrivateKey = ConfigurationManager.AppSettings["RSAPrivateKey"]; } } catch { throw new Exception("Configuration / RSA key can't be found"); } var cipher = new System.Security.Cryptography.RSACryptoServiceProvider(); //Decrypt using RSA private key in PEM format. var rsaParam = ConvertPemToXmlFormat(rsaPrivateKey); cipher.ImportParameters(rsaParam); //End var resultBytes = Convert.FromBase64String(encryptedMessage); var decryptedBytes = cipher.Decrypt(resultBytes, false); var decryptedData = System.Text.Encoding.UTF8.GetString(decryptedBytes); var result = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfo>(decryptedData); return(result); }
public static UserInfo DecryptIzendaAuthenticationMessage(string encryptedMessage) { IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build(); var rsaPrivateKey = configuration.GetValue <string>("AppSettings:Settings:rsaPrivateKey"); var cipher = new System.Security.Cryptography.RSACryptoServiceProvider(); //Decrypt using RSA private key in PEM format. var rsaParam = ConvertPemToXmlFormat(rsaPrivateKey); cipher.ImportParameters(rsaParam); //End var resultBytes = Convert.FromBase64String(encryptedMessage); var decryptedBytes = cipher.Decrypt(resultBytes, false); var decryptedData = System.Text.Encoding.UTF8.GetString(decryptedBytes); var result = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfo>(decryptedData); return(result); }
private static async System.Threading.Tasks.Task <ResultType> TaskMain(Fee.Crypt.OnCryptTask_CallBackInterface a_callback_interface, byte[] a_binary, string a_key, Fee.TaskW.CancelToken a_cancel) #endif { ResultType t_ret; { t_ret.binary = null; t_ret.errorstring = null; } try{ using (System.Security.Cryptography.RSACryptoServiceProvider t_rsa = new System.Security.Cryptography.RSACryptoServiceProvider()){ t_rsa.FromXmlString(a_key); t_ret.binary = t_rsa.Decrypt(a_binary, false); } }catch (System.Exception t_exception) { t_ret.binary = null; t_ret.errorstring = "Task_DecryptPrivateKey : " + t_exception.Message; } if (a_cancel.IsCancellationRequested() == true) { t_ret.binary = null; t_ret.errorstring = "Task_DecryptPrivateKey : Cancel"; a_cancel.ThrowIfCancellationRequested(); } if (t_ret.binary == null) { if (t_ret.errorstring == null) { t_ret.errorstring = "Task_DecryptPrivateKey : null"; } } return(t_ret); }
/// <summary> /// RSA解密算法 /// </summary> /// <param name="Source">要解密的字符串</param> /// <returns>解密后的结果字符串</returns> public static string RSA_Decode(byte[] Source) { string str; System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider(); provider.FromXmlString("<RSAKeyValue><Modulus>pZGIiC3CxVYpTJ4dLylSy2TLXW+R9EyRZ39ekSosvRKf7iPuz4oPlHqjssh4Glbj/vTUIMFzHFC/9zC56GggNLfZBjh6fc3adq5cXGKlU74kAyM2z7gdYlUHtLT/GwDp4YcQKeSb9GjcvsXbUp0mrzI/axzueLIqK+R07rnv3yc=</Modulus><Exponent>AQAB</Exponent><P>0wCnxVUMgu+Uqp3UJ18bp9Ahdad36wDMwa0tmHxZJUvBZEfcYpsxmSHLpTUBCcAIg2eJL5g/iK9LrIwDBvUZ+w==</P><Q>yOB6ZwG9TuXMRPCA9cFTKCoHEsreDZluptHEfG3HvnS1lp5xwRCHXVuh7VWOM0G2gnZ/JWwWIfcqf30UTWvTxQ==</Q><DP>BTc67nHPwVzSu/TyzZZYRKmsahAdsr1uUktJmT9ZpMZenW/5Tqavby2arxbEU81faIAir/5/c42BvV4opP9iCQ==</DP><DQ>QETR5LMBxoRvXn80Q2yfFnKb4L9XXDKC3IywuL7G8YCVuKLo8kQ/ivcOT8jXvj6ADi2rcGWsjyFtT2zNWhftoQ==</DQ><InverseQ>jwpY6fpkzwtLOABZQncXMC4h7VbYrx+sZeSrBFXAgw1WMSs9YsT6EQcDRjpGt7JAkP14nSTSIVJNd23jZURCLw==</InverseQ><D>cw6SqcfbLVV198d9EnQOFEgkRvcsn2/CMAFET27WjkHuIAiagWE4+H7NWYWUaQFvCZNMAsNMYiX/cSFMYCRUFBBgkPqaqQ3+3qCs/kKiWpDjRwX8eXrMAnWniFDEoxc229Mxl4QZrcYKVRxrCIq8wKamuoWgwN0M+3CAiLwLvNk=</D></RSAKeyValue>"); try { str = System.Text.Encoding.UTF8.GetString(provider.Decrypt(Source, true)); } catch (System.Exception) { return ""; } return str; }
/// <summary> /// Decrypts a byte array. /// </summary> /// <param name="inBytes">Input bytes</param> /// <param name="fOAEP">'true' to perform direct RSA decryption using OAEP padding, 'false' to use PKCS#1 v1.5 padding</param> /// <returns>Decrypted byte array</returns> public byte[] decryptBytes(byte[] inBytes, bool fOAEP = true) { return(csp.Decrypt(inBytes, fOAEP)); }
public string decrypt(string privateKey, string encrypted) { System.Security.Cryptography.CspParameters cspParams = null; System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null; byte[] encryptedBytes = null; byte[] plainBytes = null; string result = ""; try { cspParams = new System.Security.Cryptography.CspParameters(); cspParams.ProviderType = 1; rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams); rsaProvider.FromXmlString(privateKey); encryptedBytes = Convert.FromBase64String(encrypted); plainBytes = rsaProvider.Decrypt(encryptedBytes, false); result = System.Text.Encoding.UTF8.GetString(plainBytes); } catch (Exception ex) { } return result; }
/// <summary> /// Loads the private key from a PFX file in the certificate store. /// </summary> public X509Certificate2 LoadPrivateKey(string thumbprint, string subjectName, System.Security.SecureString password) { if (m_certificateSubdir == null || !m_certificateSubdir.Exists) { return(null); } if (string.IsNullOrEmpty(thumbprint) && string.IsNullOrEmpty(subjectName)) { return(null); } foreach (FileInfo file in m_certificateSubdir.GetFiles("*.der")) { try { X509Certificate2 certificate = new X509Certificate2(file.FullName); if (!String.IsNullOrEmpty(thumbprint)) { if (!string.Equals(certificate.Thumbprint, thumbprint, StringComparison.CurrentCultureIgnoreCase)) { continue; } } if (!String.IsNullOrEmpty(subjectName)) { if (!Utils.CompareDistinguishedName(subjectName, certificate.Subject)) { if (subjectName.Contains("=") || !certificate.Subject.Contains("CN=" + subjectName)) { continue; } } } string fileRoot = file.Name.Substring(0, file.Name.Length - file.Extension.Length); StringBuilder filePath = new StringBuilder(); filePath.Append(m_privateKeySubdir.FullName); filePath.Append("\\"); filePath.Append(fileRoot); FileInfo privateKeyFile = new FileInfo(filePath.ToString() + ".pfx"); certificate = new X509Certificate2( privateKeyFile.FullName, (password == null)?new System.Security.SecureString():password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); System.Security.Cryptography.RSACryptoServiceProvider rsa = certificate.PrivateKey as System.Security.Cryptography.RSACryptoServiceProvider; if (rsa != null && rsa.CspKeyContainerInfo.Exportable) { int inputBlockSize = rsa.KeySize / 8 - 42; byte[] bytes1 = rsa.Encrypt(new byte[inputBlockSize], true); byte[] bytes2 = rsa.Decrypt(bytes1, true); if (bytes2 != null) { // Utils.Trace(1, "RSA: {0}", certificate.Thumbprint); return(certificate); } } return(certificate); } catch (Exception e) { Utils.Trace(e, "Could not load private key certificate from file: {0}", file.Name); } } return(null); }
/// <summary> /// Realizar el inicio de sesión para un usuario en la BD. /// </summary> /// <param name="NombreUsuario"></param> /// <param name="Pwd"></param> /// <returns>Objeto "RetornoInicioSesion" que indica el Resultado(true o false), Datos Globales del Sistema, el objeto Usuario CIPOL y un posible Mensaje de error.</returns> /// <history> /// [MartinV] [jueves, 25 de septiembre de 2014] Modificado GCP-Cambios 15585 /// </history> private mFormLogin IniciarSesion(string NombreUsuario, string Pwd, System.Net.CookieContainer cokie, string ip) { ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' // DESCRIPCION DE VARIABLES LOCALES //strUsuario : Nombre del usuario //objProxy : objeto proxy de conexion al servicio web //strCipol : objeto serializado de sipol, //strErro : string con mensaje de error si lo hubiera. //objEncSer : Objeto de encriptación RSA que contiene la clave pública // del servidor //strClave : Clave de encriptación //objEncCli : Objeto de encriptación RSA que contiene la clave pública // y privada del cliente ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' string strUsuario = null; COA.WebCipol.Fachada.FInicioSesion facInicioSesion = new COA.WebCipol.Fachada.FInicioSesion(); string strCipol = null; string strError = ""; string strClave = null; string strTerminal = null; mFormLogin objRetIS = new mFormLogin(); //Define variables locales. //System.Runtime.Serialization.Formatters.Binary.BinaryFormatter objDeserializador; //System.IO.MemoryStream objFlujo; byte[] bytPub; System.Security.Cryptography.RSACryptoServiceProvider objEncServ = new System.Security.Cryptography.RSACryptoServiceProvider(); System.Security.Cryptography.RSACryptoServiceProvider objEncCli = new System.Security.Cryptography.RSACryptoServiceProvider(); EntidadesEmpresariales.PadreCipolCliente objUsuarioCipol; TresDES objEncriptarNET; General objGeneral; try { strUsuario = NombreUsuario.Trim(); if (string.IsNullOrEmpty(strUsuario)) { objRetIS.Mensaje = "El nombre del usuario es un dato obligatorio."; objRetIS.ResultadoProcesoInicioSesion = false; return(objRetIS); } if (Pwd.Trim() == string.Empty) { objRetIS.Mensaje = "La contraseña es un dato obligatorio."; objRetIS.ResultadoProcesoInicioSesion = false; return(objRetIS); } strClave = Pwd; ManejoSesion.CookieMaster = cokie; System.Net.CookieContainer objCookieMASTER = ManejoSesion.CookieMaster; bytPub = facInicioSesion.GetClavePublica(objEncCli.ExportCspBlob(false), objCookieMASTER); if ((bytPub == null)) { objRetIS.Mensaje = "No se ha podido recuperar la clave pública."; objRetIS.ResultadoProcesoInicioSesion = false; return(objRetIS); } // Prepara el algoritmo asimétrico del servidor objEncServ.ImportCspBlob(bytPub); // Encripta con la clave pública strClave = System.Convert.ToBase64String(objEncServ.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(strClave), false)); strTerminal = COA.WebCipol.Presentacion.Utiles.cPrincipal.ObtenerTerminal(ip); strCipol = facInicioSesion.IniciarSesion(strUsuario, strTerminal, ref strError, strClave, objCookieMASTER); if (strCipol == null || string.IsNullOrEmpty(strCipol)) { objRetIS.Mensaje = "No se ha podido iniciar sesión" + (String.IsNullOrEmpty(strError) ? "" : ": " + strError).ToString(); objRetIS.ResultadoProcesoInicioSesion = false; return(objRetIS); } if (Validaciones.ValidarCadenaNulaOVacia(strError)) { objRetIS.Mensaje = strError; objRetIS.ResultadoProcesoInicioSesion = false; return(objRetIS); } //Dim objFlujo As System.IO.MemoryStream System.IO.MemoryStream objFlu; //Dim objDeserializador As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter() System.Runtime.Serialization.Formatters.Binary.BinaryFormatter objDeser = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //Dim objSerializar As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter() System.Runtime.Serialization.Formatters.Binary.BinaryFormatter objSerializar = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //objFlujo = New System.IO.MemoryStream(System.Convert.FromBase64CharArray(pStrCipol.ToCharArray, 0, pStrCipol.Length)) objFlu = new System.IO.MemoryStream(System.Convert.FromBase64CharArray(strCipol.ToCharArray(), 0, strCipol.Length)); //gobjUsuarioCipol = CType(objDeserializador.Deserialize(objFlujo), EntidadesEmpresariales.PadreCipolCliente) objUsuarioCipol = (EntidadesEmpresariales.PadreCipolCliente)objDeser.Deserialize(objFlu); //Desencripta los valores encriptados en el servidor con la clave pública del RSA cliente //gobjUsuarioCipol.OtrosDatos("clave.usuario", System.Text.UTF8Encoding.UTF8.GetString(objEncCli.Decrypt(System.Convert.FromBase64String(gobjUsuarioCipol.OtrosDatos("clave.usuario")), False))) objUsuarioCipol.OtrosDatos("clave.usuario", System.Text.UTF8Encoding.UTF8.GetString(objEncCli.Decrypt(System.Convert.FromBase64String(objUsuarioCipol.OtrosDatos("clave.usuario")), false))); //gobjUsuarioCipol.Key = System.Convert.ToBase64String(objEncCli.Decrypt(System.Convert.FromBase64String(gobjUsuarioCipol.Key), False)) objUsuarioCipol.Key = System.Convert.ToBase64String(objEncCli.Decrypt(System.Convert.FromBase64String(objUsuarioCipol.Key), false)); //gobjUsuarioCipol.IV = System.Convert.ToBase64String(objEncCli.Decrypt(System.Convert.FromBase64String(gobjUsuarioCipol.IV), False)) objUsuarioCipol.IV = System.Convert.ToBase64String(objEncCli.Decrypt(System.Convert.FromBase64String(objUsuarioCipol.IV), false)); //TODO: VER QUE PASA CON LAS COOKIES //gobjUsuarioCipol.objColeccionDeCookies = pCookies //objUsuarioCipol.objColeccionDeCookiesCipol = //gobjUsuarioCipol.gobjRSAServ = objEncServ.ExportCspBlob(False) objUsuarioCipol.gobjRSAServ = objEncServ.ExportCspBlob(false); //gobjUsuarioCipol.OtrosDatos("urlwsInicioSesion", UrlWsInicioSesion) //objFlujo = New System.IO.MemoryStream() //objFlu= new System.IO.MemoryStream(); //objSerializar.Serialize(objFlujo, gobjUsuarioCipol) //objSerializar.Serialize(objFlu, objUsuarioCipol); //gstrUsuarioCipol = System.Convert.ToBase64String(objFlujo.ToArray()) //gstrUsuarioCipol = System.Convert.ToBase64String(objFlujo.ToArray()) //Crea el objeto para encriptar. objEncriptarNET = new TresDES(); objEncriptarNET.IV = objUsuarioCipol.IV; objEncriptarNET.Key = objUsuarioCipol.Key; //Crea el objeto con datos generales del usuario/sistema. objGeneral = new General(System.Reflection.Assembly.GetExecutingAssembly()); objGeneral.AcercaDe_Descripcion = "Componente de Seguridad. Desarrollado por COA S.A."; objGeneral.AcercaDe_Detalle = "Configurador Interactivo de Políticas de seguridad de los sistemas. Resuelve las funciones operativas propias de la seguridad de sistemas (implementación de políticas, administración de usuarios, roles, acceso a subsistemas)."; //TODO: HAY QUE EVALUAR COMO SE TRABAJA CON ESTA INFORMACION SI ES NECESARIA //objGeneral.AcercaDe_Logo = objGeneral.RutaArchivos + "img_CIPOL_CIPOL.jpg"; //objGeneral.AcercaDe_Logo = "Imagenes/prod_cipol.gif";//PRUEBA.. ver la imagen a poner!! //objGeneral.AcercaDe_Icono = objGeneral.RutaArchivos + "CIPOL32.ico"; objGeneral.AcercaDe_Cliente = objUsuarioCipol.NombreOrganizacion; objGeneral.UsuarioCIPOL = objUsuarioCipol.Login; objGeneral.Hoy = objUsuarioCipol.FechaServidor; //Pasa al objeto Datos Sistema, que se va a guardar en sesión. //objDatosS.NombreSistema = objGeneral.NombreSistema; //objDatosS.EncriptarNET = objEncriptarNET; DatosSistema objDatosS = new DatosSistema(); objDatosS.DatosGenerales = objGeneral; //Pasa al objeto de Retorno. objRetIS.DatosSistema = objDatosS; DatosCIPOL objDatosC = new DatosCIPOL(); objDatosC.DatosPadreCIPOLCliente = objUsuarioCipol; objDatosC.strCipol = strCipol; objDatosC.DatosPadreCIPOLCliente.objColeccionDeCookies = objCookieMASTER; objDatosC.DatosPadreCIPOLCliente.objColeccionDeCookiesCipol = objCookieMASTER; objRetIS.DatosCipol = objDatosC; objRetIS.Mensaje = "El proceso de inicio de sesión se realizó exitosamente"; objRetIS.ResultadoProcesoInicioSesion = true; return(objRetIS); } catch (Exception ex) { COA.Logger.Logueador.Loggear(ex, System.Diagnostics.EventLogEntryType.Error); objRetIS.ResultadoProcesoInicioSesion = false; objRetIS.Mensaje = "Ocurrió un error en el proceso de inicio de sesión."; return(objRetIS); } }
private void btnParse_Click(object sender, EventArgs e) { if (this.bmp == null) { MessageBox.Show(this, "Please select an image first.", "Does not compute...", MessageBoxButtons.OK); this.cmdSelectSrc_Click(sender, e); return; } bool done = false; int seed = bmp.GetPixel(0, 0).ToArgb(); Color cPwReq = bmp.GetPixel(1, 0); byte[] rsaBlob = null; if (cPwReq.R % 2 == 0 && cPwReq.G % 2 == 0 && cPwReq.B % 2 == 0) { using (frmPw frm = new frmPw()) if (frm.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(frm.Password)) { seed = (seed.ToString() + frm.Password.ToString()).GetHashCode(); //rsaBlob = System.Text.Encoding.UTF8.GetBytes(seed.ToString()); } } Dictionary <string, string> cypher = this.GetCypher(seed, true); int x = 3, y = 0; StringBuilder identCheck = new StringBuilder(); #region Old Read Method //for (int i = 0; i < identString.Length; i++) //{ // if (x++ > bmp.Width) // { x = 0; y++; } // Color cPxl1 = bmp.GetPixel(x, y); // int r1 = Convert.ToInt32(cPxl1.R), // g1 = Convert.ToInt32(cPxl1.G), // b1 = Convert.ToInt32(cPxl1.B); // if (x++ > bmp.Width) // { x = 0; y++; } // Color cPxl2 = bmp.GetPixel(x, y); // int r2 = Convert.ToInt32(cPxl2.R), // g2 = Convert.ToInt32(cPxl2.G), // b2 = Convert.ToInt32(cPxl2.B); // if (x++ > bmp.Width) // { x = 0; y++; } // Color cPxl3 = bmp.GetPixel(x, y); // int r3 = Convert.ToInt32(cPxl3.R), // g3 = Convert.ToInt32(cPxl3.G), // b3 = Convert.ToInt32(cPxl3.B); // int c1 = (r1 % 2), // c2 = (g1 % 2), // c3 = (b1 % 2), // c4 = (r2 % 2), // c5 = (g2 % 2), // c6 = (b2 % 2), // c7 = (r3 % 2), // c8 = (g3 % 2), // c9 = (b3 % 2); // string cypherCode = GetCypherCode(c1, c2, c3, c4, c5, c6, c7, c8); // try // { identCheck.Append(cypher[cypherCode]); } // catch // { break; } //} #endregion string msgText = null; using (System.IO.FileStream fs = new System.IO.FileStream(this._imgFn, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { //int identBufferLen = (identString.Length * 9) + x; //byte[] fsBuffer = new byte[identBufferLen]; //fs.Read(fsBuffer, 0, fsBuffer.Length); //for (int i = x; i < fsBuffer.Length; i += 9) //{ // if (i > fsBuffer.Length) // throw new Exception("Key check exceeded buffer length."); // int[] vals = new int[8]; // for (int j = 0; j < 8; j++) // vals[j] = (fsBuffer[i] % 2); // string cypherCode = GetCypherCode(vals); // try // { identCheck.Append(cypher[cypherCode]); } // catch // { break; } // x += 9; //} for (int i = x; i < identString.Length + 3; i++) { Color cPxl1 = bmp.GetPixel(x, y); int r1 = Convert.ToInt32(cPxl1.R), g1 = Convert.ToInt32(cPxl1.G), b1 = Convert.ToInt32(cPxl1.B); if (x++ > bmp.Width) { x = 0; y++; } Color cPxl2 = bmp.GetPixel(x, y); int r2 = Convert.ToInt32(cPxl2.R), g2 = Convert.ToInt32(cPxl2.G), b2 = Convert.ToInt32(cPxl2.B); if (x++ > bmp.Width) { x = 0; y++; } Color cPxl3 = bmp.GetPixel(x, y); int r3 = Convert.ToInt32(cPxl3.R), g3 = Convert.ToInt32(cPxl3.G), b3 = Convert.ToInt32(cPxl3.B); int c1 = (r1 % 2), c2 = (g1 % 2), c3 = (b1 % 2), c4 = (r2 % 2), c5 = (g2 % 2), c6 = (b2 % 2), c7 = (r3 % 2), c8 = (g3 % 2), c9 = (b3 % 2); // Determine the bits "code value" and find the matching character in the cypher. string cypherCode = GetCypherCode(c1, c2, c3, c4, c5, c6, c7, c8); identCheck.Append(cypher[cypherCode]); } if (identCheck.ToString() != identString) { MessageBox.Show(this, "No message detected.", "Sorry"); return; } StringBuilder sbMsg = new StringBuilder(); x = identString.Length + 2; y = 0; while (!done) { // Every three pixels contains 8 "bits" of cypher code, and the // 9th byte tells us if we're done (by being an odd number). if (x++ > bmp.Width) { x = 0; y++; } Color cPxl1 = bmp.GetPixel(x, y); int r1 = Convert.ToInt32(cPxl1.R), g1 = Convert.ToInt32(cPxl1.G), b1 = Convert.ToInt32(cPxl1.B); if (x++ > bmp.Width) { x = 0; y++; } Color cPxl2 = bmp.GetPixel(x, y); int r2 = Convert.ToInt32(cPxl2.R), g2 = Convert.ToInt32(cPxl2.G), b2 = Convert.ToInt32(cPxl2.B); if (x++ > bmp.Width) { x = 0; y++; } Color cPxl3 = bmp.GetPixel(x, y); int r3 = Convert.ToInt32(cPxl3.R), g3 = Convert.ToInt32(cPxl3.G), b3 = Convert.ToInt32(cPxl3.B); int c1 = (r1 % 2), c2 = (g1 % 2), c3 = (b1 % 2), c4 = (r2 % 2), c5 = (g2 % 2), c6 = (b2 % 2), c7 = (r3 % 2), c8 = (g3 % 2), c9 = (b3 % 2); // Determine the bits "code value" and find the matching character in the cypher. string cypherCode = GetCypherCode(c1, c2, c3, c4, c5, c6, c7, c8); sbMsg.Append(cypher[cypherCode]); // Then decide if we should keep processing based on whether the 6th bit // was divisible by 2. if (c9 != 0) { done = true; break; } x += 9; #region New read method is wrong. Deals with pixels as though they were one byte each and starts are wrong position. //byte[] fsBufferMsg = new byte[9]; //fs.Read(fsBufferMsg, x, fsBufferMsg.Length); //int[] vals = new int[9]; //for (int j = 0; j < 9; j++) // vals[j] = (fsBufferMsg[j] % 2); //string cypherCode = GetCypherCode(vals); //sbMsg.Append(cypher[cypherCode]); //// then decide if we should keep processing based on whether the //// 9th byte was divisible by 2. //if (vals[8] != 0) //{ // done = true; // break; //} //x += 9; #endregion } msgText = sbMsg.ToString(); } Color cRsa = bmp.GetPixel(2, 0); if (cRsa.R % 2 == 0 && cRsa.G % 2 == 0 && cRsa.B % 2 == 0 && rsaBlob != null) { System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); //rsa.ImportCspBlob(rsa.Encrypt(rsaBlob, true)); byte[] rsaData = rsa.Decrypt(Convert.FromBase64String(msgText), true); msgText = System.Text.Encoding.UTF8.GetString(rsaData); } MessageBox.Show(this, "Image Says:\n\n" + msgText, "Message"); }