Пример #1
0
        /// <summary>
        /// 公開鍵を使って文字列を暗号化する
        /// </summary>
        /// <param name="str">暗号化する文字列</param>
        /// <param name="publicKey">暗号化に使用する公開鍵(XML形式)</param>
        /// <returns>暗号化された文字列</returns>
        public static string Encrypt(string str, string publicKey)
        {
            //RSACryptoServiceProviderオブジェクトの作成
            System.Security.Cryptography.RSACryptoServiceProvider rsa =
                new System.Security.Cryptography.RSACryptoServiceProvider();

            //公開鍵を指定
            rsa.FromXmlString(publicKey);

            //暗号化する文字列をバイト配列に
            byte[] data = System.Text.Encoding.UTF8.GetBytes(str);
            //暗号化する
            //(XP以降の場合のみ2項目にTrueを指定し、OAEPパディングを使用できる)
            byte[] encryptedData = rsa.Encrypt(data, false);

            //Base64で結果を文字列に変換
            return System.Convert.ToBase64String(encryptedData);
        }
Пример #2
0
        public string encrypt(string publicKey, string plainText)
        {
            System.Security.Cryptography.CspParameters cspParams = null;
            System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null;
            byte[] plainBytes = null;
            byte[] encryptedBytes = null;

            string result = "";
            try
            {
                cspParams = new System.Security.Cryptography.CspParameters();
                cspParams.ProviderType = 1;
                rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams);

                rsaProvider.FromXmlString(publicKey);

                plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
                encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
                result = Convert.ToBase64String(encryptedBytes);
            }
            catch (Exception ex) { }
            return result;
        }
