Пример #1
0
        public IEnumerable <RawSimpleEntity> EncryptAll(
            IEnumerable <RawSimpleEntity> entities, string password, byte[] salt)
        {
            if (String.IsNullOrEmpty(password))
            {
                foreach (var entity in entities)
                {
                    yield return(entity);
                }
            }

            var key = Hash(password, GetDataSalt(salt));

            foreach (var entity in entities)
            {
                RawSimpleEntity e = new RawSimpleEntity();
                e.Guid = entity.Guid;
                using (var ms = new MemoryStream())
                {
                    Rijndael rijndael = Rijndael.Create();
                    rijndael.Key = key;
                    rijndael.GenerateIV();
                    using (var cs = new CryptoStream(ms, rijndael.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(entity.Data, 0, entity.Data.Length);
                    }
                    var data = ms.ToArray();
                    e.Data = new byte[data.Length + 16];
                    Array.Copy(rijndael.IV, e.Data, 16);
                    Array.Copy(data, 0, e.Data, 16, data.Length);
                }
                yield return(e);
            }
        }
Пример #2
0
        private static string EncriptarTexto(string mensaje, byte[] clave)
        {
            Rijndael cifradoRijn = Rijndael.Create();

            byte[] byteEncriptado = null;
            byte[] byteSalida     = null;

            try
            {
                cifradoRijn.Key = clave;
                cifradoRijn.GenerateIV();

                byte[] byteEntrada = System.Text.Encoding.UTF8.GetBytes(mensaje);
                byteEncriptado = cifradoRijn.CreateEncryptor().TransformFinalBlock(byteEntrada, 0, byteEntrada.Length);
                byteSalida     = new byte[cifradoRijn.IV.Length + byteEncriptado.Length];
                cifradoRijn.IV.CopyTo(byteSalida, 0);
                byteEncriptado.CopyTo(byteSalida, cifradoRijn.IV.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                cifradoRijn.Clear();
            }

            string textoSalida = Encoding.Default.GetString(byteSalida);

            return(textoSalida);
        }
Пример #3
0
        public string Encriptar(string strEncriptar)
        {
            Rijndael miRijndael = Rijndael.Create();

            byte[] encrypted   = null;
            byte[] returnValue = null;

            try
            {
                miRijndael.Key = bytPK;
                miRijndael.GenerateIV();

                byte[] toEncrypt = System.Text.Encoding.UTF8.GetBytes(strEncriptar);
                encrypted = (miRijndael.CreateEncryptor()).TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);

                returnValue = new byte[miRijndael.IV.Length + encrypted.Length];
                miRijndael.IV.CopyTo(returnValue, 0);
                encrypted.CopyTo(returnValue, miRijndael.IV.Length);
            }
            finally
            {
                miRijndael.Clear();
            }

            return(Convert.ToBase64String(returnValue));
        }
Пример #4
0
 public byte[] EncryptString(string message)
 {
     byte[] encrypted;
     using (Rijndael rijAlg = Rijndael.Create())
     {
         rijAlg.Key = key;
         rijAlg.GenerateIV();
         rijAlg.Mode    = CipherMode.CBC;
         rijAlg.Padding = PaddingMode.PKCS7;
         byte[]           iv        = rijAlg.IV;
         ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
         using (MemoryStream msEncrypt = new MemoryStream())
         {
             msEncrypt.Write(iv, 0, iv.Length);
             using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
             {
                 using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                 {
                     swEncrypt.Write(message);
                     swEncrypt.Flush();
                 }
                 encrypted = msEncrypt.ToArray();
             }
         }
     }
     return(encrypted);
 }
Пример #5
0
        /// <summary>
        /// Encriptar cadena
        /// </summary>
        /// <param name="strEncriptar">Cadena a encriptar</param>
        /// <param name="bytPK">llave</param>
        /// <returns>Encriptacion</returns>
        private static byte[] Encriptar(string strEncriptar, byte[] bytPK)
        {
            Rijndael miRijndael = Rijndael.Create();

            miRijndael.Mode = CipherMode.CBC;
            byte[] encrypted   = null;
            byte[] returnValue = null;

            try
            {
                miRijndael.Key = bytPK;
                miRijndael.GenerateIV();

                byte[] toEncrypt = System.Text.Encoding.UTF8.GetBytes(strEncriptar);
                encrypted = (miRijndael.CreateEncryptor()).TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);

                returnValue = new byte[miRijndael.IV.Length + encrypted.Length];
                miRijndael.IV.CopyTo(returnValue, 0);
                encrypted.CopyTo(returnValue, miRijndael.IV.Length);
            }
            catch { }
            finally { miRijndael.Clear(); }

            return(returnValue);
        }
