Esempio n. 1
0
        private void ContinueStartup(string token, byte[] akey, byte[] aiv, string pth)
        {
            var utf8 = new UTF8Encoding(false);

            using (var aes = RijndaelManaged.Create())
                using (var aes_enc = aes.CreateEncryptor(akey, aiv))
                    using (var fs = File.Create(pth))
                        using (var bw = new BinaryWriter(fs))
                            using (var cs = new CryptoStream(fs, aes_enc, CryptoStreamMode.Write))
                            {
                                var tkb = utf8.GetBytes(token);
                                bw.Write(aiv);
                                cs.Write(tkb, 0, tkb.Length);
                                cs.FlushFinalBlock();
                            }

            this.Bot             = new DspXamarinBot(token);
            this.Bot.LogMessage += this.Bot_LogMessage;

            this.LogItems.Clear();
            this.RunOnUiThread(() => this.LogItemsAdapter.NotifyDataSetChanged());

            this.BotTaskCancellationTokenSource = new CancellationTokenSource();
            this.BotTask = Task.Run(this.RunBot, this.BotTaskCancellationToken);
        }
Esempio n. 2
0
        public string Decrypt(string data)
        {
            var buffer = Convert.FromBase64String(data);
            var aes    = RijndaelManaged.Create();

            aes.BlockSize = 256;
            aes.KeySize   = 256;
            aes.Padding   = PaddingMode.Zeros;
            aes.Mode      = CipherMode.CBC;
            using (var ms = new MemoryStream(buffer))
            {
                using (var encoder = new CryptoStream(ms, aes.CreateDecryptor(Key.Clone() as byte[], InitialVector.Clone() as byte[]), CryptoStreamMode.Read))
                {
                    using (var raw = new MemoryStream())
                    {
                        var readLen = 0;
                        var readBuf = new byte[102400];

                        while ((readLen = encoder.Read(readBuf, 0, 102400)) != 0)
                        {
                            raw.Write(readBuf, 0, readLen);
                        }
                        var decBuffer = raw.ToArray();
                        return(Encoding.UTF8.GetString(decBuffer).Trim('\0'));
                    }
                }
            }
        }
        public static string Decrypt(byte[] data)
        {
            if (data == null || data.Length < 1)
            {
                return(null);
            }

            var secretIV  = HttpContext.Current.Application[SECRET_IV] as byte[];
            var secretKey = HttpContext.Current.Application[SECRET_KEY] as byte[];

            if (secretIV == null || secretKey == null)
            {
                return(null);
            }

            using (var cryptography = RijndaelManaged.Create())
            {
                cryptography.IV  = secretIV;
                cryptography.Key = secretKey;

                using (var decryptor = cryptography.CreateDecryptor())
                {
                    using (var ms = new System.IO.MemoryStream(data))
                    {
                        using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                        {
                            using (var reader = new System.IO.StreamReader(cs, System.Text.Encoding.UTF8))
                            {
                                return(reader.ReadToEnd());
                            }
                        }
                    }
                }
            }
        }
Esempio n. 4
0
        public void DecryptStream(Stream sourcestream, Stream deststream, string key)
        {
            byte[] _key = new byte[32];
            byte[] _IV  = new byte[16];

            byte[] myKey = Encoding.ASCII.GetBytes(key);

            for (int i = 0; i < _key.Length; i++)
            {
                _key[i] = 0;
            }
            for (int i = 0; (i < _key.Length) && (i < myKey.Length); i++)
            {
                _key[i] = myKey[i];
            }
            for (int i = 0; (i < _key.Length) && (i < _IV.Length); i++)
            {
                _IV[i] = _key[i];
            }
            _IV.Reverse();

            Rijndael rijndael = RijndaelManaged.Create();

            rijndael.IV  = _IV;
            rijndael.Key = _key;

            var decStream = new CryptoStream(sourcestream, rijndael.CreateDecryptor(), CryptoStreamMode.Read);

            deststream.SetLength(0);
            decStream.CopyTo(deststream);
        }