Пример #3
0
        //***************************************************************************
        // Event Handlers
        //
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.bmp == null)
            {
                return;
            }

            #region Old Write Method
            //// The color code of the very first pixel gives of the cypher "seed".
            //int seed = bmp.GetPixel(0, 0).ToArgb();
            //Color cPwReq = bmp.GetPixel(1, 0);
            //int cPwReqR = cPwReq.R, cPwReqG = cPwReq.G, cPwReqB = cPwReq.B;
            //byte[] rsaBlob = null;
            //using (frmPw frm = new frmPw())
            //    if (frm.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(frm.Password))
            //    {
            //        seed = (seed.ToString() + frm.Password).GetHashCode();
            //        rsaBlob = System.Text.Encoding.UTF8.GetBytes(seed.ToString());
            //        if (cPwReqR % 2 != 0)
            //            if (cPwReqR < 255) cPwReqR++; else cPwReqR--;
            //        if (cPwReqG % 2 != 0)
            //            if (cPwReqG < 255) cPwReqG++; else cPwReqG--;
            //        if (cPwReqB % 2 != 0)
            //            if (cPwReqB < 255) cPwReqB++; else cPwReqB--;
            //    }

            //cPwReq = Color.FromArgb(cPwReq.A, cPwReqR, cPwReqG, cPwReqB);
            //bmp.SetPixel(1, 0, cPwReq);

            //Dictionary<string, string> cypher = this.GetCypher(seed, false);
            //string encryptString = this.textBox1.Text;

            //if (this.chkEncrypt.Checked && rsaBlob != null)
            //{
            //    System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
            //    rsa.ImportCspBlob(rsa.Encrypt(rsaBlob, true));
            //    byte[] rsaData = rsa.Encrypt(System.Text.Encoding.UTF8.GetBytes(encryptString), true);
            //    encryptString = Convert.ToBase64String(rsaData);

            //    Color cRsa = bmp.GetPixel(2, 0);
            //    int cRsaR = cRsa.R, cRsaG = cRsa.G, cRsaB = cRsa.B;
            //    if (cRsaR % 2 != 0)
            //        if (cRsaR < 255) cRsaR++; else cRsaR--;
            //    if (cRsaG % 2 != 0)
            //        if (cRsaG < 255) cRsaG++; else cRsaG--;
            //    if (cRsaB % 2 != 0)
            //        if (cRsaB < 255) cRsaB++; else cRsaB--;
            //    bmp.SetPixel(2, 0, Color.FromArgb(cRsa.A, cRsaR, cRsaG, cRsaB));
            //}
            //encryptString = identString + encryptString;

            //// Now, we're ready to embed the text as a cypher.
            //int x = 2, y = 0;
            //for (int charPos = 0; charPos < encryptString.Length; charPos++)
            //{
            //    // First, get the character at the current position of the secret string.
            //    string curChar = encryptString.Substring(charPos, 1);

            //    // Now determine the character's cypher code.
            //    string cypherCode = string.Empty;

            //    try
            //    { cypherCode = cypher[curChar]; }
            //    catch
            //    // If we don't have that character in our cypher, just ignore it.
            //    {
            //        MessageBox.Show(this, "Unable to find cypher value for character: " + curChar, "Error");
            //        return;
            //    }

            //    // Then, we set the pixels' bits to match the cypher code.
            //    for (int i = 0; i < cypherCode.Length; i += 3)
            //    {
            //        if (x++ > bmp.Width)
            //        { x = 0; y++; }
            //        if (y > bmp.Height)
            //            throw new Exception("The image is too small to contain the selected text.");

            //        // Now, get the pixel at the current position.
            //        Color cpxl = bmp.GetPixel(x, y);
            //        int r = Convert.ToInt32(cpxl.R),
            //            g = Convert.ToInt32(cpxl.G),
            //            b = Convert.ToInt32(cpxl.B);

            //        if (cypherCode.Substring(i, 1) != (r % 2).ToString())
            //            if (r < 255) r++; else r--;
            //        if (cypherCode.Substring(i + 1, 1) != (g % 2).ToString())
            //            if (g < 255) g++; else g--;
            //        if (i + 2 < cypherCode.Length)
            //        {
            //            if (cypherCode.Substring(i + 2, 1) != (b % 2).ToString())
            //                if (b < 255) b++; else b--;
            //        }
            //        else
            //            // For the "ninth" byte in the two pixels, we define whether
            //            //   or not this is the last character with an odd number
            //            //   informing the program to stop parsing.
            //            if (charPos < encryptString.Length - 1)
            //            {
            //                if ((b % 2) != 0)
            //                { if (b < 255)b++; else b--; }
            //            }
            //            else
            //            {
            //                if ((b % 2) != 1)
            //                { if (b < 255)b++; else b--; }
            //            }

            //        // Once we have the correct color values, we need to save them
            //        //   back into the image.
            //        Color nClr = Color.FromArgb(cpxl.A, r, g, b);
            //        bmp.SetPixel(x, y, nClr);
            //    }
            //}
            #endregion

            string outputFn = null;
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.AddExtension = true;
                dlg.DefaultExt   = ".bmp";
                dlg.Filter       = "Image Files|*.bmp;*.jpg;*gif;*.png;*.jpeg;*.tiff|All Files|*.*";
                dlg.FilterIndex  = 0;
                dlg.Title        = "Select Image File";
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    outputFn = dlg.FileName;
                }
                else
                {
                    return;
                }
            }
            // The color code of the very first pixel gives of the cypher "seed".
            int    seed = bmp.GetPixel(0, 0).ToArgb();
            Color  cPwReq = bmp.GetPixel(1, 0);
            int    cPwReqR = cPwReq.R, cPwReqG = cPwReq.G, cPwReqB = cPwReq.B;
            byte[] rsaBlob = null;
            using (frmPw frm = new frmPw())
                if (frm.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(frm.Password))
                {
                    seed    = (seed.ToString() + frm.Password).GetHashCode();
                    rsaBlob = System.Text.Encoding.UTF8.GetBytes(seed.ToString());
                    if (cPwReqR % 2 != 0)
                    {
                        if (cPwReqR < 255)
                        {
                            cPwReqR++;
                        }
                        else
                        {
                            cPwReqR--;
                        }
                    }
                    if (cPwReqG % 2 != 0)
                    {
                        if (cPwReqG < 255)
                        {
                            cPwReqG++;
                        }
                        else
                        {
                            cPwReqG--;
                        }
                    }
                    if (cPwReqB % 2 != 0)
                    {
                        if (cPwReqB < 255)
                        {
                            cPwReqB++;
                        }
                        else
                        {
                            cPwReqB--;
                        }
                    }
                }

            cPwReq = Color.FromArgb(cPwReq.A, cPwReqR, cPwReqG, cPwReqB);
            bmp.SetPixel(1, 0, cPwReq);

            Dictionary <string, string> cypher = this.GetCypher(seed, false);
            string encryptString = this.textBox1.Text;

            if (this.chkEncrypt.Checked && rsaBlob != null)
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                //rsa.ImportCspBlob(rsa.Encrypt(rsaBlob, true));
                byte[] rsaData = rsa.Encrypt(System.Text.Encoding.UTF8.GetBytes(encryptString), true);
                encryptString = Convert.ToBase64String(rsaData);

                Color cRsa = bmp.GetPixel(2, 0);
                int   cRsaR = cRsa.R, cRsaG = cRsa.G, cRsaB = cRsa.B;
                if (cRsaR % 2 != 0)
                {
                    if (cRsaR < 255)
                    {
                        cRsaR++;
                    }
                    else
                    {
                        cRsaR--;
                    }
                }
                if (cRsaG % 2 != 0)
                {
                    if (cRsaG < 255)
                    {
                        cRsaG++;
                    }
                    else
                    {
                        cRsaG--;
                    }
                }
                if (cRsaB % 2 != 0)
                {
                    if (cRsaB < 255)
                    {
                        cRsaB++;
                    }
                    else
                    {
                        cRsaB--;
                    }
                }
                bmp.SetPixel(2, 0, Color.FromArgb(cRsa.A, cRsaR, cRsaG, cRsaB));
            }
            encryptString = identString + encryptString;

            // Now, we're ready to embed the text as a cypher.
            int x = 2, y = 0;
            for (int charPos = 0; charPos < encryptString.Length; charPos++)
            {
                // First, get the character at the current position of the secret string.
                string curChar = encryptString.Substring(charPos, 1);

                // Now determine the character's cypher code.
                string cypherCode = string.Empty;

                try
                { cypherCode = cypher[curChar]; }
                catch
                // If we don't have that character in our cypher, just ignore it.
                {
                    MessageBox.Show(this, "Unable to find cypher value for character: " + curChar, "Error");
                    return;
                }

                // Then, we set the pixels' bits to match the cypher code.
                for (int i = 0; i < cypherCode.Length; i += 3)
                {
                    if (++x >= bmp.Width)
                    {
                        x = 0; ++y;
                    }
                    if (y >= bmp.Height)
                    {
                        throw new Exception("The image is too small to contain the selected text.");
                    }

                    // Now, get the pixel at the current position.
                    Color cpxl = bmp.GetPixel(x, y);
                    int   r    = Convert.ToInt32(cpxl.R),
                          g    = Convert.ToInt32(cpxl.G),
                          b    = Convert.ToInt32(cpxl.B);

                    if (cypherCode.Substring(i, 1) != (r % 2).ToString())
                    {
                        if (r < 255)
                        {
                            r++;
                        }
                        else
                        {
                            r--;
                        }
                    }
                    if (cypherCode.Substring(i + 1, 1) != (g % 2).ToString())
                    {
                        if (g < 255)
                        {
                            g++;
                        }
                        else
                        {
                            g--;
                        }
                    }
                    if (i + 2 < cypherCode.Length)
                    {
                        if (cypherCode.Substring(i + 2, 1) != (b % 2).ToString())
                        {
                            if (b < 255)
                            {
                                b++;
                            }
                            else
                            {
                                b--;
                            }
                        }
                    }
                    else
                    // For the "ninth" byte in the two pixels, we define whether
                    //   or not this is the last character with an odd number
                    //   informing the program to stop parsing.
                    if (charPos < encryptString.Length - 1)
                    {
                        if ((b % 2) != 0)
                        {
                            if (b < 255)
                            {
                                b++;
                            }
                            else
                            {
                                b--;
                            }
                        }
                    }
                    else
                    {
                        if ((b % 2) != 1)
                        {
                            if (b < 255)
                            {
                                b++;
                            }
                            else
                            {
                                b--;
                            }
                        }
                    }

                    // Once we have the correct color values, we need to save them
                    //   back into the image.
                    Color nClr = Color.FromArgb(cpxl.A, r, g, b);
                    bmp.SetPixel(x, y, nClr);
                }
            }
            bmp.Save(outputFn, System.Drawing.Imaging.ImageFormat.Bmp);
        }