Пример #6
0
    public RAOPClient( string Host )
    {
        host = Host;

        volume = VOLUME_DEF;
        ajstatus = JACK_STATUS_DISCONNECTED;
        ajtype = JACK_TYPE_ANALOG;

        nfi = new CultureInfo( "en-US" ).NumberFormat;

        alg = Rijndael.Create();
        alg.Mode = CipherMode.CBC;
        alg.Padding = PaddingMode.None;
        alg.KeySize = 128;

        alg.GenerateKey();
        alg.GenerateIV();

        int i = host.LastIndexOf( '.' );
        string hostnet = host.Substring( 0, i );
        IPHostEntry iphe = Dns.GetHostEntry(Dns.GetHostName());//Dns.GetHostByName( Dns.GetHostName() );
        foreach( IPAddress ipaddr in iphe.AddressList )
        {
            string s = ipaddr.ToString();
            if( s.StartsWith( hostnet ) )
            {
                local = s;
                break;
            }
        }

        if( local == null )
            local = Host;
    }
Пример #7
0
 public byte[] EncryptBytes(byte[] bytes)
 {
     if (bytes.Length == 0)
     {
         return(bytes);
     }
     byte[] encrypted;
     using (Rijndael rijAlg = Rijndael.Create()) {
         rijAlg.Key = key;
         rijAlg.GenerateIV();
         rijAlg.Mode    = CipherMode.CBC;
         rijAlg.Padding = PaddingMode.PKCS7;
         byte[]           iv        = rijAlg.IV;
         ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
         using (MemoryStream msEncrypt = new MemoryStream())
         {
             msEncrypt.Write(iv, 0, iv.Length);
             using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
             {
                 csEncrypt.Write(bytes, 0, bytes.Length);
                 csEncrypt.FlushFinalBlock();
                 encrypted = msEncrypt.ToArray();
             }
         }
     }
     return(encrypted);
 }
Пример #8
0
        string TextEncryption(string message, byte[] key)
        {
            Rijndael rijndael = Rijndael.Create();

            byte[] encryptByte = null;
            byte[] outputByte  = null;
            try
            {
                rijndael.Key = key;
                rijndael.GenerateIV();
                byte[] inputByte = Encoding.UTF8.GetBytes(message);
                encryptByte = rijndael.CreateEncryptor().TransformFinalBlock(inputByte, 0, inputByte.Length);
                outputByte  = new byte[rijndael.IV.Length + encryptByte.Length];
                rijndael.IV.CopyTo(outputByte, 0);
                encryptByte.CopyTo(outputByte, rijndael.IV.Length);
                ;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                rijndael.Clear();
            }
            string output = Encoding.Default.GetString(outputByte);

            return(output);
        }
Пример #9
0
        public static byte[] Encriptar(string strEncriptar, byte[] bytPK)
        {
            Rijndael rijndael = Rijndael.Create();

            byte[] buffer = null;
            byte[] array  = null;
            try
            {
                rijndael.Key = bytPK;
                rijndael.GenerateIV();
                byte[] bytes = Encoding.UTF8.GetBytes(strEncriptar);
                buffer = rijndael.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);
                array  = new byte[rijndael.IV.Length + buffer.Length];
                rijndael.IV.CopyTo(array, 0);
                buffer.CopyTo(array, rijndael.IV.Length);
            }
            catch
            {
            }
            finally
            {
                rijndael.Clear();
            }
            return(array);
        }
Пример #10
0
    public static byte[] AESEncrypt(string plainText)
    {
        byte[] bKey      = Encoding.UTF8.GetBytes(ConfigurationController.Instance._AesKey);
        byte[] byteArray = Encoding.UTF8.GetBytes(plainText);

        byte[]   encrypt = null;
        Rijndael aes     = Rijndael.Create();

        aes.GenerateIV();
        aes.Mode = CipherMode.CFB;
        try {
            using (MemoryStream mStream = new MemoryStream()) {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, aes.IV), CryptoStreamMode.Write)) {
                    cStream.Write(aes.IV, 0, aes.IV.Length);
                    cStream.Write(byteArray, 0, byteArray.Length);
                    cStream.FlushFinalBlock();
                    encrypt = mStream.ToArray();
                }
            }
        } catch (Exception e) {
            LogManager.Log(e);
            return(null);
        } finally {
            aes.Clear();
        }

        return(encrypt);
    }