Esempio n. 5
0
        /// <summary>
        /// Decrypts a byte array that has been encrypted by ProtectBuffer
        /// </summary>
        /// <param name="encrpyted">Value that has been encrypted with ProtectBuffer</param>
        /// <returns>A decrypted string value</returns>
        /// 1. Decrypt the 256 byte prefix to get Key and IV
        /// 2. Decrypt remainder using Key and IV
        public string UnprotectBuffer(byte[] encrpyted)
        {
            if (encrpyted == null)
            {
                return(null);
            }
            else if (encrpyted.Length < 256)
            {
                throw new ArgumentException("encrypted");
            }

            // extract the first 256 bytes and decrypt
            var clearpw = DecryptAsymmetrical(encrpyted.Take(256).ToArray());
            var key     = clearpw.Take(32);          // Rijndael key is 32 bytes
            var iv      = clearpw.Skip(32).Take(16); // Rijndael iv is 16 bytes

            // now extract the remainder
            using (Rijndael rj = RijndaelManaged.Create())
                using (MemoryStream ms = new MemoryStream(encrpyted.Skip(256).ToArray()))
                    // decrypt using symmeterical (key and initial vector from encrypted value)
                    using (CryptoStream cs = new CryptoStream(ms, rj.CreateDecryptor(key.ToArray(), iv.ToArray()), CryptoStreamMode.Read))
                    {
                        byte[] decrypted = new byte[encrpyted.Length - 256];
                        cs.Read(decrypted, 0, decrypted.Length);
                        return(Encoding.UTF8.GetString(decrypted).TrimEnd('\0'));
                    }
        }
Esempio n. 6
0
        public AES()
        {
            CNG c = new CNG();

            c.Key = Key = RijndaelManaged.Create().Key;
            Cng   = c;
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1892);

            listener.Start();
            TcpClient     client = listener.AcceptTcpClient();
            NetworkStream ns     = client.GetStream();

            Rijndael aes = RijndaelManaged.Create();

            byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            byte[] iv  = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            aes.Key = key;
            aes.IV  = iv;

            byte[] message = Program.ReadMessage(ns, aes);
            String output  = System.Text.Encoding.UTF8.GetString(message);

            Console.WriteLine(output);

            Console.Read();

            ns.Close();
            client.Close();
            listener.Stop();
        }
Esempio n. 8
0
        private static string DecryptString(string decString, string password)
        {
            MemoryStream ms = new MemoryStream();

            byte[] clearBytes = Convert.FromBase64String(decString);

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password,
                                                              new byte[] { 0x49, 0x76, 0x61, 0x6e,
                                                                           0x20, 0x4d, 0x65, 0x64, 0x76,
                                                                           0x65, 0x64, 0x65, 0x76 });

            byte[] Key = pdb.GetBytes(32);
            byte[] IV  = pdb.GetBytes(16);

            Rijndael encryptor = RijndaelManaged.Create();

            encryptor.Key     = Key;
            encryptor.IV      = IV;
            encryptor.Padding = PaddingMode.PKCS7;

            CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(clearBytes, 0, clearBytes.Length);
            cs.Close();
            byte[] decryptedData = ms.ToArray();
            decString = System.Text.Encoding.Unicode.GetString(decryptedData);
            return(decString);
        }
