Buscar contenidos

jueves, 30 de marzo de 2017

Criptografía [Encrypting/Decrypting] métodos en C# para encriptar datos


Definición encripción ( código )



...En criptografía, el cifrado es un procedimiento que utiliza un algoritmo de cifrado con cierta clave (clave de cifrado) para transformar un mensaje, sin atender a su estructura lingüística o significado, de tal forma que sea incomprensible o, al menos, difícil de comprender a toda persona que no tenga la clave secreta (clave de descifrado) del algoritmo. Las claves de cifrado y de descifrado pueden ser iguales (criptografía simétrica), (criptografía asimétrica) o (Criptografía híbrida)...

Link artículo

https://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt


   public static class Serialization
    {
        public static string ToJsonSerialize<T>(this T obj) where T : class
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream, obj);
                return Encoding.Default.GetString(stream.ToArray());
            }
        }

        public static T ToJsonDeserialize<T>(this T obj, string json) where T : class
        {
            using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return serializer.ReadObject(stream) as T;
            }
        }

        public static string ToXmlSerialize<T>(this T obj)
        {
            try
            {
                string xmlString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xs.Serialize(xmlTextWriter, obj);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                xmlString = UTF8ByteArrayToString(memoryStream.ToArray()); return xmlString;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static T ToXmlDeserialize<T>(this string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));

            MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            return (T)xs.Deserialize(memoryStream);
        }

        private static string UTF8ByteArrayToString(byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        private static Byte[] StringToUTF8ByteArray(string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }


    }

-------------------

Ejemplo


  class Program
    {
        static void Main(string[] args)
        {
            string data = "Hello World";

            data = data.ToEncrypt();

            data = data.ToDecrypt();
        }

    }


   public static string EncodeAndEncrypt(this string value)
        {

            return System.Web.HttpUtility.UrlEncode(Encryption.ToEncrypt(value));

        }

        public static string EncodeAndDecrypt(this string value)
        {
            string res = System.Web.HttpUtility.UrlDecode(System.Web.HttpUtility.UrlEncode(value));

            return Encryption.ToDecrypt(res);
           

        }


    public static class Encryption
    {
        private static string PassEncryt = "1450Pass*-qq";

        public static string ToEncrypt(this string value)
        {
            return internalEncrypt(value, PassEncryt);
        }

        public static string ToDecrypt(this string value)
        {
            return internalDecrypt(value, PassEncryt);
        }

        private static string internalEncrypt(this string stringToEncrypt, string sEncryptionKey)
        {
            byte[] key = { };

            byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };

            byte[] inputByteArray;

            try
            {
                key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);

                cs.FlushFinalBlock();

                return (Convert.ToBase64String(ms.ToArray()));

            }
            catch (System.Exception ex)
            {
                return ex.Message;

            }
        }

        private static string internalDecrypt(this string stringToDecrypt, string sEncryptionKey)
        {
            byte[] key = { };

            byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
            byte[] inputByteArray = new byte[stringToDecrypt.Length];

            try
            {
                key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(stringToDecrypt);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);

                cs.FlushFinalBlock();
                Encoding encoding = Encoding.UTF8;
                return encoding.GetString(ms.ToArray());

            }
            catch (System.Exception ex)
            {
                return ex.Message;

            }
        }


    }

No hay comentarios:

Publicar un comentario