Пример #11
0
        private byte[] DiffieHellmanClient(Rijndael newRijndael)
        {
            ECDiffieHellmanCng ECDF = new ECDiffieHellmanCng();
            ECDF.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            ECDF.HashAlgorithm = CngAlgorithm.Sha256;
            byte[] pubkey = ECDF.PublicKey.ToByteArray();

            string base64pubkey = Convert.ToBase64String(pubkey);

            Send(dataStream, base64pubkey); //pošlje javni ključ kot base64

            string serverPublicKey = Recieve(dataStream); //prejme njegov javni ključ

            //byte[] iv = Encoding.UTF32.GetBytes("sestnajst1234567");
            //Send(dataStream, Convert.ToBase64String(iv));
            newRijndael.GenerateIV();
            iv = Convert.ToBase64String(newRijndael.IV);
            MessageBox.Show("iv je: " + iv);
            Send(dataStream, iv);

            byte[] byteServerKey = Convert.FromBase64String(serverPublicKey);
            byte[] sharedKey = ECDF.DeriveKeyMaterial(ECDiffieHellmanCngPublicKey.FromByteArray(byteServerKey, CngKeyBlobFormat.EccPublicBlob));

            return sharedKey;
        }
Пример #12
0
        public static string Encriptar(string cadenaEncriptar, byte[] bytPK)
        {
            Rijndael rijndael = Rijndael.Create();

            byte[] array  = null;
            byte[] array2 = null;

            try
            {
                rijndael.Key = bytPK;
                rijndael.GenerateIV();
                byte[] bytes = Encoding.UTF8.GetBytes(cadenaEncriptar);
                array  = rijndael.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);
                array2 = new byte[rijndael.IV.Length + array.Length];
                rijndael.IV.CopyTo(array2, 0);
                array.CopyTo(array2, rijndael.IV.Length);
                return(Convert.ToBase64String(array2));
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                rijndael.Clear();
            }
        }
Пример #13
0
        //With the AsymmetricEncrypt we are going to encrypt the symmetric keys

        public static MemoryStream HybridEnryption(MemoryStream clearFile, string publicKey)
        {
            Rijndael myAlg = Rijndael.Create();

            myAlg.GenerateKey(); //secretkey
            myAlg.GenerateIV();  //iv

            var key = myAlg.Key;
            var iv  = myAlg.IV;

            byte[] fileInBytes   = clearFile.ToArray();
            var    encryptedFile = SymmetricEncrypt(fileInBytes, iv, key);

            byte[] encryptedKey = AsymmetricEncrypt(key, publicKey);
            byte[] encryptedIv  = AsymmetricEncrypt(iv, publicKey);

            MemoryStream msOut = new MemoryStream();

            msOut.Write(encryptedKey, 0, encryptedKey.Length);
            msOut.Write(encryptedIv, 0, encryptedIv.Length);

            MemoryStream encryptedFileContent = new MemoryStream(encryptedFile);

            encryptedFileContent.Position = 0;
            encryptedFileContent.CopyTo(msOut);

            return(msOut);
        }
Пример #14
0
            static byte[] Encrypt(byte[] buff, byte[] dat, out byte[] iv, byte key)
            {
                dat = (byte[])dat.Clone();
                SHA512 sha = SHA512.Create();

                byte[] c = sha.ComputeHash(buff);
                for (int i = 0; i < dat.Length; i += 64)
                {
                    byte[] o   = new byte[64];
                    int    len = dat.Length <= i + 64 ? dat.Length : i + 64;
                    Buffer.BlockCopy(dat, i, o, 0, len - i);
                    for (int j = i; j < len; j++)
                    {
                        dat[j] ^= (byte)(c[j - i] ^ key);
                    }
                    c = sha.ComputeHash(o);
                }

                Rijndael ri = Rijndael.Create();

                ri.GenerateIV(); iv = ri.IV;
                MemoryStream ret = new MemoryStream();

                using (CryptoStream cStr = new CryptoStream(ret, ri.CreateEncryptor(SHA256.Create().ComputeHash(buff), iv), CryptoStreamMode.Write))
                    cStr.Write(dat, 0, dat.Length);
                return(ret.ToArray());
            }