Пример #4
0
        /// <summary>
        /// 请求服务器进行加密。如果加密失败,连接将被断开,且抛出异常。
        /// </summary>
        public void RequestEncryption() {
            try {
                // 请求服务器 RSA 公钥
                var ret = Send(new byte[] { (byte)InternalCalls.RequestRSAPublicKey }, 0, 1, block: true, extraFlags: MessageFlags.InternalCalls);
                var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                rsa.PersistKeyInCsp = false;

                var keyxml = Encoding.UTF8.GetString(ret.Value.Array, ret.Value.Offset, ret.Value.Count);
                rsa.FromXmlString(keyxml);

                // 随机产生一个 AES 密钥和 IV,并发送给服务器
                var aesKeyAndIV = RandomHelper.NextStrongRandomByteArray(32, false);

                // 将 AES 密钥信息通过 RSA 加密
                var keyEncrypted = new byte[] { (byte)InternalCalls.SendAESKeysViaRSA }.Concat(rsa.Encrypt(aesKeyAndIV, true)).ToArray();

                ret = Send(keyEncrypted, 0, keyEncrypted.Length, block: true, extraFlags: MessageFlags.InternalCalls);

                // 判断返回值是否成功
                if (ret.HasValue && ret.Value.Count == 1 && ret.Value.Array[ret.Value.Offset] == 0) {
                    AesKey = aesKeyAndIV.Take(16).ToArray();
                    AesIV = aesKeyAndIV.Skip(16).ToArray();
                    IsEncrypted = true;
                    return;
                }

                closeSocket();
                throw new Exception("请求加密失败");
            }
            catch (Exception ex) {
                throw new Exception("请求加密失败", ex);
            }
        }