Esempio n. 9
0
        private byte[] DecryptKey(byte[] contentBytes, string passphrase)
        {
            byte[] importKey = null;

            if (passwordProtected)
            {
                byte[] passHash = CheckPassword(contentBytes, passphrase);

                byte[] encryptedKey = new byte[contentBytes.Length - FlagLength - PassHashLength];
                Buffer.BlockCopy(contentBytes, FlagLength + PassHashLength, encryptedKey, 0, encryptedKey.Length);

                using (SymmetricAlgorithm algorithm = RijndaelManaged.Create())
                {
                    SymmetricCryptographer crypto = new SymmetricCryptographer(algorithm, passHash);
                    importKey = crypto.Decrypt(encryptedKey);
                }
            }
            else
            {
                importKey = new byte[contentBytes.Length - 1];
                Buffer.BlockCopy(contentBytes, 1, importKey, 0, contentBytes.Length - FlagLength);
            }

            return(importKey);
        }
Esempio n. 10
0
        public void testAES()
        {
            var aes = RijndaelManaged.Create();

            aes.BlockSize = 256;
            aes.KeySize   = 256;
            aes.Padding   = PaddingMode.Zeros;
            aes.Mode      = CipherMode.CBC;

            aes.GenerateIV();
            aes.GenerateKey();

            var iv  = Convert.ToBase64String(aes.IV);
            var key = Convert.ToBase64String(aes.Key);

            var init = $"{key}:{iv}";

            var myaes = new AES();

            myaes.Init(init);

            var rnd = StrHelper.RndString(1100);

            Assert.AreEqual(
                rnd,
                myaes.Decrypt(myaes.Encrypt(rnd))
                );
        }