Пример #15
0
        } //compute hash from arguments and return hash value as string

        private static string GetRijndaelHash(string text)
        {
            //create variables for computing hash and making it a string
            UnicodeEncoding UniCode = new UnicodeEncoding();

            byte[]   HashResult;
            byte[]   msg        = UniCode.GetBytes(text);
            Rijndael hashString = RijndaelManaged.Create();

            //generate a weak KEY and Initialization Vector for the hash algorithm
            hashString.GenerateKey();
            hashString.GenerateIV();
            ICryptoTransform encryptor = hashString.CreateEncryptor(hashString.Key, hashString.IV);
            string           Str       = "";

            //compute hash with Rijndael module and format output as string
            //convert bytes in HashResult to string values
            HashResult = encryptor.TransformFinalBlock(msg, 0, msg.Length);
            foreach (byte x in HashResult)
            {
                Str += String.Format("{0:x2}", x);
            }

            //clear excess resource usage
            hashString.Clear();
            return(Str);
        } //compute hash from arguments and return hash value as string
Пример #16
0
        private static void TestShims(Rijndael alg)
        {
            alg.BlockSize = 128;
            Assert.Equal(128, alg.BlockSize);

            var emptyIV = new byte[alg.BlockSize / 8];

            alg.IV = emptyIV;
            Assert.Equal(emptyIV, alg.IV);
            alg.GenerateIV();
            Assert.NotEqual(emptyIV, alg.IV);

            var emptyKey = new byte[alg.KeySize / 8];

            alg.Key = emptyKey;
            Assert.Equal(emptyKey, alg.Key);
            alg.GenerateKey();
            Assert.NotEqual(emptyKey, alg.Key);

            alg.KeySize = 128;
            Assert.Equal(128, alg.KeySize);

            alg.Mode = CipherMode.ECB;
            Assert.Equal(CipherMode.ECB, alg.Mode);

            alg.Padding = PaddingMode.PKCS7;
            Assert.Equal(PaddingMode.PKCS7, alg.Padding);
        }
Пример #17
0
        public static string Encrypt(string plain, string password)
        {
            if (password == null)
            {
                return(plain);
            }

            //convert password to key
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT);

            byte[] encrypted;
            byte[] iv;

            //Create instance of the rijndael encryption algorithm
            using (Rijndael rijndael = Rijndael.Create())
            {
                rijndael.Key = pdb.GetBytes(32);
                rijndael.GenerateIV();
                iv = rijndael.IV;

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(cryptoStream))
                        {
                            swEncrypt.Write(plain);
                        }
                        encrypted = memoryStream.ToArray();
                    }
                }
            }
            return(Convert.ToBase64String(iv.Concat(encrypted).ToArray()));
        }
Пример #18
0
        /// <summary>
        /// Función para encriptar usuario y password e introducirlo en un Token de RECO para autenticarse en los servicios Web
        /// </summary>
        /// <param name="strEncriptar">Cadena que será encriptada</param>
        /// <param name="bytPK">Llave del servicio Web en Bytes</param>
        /// <returns></returns>
        private byte[] Encriptar(string strEncriptar, byte[] bytPK)
        {
            Rijndael rijndael = Rijndael.Create();

            byte[] numArray = (byte[])null /* TODO Change to default(_) if this is not a reference type */;

            try
            {
                rijndael.Key = bytPK;
                rijndael.GenerateIV();
                byte[] bytes1 = Encoding.UTF8.GetBytes(strEncriptar);
                byte[] bytes2 = rijndael.CreateEncryptor().TransformFinalBlock(bytes1, 0, bytes1.Length);
                numArray = new byte[rijndael.IV.Length + bytes2.Length - 1 + 1];
                rijndael.IV.CopyTo((Array)numArray, 0);
                string str1 = Encoding.Default.GetString(rijndael.IV);
                string str2 = Encoding.Default.GetString(bytes2);
                string str3;

                if (str1 == str2)
                {
                    str3 = str1 + "¯‡«í\0x25Ö›O\0x18\0x129öIǤqž";
                }

                bytes2.CopyTo((Array)numArray, rijndael.IV.Length);
            }
            catch
            {
            }
            finally
            {
                rijndael.Clear();
            }

            return(numArray);
        }