Пример #5
0
        /// <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);
        }
Пример #6
0
 public override byte[] GetBody()
 {
     MemoryStream stream = new MemoryStream();
     BinaryWriter writer = new BinaryWriter(stream);
     byte[] mashed = Mash(name, additionalNonce);
     writer.Write(mashed.Length);
     writer.Write(mashed, 0, mashed.Length);
     System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
     rsa.ImportCspBlob(publicKeyData);
     MemoryStream combiner = new MemoryStream();
     combiner.Write(startNonce, 0, startNonce.Length);
     combiner.Write(nonce, 0, nonce.Length);
     combiner.Write(passwordHash, 0, passwordHash.Length);
     combiner.Write(additionalNonce, 0, additionalNonce.Length);
     byte[] toSend = rsa.Encrypt(combiner.ToArray(), false);
     writer.Write(toSend.Length);
     writer.Write(toSend, 0, toSend.Length);
     writer.Flush();
     return stream.ToArray();
 }
Пример #7
0
        /// <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 string AdministrarContrasenia()
        {
            try
            {
                string strMensaje = string.Empty;
                string strClave;
                System.Security.Cryptography.RSACryptoServiceProvider objRSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                EntidadesEmpresariales.PadreCipolCliente objCipol            = (EntidadesEmpresariales.PadreCipolCliente)ManejoSesion.DatosCIPOLSesion.DatosPadreCIPOLCliente;
                FSeguridad    objFachada      = new FSeguridad();
                FInicioSesion objInicioSesion = new FInicioSesion();

                objRSA.ImportCspBlob(objCipol.gobjRSAServ);
                strClave = CurrentPassword.Text.Trim();
                strClave = System.Convert.ToBase64String(objRSA.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(strClave), false));

                if (CurrentPassword.Text.Trim().Equals(NewPassword.Text.Trim()))
                {
                    return(COA.Cipol.Presentacion.PaginaPadre.RetornaMensajeUsuario(50));
                }

                if (NewPassword.Text.Trim().Length < ManejoSesion.gudParam.LongitudContraseña)
                {
                    if (objInicioSesion.Auditar(COA.WebCipol.Inicio.Utiles.cPrincipal.MensajeAuditoria(500, objCipol.Login, "", "")))
                    {
                        return("La contraseña especificada debe tener una longitud mínima de " + ManejoSesion.gudParam.LongitudContraseña + " caracteres.");
                    }
                    else
                    {
                        return("No se ha podido realizar el proceso solicitado.");
                    }
                }

                if (!NewPassword.Text.Trim().Equals(ConfirmNewPassword.Text.Trim()))
                {
                    if (objInicioSesion.Auditar(COA.WebCipol.Inicio.Utiles.cPrincipal.MensajeAuditoria(190, objCipol.Login, "", "")))
                    {
                        return(COA.Cipol.Presentacion.PaginaPadre.RetornaMensajeUsuario(55));
                    }
                    else
                    {
                        return("No se ha podido realizar el proceso solicitado.");
                    }
                }

                string strNuevaContraseña;
                strNuevaContraseña = NewPassword.Text.Trim();
                string strTemp = ValidarSeguridadContrasenia(ref strNuevaContraseña);

                if (!string.IsNullOrEmpty(strTemp.Trim()))
                {
                    if (objInicioSesion.Auditar(COA.WebCipol.Inicio.Utiles.cPrincipal.MensajeAuditoria(205, objCipol.Login, "", "")))
                    {
                        return(strTemp);
                    }
                    else
                    {
                        return("No se ha podido realizar el proceso solicitado.");
                    }
                }

                COA.WebCipol.Entidades.ClasesWs.dcRecuperarDatosParaABMUsuarios.dcRecuperarDatosParaABMUsuarios objResp = objFachada.RecuperarDatosParaABMUsuarios(objCipol.IDUsuario);


                strNuevaContraseña = System.Convert.ToBase64String(objRSA.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(strNuevaContraseña), false));
                if (!objInicioSesion.CambiarContrasenia(ManejoSesion.gudParam.CantidadContraseñasAlmacenadas,
                                                        objCipol.IDUsuario,
                                                        objCipol.Login,
                                                        COA.WebCipol.Inicio.Utiles.cPrincipal.MensajeAuditoria(210, objCipol.Login, "", ""),
                                                        strNuevaContraseña,
                                                        ManejoSesion.gudParam.DuracionContraseña,
                                                        ManejoSesion.ModoCambioClave,
                                                        strClave,
                                                        ref strMensaje,
                                                        ManejoSesion.gudParam.TiempoEnDiasNoPermitirCambiarContrasenia))
                {
                    if (strMensaje.Trim().ToUpper().Equals("OCURRIO ERROR"))
                    {
                        return("No se ha podido realizar el proceso solicitado.");
                    }
                    else
                    if (string.IsNullOrEmpty(strMensaje))
                    {
                        return(COA.Cipol.Presentacion.PaginaPadre.RetornaMensajeUsuario(50));
                    }
                    else
                    {
                        return(strMensaje);
                    }
                }

                return("");
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
Пример #9
0
 /// <summary>
 /// RSA加密算法
 /// </summary>
 /// <param name="Source">要加密的字符串</param>
 /// <returns>加密后的结果字符串</returns>
 public static byte[] RSA_Encode(string Source)
 {
     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></RSAKeyValue>");
     return provider.Encrypt(System.Text.Encoding.UTF8.GetBytes(Source), true);
 }