Esempio n. 11
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
    public void uploadPicture()
    {
        //insert sql query to get users password for string passPhrase from Encrypt method
        SqlConnection con = new SqlConnection(connectionstring);

        con.Open();
        SqlCommand getPassCmd = new SqlCommand("Select Password FROM Users Where UserID = " + Session["UserID"], con);
        string     password   = getPassCmd.Parameters.ToString();

        con.Close();
        string fileName;

        if (picFile.HasFile)
        {
            fileName = picFile.PostedFile.FileName;
            using (Rijndael encryption = RijndaelManaged.Create())
            {
                byte[] image         = ImageToBytes(fileName);
                byte[] encyptedImage = Encrypt(image, password);
                con.Open();
                SqlCommand cmd = new SqlCommand("Insert Into Images values (@Images, @UserID)", con);
                cmd.Parameters.AddWithValue("@Images", encyptedImage);
                cmd.Parameters.AddWithValue("@UserID", Session["UserID"]);
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

        else
        {
            result.Visible = true;
            result.Text    = "Please upload an image!";
        }
    }
Esempio n. 13
0
 /// <summary>
 /// Generates a random 256 bit key to be used for encrypting
 /// Customer data.
 /// </summary>
 /// <returns>The base64 encoded key</returns>
 private static string GenerateKey()
 {
     using (var alg = RijndaelManaged.Create())
     {
         return(Convert.ToBase64String(alg.Key));
     }
 }
Esempio n. 14
0
        private byte[] GenerateKeyToBeArchived()
        {
            RijndaelManaged symmetricAlgorithm = (RijndaelManaged)RijndaelManaged.Create();

            symmetricAlgorithm.GenerateKey();
            return(symmetricAlgorithm.Key);
        }
Esempio n. 15
0
 private static byte[] GenerateKey()
 {
     using (var e = RijndaelManaged.Create())
     {
         e.GenerateKey();
         return(e.Key);
     }
 }
Esempio n. 16
0
        protected static Rijndael Create()
        {
            var instance = RijndaelManaged.Create();

            instance.Key = _key;
            instance.IV  = _iv;
            return(instance);
        }
        public void CreateSymmetricKey()
        {
            symmetricAlgo = (RijndaelManaged)RijndaelManaged.Create();
            symmetricAlgo.GenerateKey();
            encryptedKey = ProtectedData.Protect(symmetricAlgo.Key, null, DataProtectionScope.CurrentUser);

            stream = new MemoryStream();
        }
Esempio n. 18
0
        public void decrypt_file(object pcp /*string pwd_file_enc, int key_size, string src_enc_file, string dst_dec_file, ProgressBar pr_b*/)
        {
            PackDeCryptParam _vpcp        = (PackDeCryptParam)pcp;
            string           pwd_file_enc = _vpcp.pwd_file_enc;
            int         key_size          = _vpcp.key_size;
            string      src_enc_file      = _vpcp.src_enc_file;
            string      dst_dec_file      = _vpcp.dst_dec_file;
            ProgressBar pr_b = _vpcp.pr_b;

            if (string.IsNullOrEmpty(pwd_file_enc))
            {
                pwd_file_enc = Crypt.default_key;
            }
            SymmetricAlgorithm alg;

            alg = (SymmetricAlgorithm)RijndaelManaged.Create();                    //пример создания класса RijndaelManaged

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd_file_enc, null); //класс, позволяющий генерировать ключи на базе паролей

            pdb.HashName = "SHA512";                                               //будем использовать SHA512
            int keylen = key_size;                                                 //получаем размер ключа из ComboBox’а

            alg.KeySize = keylen;                                                  //устанавливаем размер ключа
            alg.Key     = pdb.GetBytes(keylen >> 3);                               //получаем ключ из пароля
            alg.Mode    = CipherMode.CBC;                                          //используем режим CBC
            alg.IV      = new Byte[alg.BlockSize >> 3];                            //и пустой инициализационный вектор
            ICryptoTransform tr = alg.CreateDecryptor();                           //создаем decryptor

            FileStream instream  = new FileStream(src_enc_file, FileMode.Open, FileAccess.Read, FileShare.Read);
            FileStream outstream = new FileStream(dst_dec_file, FileMode.Create, FileAccess.Write, FileShare.None);
            int        buflen    = ((2 << 16) / alg.BlockSize) * alg.BlockSize;

            byte[] inbuf  = new byte[buflen];
            byte[] outbuf = new byte[buflen];
            int    len;
            long   input_size = instream.Length;
            long   cur_byte   = 0;

            while ((len = instream.Read(inbuf, 0, buflen)) == buflen)
            {
                int enclen = tr.TransformBlock(inbuf, 0, buflen, outbuf, 0); //собственно расшифровываем
                outstream.Write(outbuf, 0, enclen);
                cur_byte += enclen;
                NewMethod2(pr_b, input_size, cur_byte);
                EncryptingFile(cur_byte, input_size);
            }
            instream.Close();
            outbuf = tr.TransformFinalBlock(inbuf, 0, len); //расшифровываем финальный блок
            outstream.Write(outbuf, 0, outbuf.Length);
            pr_b.Value = (int)input_size;
            outstream.Close();
            alg.Clear(); //осуществляем зачистку

            SetDecryptedFile d = new SetDecryptedFile(Action.FormAction.RecievedFile);

            pr_b.Invoke(d, new object[] { src_enc_file });
            DecryptedFile(src_enc_file);
        }
Esempio n. 19
0
        public static string Encrypt(string plainText, string password = "******")
        {
            if (plainText == null)
            {
                throw new ArgumentNullException("plainText");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            // Will return this
            var CryptoJSFormat = new CryptoJSFormat();

            // Generate random 8 byte salt
            Random rnd = new Random();

            byte[] salt = new byte[8];
            rnd.NextBytes(salt);

            CryptoJSFormat.s = Parsers.ByteArrayToHexViaLookup32Unsafe(salt);
            // Convert plain text to bytes
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);

            // create new password derived bytes using password/salt
            using (OpenSslCompatDeriveBytes pdb = new OpenSslCompatDeriveBytes(password, salt))
            {
                using (Rijndael aes = RijndaelManaged.Create())
                {
                    // Generate key and iv from password/salt and pass to aes
                    aes.Key       = pdb.GetBytes(aes.KeySize / 8);
                    aes.IV        = pdb.GetBytes(aes.BlockSize / 8);
                    aes.Mode      = CipherMode.CBC;
                    aes.BlockSize = 128;

                    CryptoJSFormat.iv = Parsers.ByteArrayToHexViaLookup32Unsafe(aes.IV);

                    // Open a new memory stream to write the encrypted data to
                    using (MemoryStream ms = new MemoryStream())
                    {
                        // Create a crypto stream to perform encryption
                        using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            // write encrypted bytes to memory
                            cs.Write(plainBytes, 0, plainBytes.Length);
                        }
                        // get the cipher bytes from memory
                        byte[] cipherBytes = ms.ToArray();

                        // convert cipher array to base 64 string
                        CryptoJSFormat.ct = Convert.ToBase64String(cipherBytes);
                    }
                    aes.Clear();
                }
            }

            return(JsonConvert.SerializeObject(CryptoJSFormat));
        }