Пример #19
0
        static Rijndael CreateRijndael(byte[] userID, string password, string pepper)
        {
            if (userID == null)
            {
                throw new ArgumentNullException("userID");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (pepper == null)
            {
                throw new ArgumentNullException("pepper");
            }
            string   passpepper = password + pepper;
            Rijndael Rij        = Rijndael.Create();

            Rij.KeySize = 256;
            Rij.Padding = PaddingMode.ISO10126;
            Rij.Mode    = CipherMode.CBC;
            Rfc2898DeriveBytes aesKey = new Rfc2898DeriveBytes(passpepper, userID, 65536);

            Rij.Key = aesKey.GetBytes(Rij.KeySize / 8);
            Rij.GenerateIV();
            return(Rij);
        }
Пример #20
0
            public User(string name, string keyApi)
            {
                Name   = name;
                KeyApi = keyApi;

                //Encryption initialization

                encryptorParams = Rijndael.Create();
                encryptorParams.GenerateIV();
                encryptorParams.KeySize = 256;
                encryptorParams.Padding = PaddingMode.Zeros;
            }
 void EncryptWithNewKey(ref Packet input)
 {
     using (var output = new MemoryStream()) {
         Rij.GenerateIV();
         Rij.Key = NewKey;
         DataUtility.WriteOnlyBytesToStream(Rij.IV, output);
         DataUtility.WriteOnlyBytesToStream(Rij.CreateEncryptor().TransformFinalBlock
                                                (input.RawContent, 0, input.RawContent.Length), output);
         Rij.Key          = CurrentKey;
         input.RawContent = output.ToArray();
     }
 }
Пример #22
0
        public void GenerateKeys(int keySize)
        {
            rijndael           = Rijndael.Create();
            rijndael.BlockSize = 128;
            rijndael.KeySize   = keySize;
            rijndael.GenerateIV();
            rijndael.GenerateKey();

            this.blockSize = rijndael.BlockSize;
            this.keySize   = rijndael.KeySize;
            this.key       = rijndael.Key;
            this.iv        = rijndael.IV;
        }
Пример #23
0
 static void Main()
 {
     try
     {
         // Create a new Rijndael object to generate a key
         // and initialization vector (IV).
         Rijndael RijndaelAlg = Rijndael.Create();
         System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
         string privateKey = "qwertyuiopasdfghjklzxcvbnmqwerty";
         RijndaelAlg.Key = encoding.GetBytes(privateKey);
         bool cryptFileExists = File.Exists(CryptFile);
         bool ivFileExists    = File.Exists(IVFile);
         if (cryptFileExists && ivFileExists)
         {
             Console.WriteLine("Enter Text to Encrypt, or a Blank Line to Decrypt Previous:");
         }
         else
         {
             Console.WriteLine("Enter Text to Encrypt:");
         }
         // Create a string to encrypt.
         string sData = Console.ReadLine();
         if (!String.IsNullOrEmpty(sData))
         {
             // Initialize the IV explicitly to something random
             RijndaelAlg.GenerateIV();
             // Encrypt text to a file using the file name, key, and IV.
             EncryptTextToFile(sData, CryptFile, RijndaelAlg);
             // Save the IV for use when decrypting
             File.WriteAllBytes(IVFile, RijndaelAlg.IV);
         }
         else if (!cryptFileExists || !ivFileExists)
         {
             throw new InvalidOperationException("Previous Encrypted Data Not Found");
         }
         else
         {
             // Read the IV that was used for encrypting the file
             RijndaelAlg.IV = File.ReadAllBytes(IVFile);
         }
         // Decrypt the text from a file using the file name, key, and IV.
         string Final = DecryptTextFromFile(CryptFile, RijndaelAlg);
         // Display the decrypted string to the console.
         Console.WriteLine(Final);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
     Console.ReadLine();
 }
Пример #24
0
        private byte[] EncryptBytes(byte[] message)
        {
            if ((message == null) || (message.Length == 0))
            {
                return(message);
            }
            Rij.GenerateIV();

            using (MemoryStream outStream = new MemoryStream()) {
                DataUtility.WriteBytesToStream(Rij.IV, outStream);
                DataUtility.WriteBytesToStream(Rij.CreateEncryptor().TransformFinalBlock(message, 0, message.Length), outStream);
                return(outStream.ToArray());
            }
        }
Пример #25
0
        //drawback of this method is that you have to save the key and iv somwhere because you 'll need them for the decrypt
        public static SymmetricKeys GenerateSymmetricKeys()
        {
            Rijndael myAlg = Rijndael.Create();

            myAlg.GenerateKey(); myAlg.GenerateIV();

            SymmetricKeys keys = new SymmetricKeys()
            {
                Key = myAlg.Key,
                Iv  = myAlg.IV
            };

            return(keys);
        }
Пример #26
0
        // Generate random AES key and IV
        public static string[] GenerateAESKeyAndIV(int length)
        {
            using (Rijndael myAes = Rijndael.Create())
            {
                myAes.KeySize = length;

                myAes.GenerateKey();
                myAes.GenerateIV();

                string[] keyAndIV = new string[2];
                keyAndIV[0] = Convert.ToBase64String(myAes.Key);
                keyAndIV[1] = Convert.ToBase64String(myAes.IV);

                return(keyAndIV);
            }
        }
Пример #27
0
        /// <summary>
        /// 获得初始向量IV数组
        /// </summary>
        /// <returns>初试向量IV数组</returns>
        private byte[] GetLegalIV()
        {
            string result = iv;

            mCrypto.GenerateIV();
            byte[] ivBytes  = mCrypto.IV;
            int    ivLength = ivBytes.Length;

            if (result.Length > ivLength)
            {
                result = result.Substring(0, ivLength);
            }
            else if (result.Length < ivLength)
            {
                result = result.PadRight(ivLength, ' ');
            }
            return(ASCIIEncoding.ASCII.GetBytes(result));
        }
Пример #28
0
        public string encrypt(string content)
        {
            // Encrypt token content
            Rijndael myRijndael = Rijndael.Create();

            myRijndael.GenerateIV();
            byte[] key   = Convert.FromBase64String(this.appKey);
            string iv    = Convert.ToBase64String(myRijndael.IV);
            string value = Convert.ToBase64String(EncryptStringToBytes(content, key, myRijndael.IV));

            // Caculate mac with SHA256 Hash
            Byte[] hashBytes = new HMACSHA256(key).ComputeHash(Encoding.UTF8.GetBytes(iv + value));
            string mac       = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();

            Credential credential = new Credential(iv, value, mac);

            // Build token with Json
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(credential))));
        }