Esempio n. 20
0
        public void crypt_file(bool isEncrypting, string key_word, int key_size, string src_file, string dst_file, ProgressBar pr_b)
        {
            if (string.IsNullOrEmpty(key_word))
            {
                key_word = FileCrypt.default_key;
            }
            SymmetricAlgorithm alg;

            alg = (SymmetricAlgorithm)RijndaelManaged.Create();                //пример создания класса RijndaelManaged

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(key_word, null); //класс, позволяющий генерировать ключи на базе паролей

            pdb.HashName = "SHA512";                                           //будем использовать SHA512
            int keylen = key_size;                                             //получаем размер ключа из ComboBox’а

            alg.KeySize = keylen;                                              //устанавливаем размер ключа
            alg.Key     = pdb.GetBytes(keylen >> 3);                           //получаем ключ из пароля
            alg.Mode    = CipherMode.CBC;                                      //используем режим CBC
            alg.IV      = new Byte[alg.BlockSize >> 3];                        //и пустой инициализационный вектор
            ICryptoTransform tr;

            if (isEncrypting)
            {
                tr = alg.CreateEncryptor(); //создаем encryptor
            }
            else
            {
                tr = alg.CreateDecryptor(); //создаем decryptor
            }

            FileStream instream  = new FileStream(src_file, FileMode.Open, FileAccess.Read, FileShare.Read);
            FileStream outstream = new FileStream(dst_file, FileMode.Create, FileAccess.Write, FileShare.None);
            int        buflen    = ((2 << 16) / alg.BlockSize) * alg.BlockSize;

            byte[] inbuf  = new byte[buflen];
            byte[] outbuf = new byte[buflen];
            int    len;
            long   input_size = instream.Length;
            long   c_position = 0;

            pr_b.Maximum = int.MaxValue;

            while ((len = instream.Read(inbuf, 0, buflen)) == buflen)
            {
                int enclen = tr.TransformBlock(inbuf, 0, buflen, outbuf, 0); //собственно шифруем
                outstream.Write(outbuf, 0, enclen);
                c_position += enclen;
                pr_b.Value  = (int)Math.Ceiling((double)int.MaxValue * ((double)c_position / (double)input_size));
                Application.DoEvents();
            }
            instream.Close();
            outbuf = tr.TransformFinalBlock(inbuf, 0, len); //шифруем финальный блок
            outstream.Write(outbuf, 0, outbuf.Length);
            pr_b.Value = int.MaxValue;
            outstream.Close();
            alg.Clear(); //осуществляем зачистку
        }
Esempio n. 21
0
        public static CryptoStream GetEncryptStreamAES(byte[] key, byte[] salt, Stream output)
        {
            var r = RijndaelManaged.Create();
            Rfc2898DeriveBytes pw = new Rfc2898DeriveBytes(key, salt, 5);

            CryptoStream cs = new CryptoStream(output, r.CreateEncryptor(pw.GetBytes(32), pw.GetBytes(16)), CryptoStreamMode.Write);

            return(cs);
        }