Пример #29
0
            // This encrypts the passed data
            internal void SetData(string data)
            {
                if (data != null)
                {
                    if (rijndael == null)
                    {
                        rijndael = Rijndael.Create();
                        rijndael.GenerateKey();                                         // Not sure if this is necessary. Is
                        rijndael.GenerateIV();                                          // this done by default in the ctor?
                    }

                    ICryptoTransform encryptor = rijndael.CreateEncryptor();
                    encryptedData = encryptor.TransformFinalBlock(ToBytes(data), 0, (data.Length) * 2);
                }
                else
                {
                    encryptedData = null;
                }
            }
Пример #30
0
        /// <summary>
        /// Método de la clase SecurityProtocol. Utilizado para la encryptación de datos.
        /// </summary>
        /// <param name="toEncrypt">Array de bytes a ser encryptado.</param>
        /// <param name="key">Llave para la emcriptación.</param>
        /// <returns>Retorna un byte[] con los datos encryptados.</returns>
        public static byte[] Encrypt(byte[] toEncrypt, byte[] key)
        {
            Rijndael miRijndael = Rijndael.Create();
            byte[] encrypted = null;
            byte[] returnValue = null;

            try
            {
                miRijndael.Key = key;
                miRijndael.GenerateIV();
                encrypted = (miRijndael.CreateEncryptor()).TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);
                returnValue = new byte[miRijndael.IV.Length + encrypted.Length];
                miRijndael.IV.CopyTo(returnValue, 0);
                encrypted.CopyTo(returnValue, miRijndael.IV.Length);
            }
            catch (Exception ex) { throw ex; }
            finally { miRijndael.Clear(); }

            return returnValue;
        }
Пример #31
0
        static string Encrypt(string stringToEncrypt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce aliquam magna ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
        {
            string retValue = "";

            Rijndael rij = Rijndael.Create();

            rij.GenerateKey();
            rij.GenerateIV();

            ICryptoTransform transformer = rij.CreateEncryptor();
            MemoryStream     ms          = new MemoryStream();
            CryptoStream     cs          = new CryptoStream(ms, transformer, CryptoStreamMode.Write);
            StreamWriter     sw          = new StreamWriter(cs);

            sw.Write(stringToEncrypt);

            retValue = Encoding.UTF8.GetString(ms.ToArray());

            return(retValue);
        }