Esempio n. 22
0
        public static CryptoStream GetDecryptStreamAES(string key, byte[] salt, Stream input)
        {
            var r = RijndaelManaged.Create();
            Rfc2898DeriveBytes pw = new Rfc2898DeriveBytes(key, salt);

            CryptoStream cs = new CryptoStream(input, r.CreateDecryptor(pw.GetBytes(32), pw.GetBytes(16)), CryptoStreamMode.Read);

            return(cs);
        }
        private void ContinueStartup(string token, byte[] akey, byte[] aiv, string pth)
        {
            var utf8 = new UTF8Encoding(false);

            using (var aes = RijndaelManaged.Create())
                using (var aes_enc = aes.CreateEncryptor(akey, aiv))
                    using (var fs = File.Create(pth))
                        using (var bw = new BinaryWriter(fs))
                            using (var cs = new CryptoStream(fs, aes_enc, CryptoStreamMode.Write))
                            {
                                var tkb = utf8.GetBytes(token);
                                bw.Write(aiv);
                                cs.Write(tkb, 0, tkb.Length);
                                cs.FlushFinalBlock();
                            }

            this.Discord = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect         = true,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Info,
                ShardCount            = 1,
                ShardId               = 0,
                Token                 = token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });

            this.DiscordCommands = this.Discord.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive       = true,
                EnableDefaultHelp   = true,
                EnableDms           = true,
                EnableMentionPrefix = true,
                StringPrefix        = "daddy:",
                SelfBot             = false
            });

            this.Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived;
            this.Discord.ClientErrored  += this.Discord_ClientError;
            this.Discord.GuildAvailable += this.Discord_GuildAvailable;
            this.Discord.Ready          += this.Discord_Ready;

            this.DiscordCommands.CommandExecuted += this.DiscordCommands_CommandExecuted;
            this.DiscordCommands.CommandErrored  += this.DiscordCommands_CommandErrored;

            this.Discord.SetWebSocketClient <WebSocket4NetClient>();
            this.DiscordCommands.RegisterCommands <PortableCommands>();

            this.LogItems.Clear();
            this.RunOnUiThread(() => this.LogItemsAdapter.NotifyDataSetChanged());

            this.BotTaskCancellationTokenSource = new CancellationTokenSource();
            this.BotTask = Task.Run(this.RunBot, this.BotTaskCancellationToken);
        }
Esempio n. 24
0
        private static MemoryStream CreateSymmetricKey()
        {
            MemoryStream stream = new MemoryStream();

            RijndaelManaged algo = (RijndaelManaged)RijndaelManaged.Create();

            algo.GenerateKey();
            KeyManager.Write(stream, ProtectedKey.CreateFromPlaintextKey(algo.Key, DataProtectionScope.CurrentUser));
            stream.Seek(0, SeekOrigin.Begin);

            return(stream);
        }
        static void Main(string[] args)
        {
            //perform symmetric encryption using RijndaelManaged algorithm
            SymmetricAlgorithm algoProvider = RijndaelManaged.Create();

            Console.WriteLine("Crypto Provider Information");
            Console.WriteLine("--------------------");
            Console.WriteLine("Cipher Mode : " + algoProvider.Mode);
            Console.WriteLine("Padding Mode : " + algoProvider.Padding);
            Console.WriteLine("Block Size : " + algoProvider.BlockSize);
            Console.WriteLine("Key Size : " + algoProvider.KeySize);

            Console.WriteLine("Contract Note Encryption Stage - Broker end");
            Console.WriteLine("-------------------------------------------");
            //Generate Symmetric Key
            algoProvider.GenerateKey();
            //Generate IV
            algoProvider.GenerateIV();

            //create file which stores encrypted content of contract note
            FileStream fileStream = new FileStream(@"C:\ContractNote.enc", FileMode.Create);
            //create symmetric encryptor object
            ICryptoTransform cryptoTransform = algoProvider.CreateEncryptor();
            //create crypto stream
            CryptoStream cryptoStream = new CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Write);
            string       contractNote = "<CONTRACTNOTE>"
                                        + "<SYMBOL>MSFT</SYMBOL>"
                                        + "<QUANTITY>100</QUANTITY>"
                                        + "<PRICE>24</PRICE>"
                                        + "</CONTRACTNOTE>";

            byte[] contentBuffer = Encoding.ASCII.GetBytes(contractNote);
            //write encrypted data
            cryptoStream.Write(contentBuffer, 0, contentBuffer.Length);
            cryptoStream.Close();
            fileStream.Close();

            Console.WriteLine("Contract Note Decryption Stage - Fund Manager end");
            Console.WriteLine("-------------------------------------------------");
            //open encrypted content of contract note
            fileStream = new FileStream(@"C:\ContractNote.enc", FileMode.Open);
            //create symmetric decryptor object
            cryptoTransform = algoProvider.CreateDecryptor();
            cryptoStream    = new CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Read);
            byte[] readBuffer = new byte[fileStream.Length];
            //decrypt data
            cryptoStream.Read(readBuffer, 0, readBuffer.Length);
            string decryptedText = Encoding.ASCII.GetString(readBuffer, 0, readBuffer.Length);

            Console.WriteLine(decryptedText);
        }
Esempio n. 26
0
 public byte[] Encrypt(byte[] data)
 {
     using (var crypto = RijndaelManaged.Create())
     {
         crypto.Mode      = CipherMode.CBC;
         crypto.BlockSize = 256;
         crypto.KeySize   = 256;
         crypto.Padding   = PaddingMode.ISO10126;
         using (var encryptor = crypto.CreateEncryptor(_key, _iv))
         {
             return(encryptor.TransformFinalBlock(data, 0, data.Length));
         }
     }
 }
Esempio n. 27
0
        private string EncryptKey(byte[] key, string passphrase)
        {
            byte[] output          = null;
            byte[] passphraseBytes = GetPassphraseBytes(passphrase);

            using (SymmetricAlgorithm algorithm = RijndaelManaged.Create())
            {
                SymmetricCryptographer crypto = new SymmetricCryptographer(algorithm, passphraseBytes);
                byte[] encryptedKey           = crypto.Encrypt(key);
                output = AppendPasswordHash(encryptedKey, passphraseBytes, PasswordProtectedFlag);
            }

            return(Convert.ToBase64String(output));
        }
Esempio n. 28
0
        public void AddChannel(byte[] cryptoKey, SymmetricAlgorithm algorithm = null, string channelName = null)
        {
            algorithm = algorithm ?? RijndaelManaged.Create();
            var channel = new EncryptionChannel(channelName, cryptoKey, algorithm);

            if (channelName == null)
            {
                _defaultChannel = channel;
            }
            else
            {
                _channels[channelName] = channel;
            }
        }
Esempio n. 29
0
 public byte[] Decrypt(byte[] encrypted)
 {
     using (var crypto = RijndaelManaged.Create())
     {
         crypto.Mode      = CipherMode.CBC;
         crypto.BlockSize = 128;
         crypto.KeySize   = 256;
         crypto.Padding   = PaddingMode.ISO10126;
         using (var dencryptor = crypto.CreateDecryptor(_key, _iv))
         {
             return(dencryptor.TransformFinalBlock(encrypted, 0, encrypted.Length));
         }
     }
 }
Esempio n. 30
0
        public static string GenerateKey()
        {
            var aes = RijndaelManaged.Create();

            aes.BlockSize = 256;
            aes.KeySize   = 256;
            aes.Padding   = PaddingMode.Zeros;
            aes.Mode      = CipherMode.CBC;
            aes.GenerateKey();
            aes.GenerateIV();
            var key = Convert.ToBase64String(aes.Key);
            var iv  = Convert.ToBase64String(aes.IV);

            return(key + ":" + iv);
        }