Ejemplo n.º 1
0
        public static MemoryStream Encrypt(Byte[] key, Stream plaintextMessage, Byte[] iv)
        {
            MemoryStream ms = new MemoryStream();

            using (Aes aes = new AesCryptoServiceProvider())
            {
                var is1024 = aes.ValidKeySize(512);
                aes.Key     = key;
                iv          = aes.IV;
                aes.Padding = PaddingMode.PKCS7;

                using (MemoryStream ciphertext = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        plaintextMessage.CopyTo(cs);
                        // cs.Write(plaintextMessage, 0, plaintextMessage.Length);
                        cs.Close();
                        //ciphertext.CopyTo(ms);
                        var buf = ciphertext.ToArray();
                        ms.Write(buf, 0, buf.Length);
                    }
                }
            }

            return(ms);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// AES Decrypt
        /// </summary>
        /// <param name="encryptString">encrypted string</param>
        /// <param name="encryptKey">encription key</param>
        /// <returns>decrypted message</returns>
        public static string Decrypt(string encryptString, string encryptKey)
        {
            try
            {
                using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
                {
                    if (!aesAlg.ValidKeySize(Encoding.Default.GetByteCount(encryptKey) * 8))
                    {
                        throw new ArgumentOutOfRangeException("encryptKey", "key bit length invalid:128~256");
                    }

                    aesAlg.Key = Encoding.Default.GetBytes(encryptKey);
                    aesAlg.IV  = Encoding.Default.GetBytes(encryptKey);
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor();
                    using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptString)))
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                                return(srDecrypt.ReadToEnd());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// AES Encrypt
        /// </summary>
        /// <param name="message">message to encrypt</param>
        /// <param name="encryptKey">encription key min length:16</param>
        /// <returns>encrypted string</returns>
        public static string Encrypt(string message, string encryptKey)
        {
            try
            {
                using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
                {
                    if (!aesAlg.ValidKeySize(Encoding.Default.GetByteCount(encryptKey) * 8))
                    {
                        throw new ArgumentOutOfRangeException("encryptKey", "key bit length invalid:128~256");
                    }

                    aesAlg.Key = Encoding.Default.GetBytes(encryptKey);
                    aesAlg.IV  = Encoding.Default.GetBytes(encryptKey);
                    ICryptoTransform encryptor = aesAlg.CreateEncryptor();
                    using (MemoryStream msEncrypt = new MemoryStream())
                        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                            {
                                swEncrypt.Write(message);
                            }
                            return(Convert.ToBase64String(msEncrypt.ToArray()));
                        }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Creates a new Encryption instance with a random Initialization Vector and 256-bit Key
 /// </summary>
 public Encryption()
 {
     using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
     {
         if (aes.KeySize != 256 && aes.ValidKeySize(256))
         {
             aes.KeySize = 256;
         }
         Key = aes.Key;
         IV  = aes.IV;
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="company_id">公司統編</param>
        /// <param name="encode_string">要解密的字串</param>
        /// <returns></returns>
        public static string Decode(string company_id, string encode_string)
        {
            string encryptKey = company_id;

            var aes = new AesCryptoServiceProvider();
            var key = Encoding.UTF8.GetBytes(encryptKey);

            if (!aes.ValidKeySize(key.Length * 8))
            {
                SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
                key = sha256.ComputeHash(Encoding.UTF8.GetBytes(encryptKey));
            }

            var md5Service = new MD5CryptoServiceProvider();
            var iv         = md5Service.ComputeHash(Encoding.UTF8.GetBytes(encryptKey));

            return(Encoding.UTF8.GetString(AesDecrypt(Convert.FromBase64String(encode_string), key, iv, CipherMode.CBC)));
        }
Ejemplo n.º 6
0
        public static byte[] Encrypt(Byte[] key, byte[] plaintextBytes, Byte[] iv)
        {
            byte[] encryptedMessage;
            using (Aes aes = new AesCryptoServiceProvider())
            {
                var is1024 = aes.ValidKeySize(512);
                aes.Key     = key;
                iv          = aes.IV;
                aes.Padding = PaddingMode.PKCS7;

                using (MemoryStream ciphertext = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintextBytes, 0, plaintextBytes.Length);
                        cs.Close();
                        encryptedMessage = ciphertext.ToArray();
                    }
                }
            }
            return(encryptedMessage);
        }
Ejemplo n.º 7
0
        // Encrypt the data in the input stream into the output stream.
        public static void CryptStream(string password, Stream in_stream, Stream out_stream, bool encrypt)
        {
            // Make an AES service provider.
            AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();

            // Find a valid key size for this provider.
            int key_size_bits = 0;

            for (int i = 1024; i > 1; i--)
            {
                if (aes_provider.ValidKeySize(i))
                {
                    key_size_bits = i;
                    break;
                }
            }
            Debug.Assert(key_size_bits > 0);
            Console.WriteLine("Key size: " + key_size_bits);

            // Get the block size for this provider.
            int block_size_bits = aes_provider.BlockSize;

            // Generate the key and initialization vector.
            byte[] key  = null;
            byte[] iv   = null;
            byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
            MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);

            // Make the encryptor or decryptor.
            ICryptoTransform crypto_transform;

            if (encrypt)
            {
                crypto_transform = aes_provider.CreateEncryptor(key, iv);
            }
            else
            {
                crypto_transform = aes_provider.CreateDecryptor(key, iv);
            }

            // Attach a crypto stream to the output stream.
            // Closing crypto_stream sometimes throws an
            // exception if the decryption didn't work
            // (e.g. if we use the wrong password).
            try
            {
                using (CryptoStream crypto_stream = new CryptoStream(out_stream, crypto_transform, CryptoStreamMode.Write))
                {
                    // Encrypt or decrypt the file.
                    const int block_size = 1024;
                    byte[]    buffer     = new byte[block_size];
                    int       bytes_read;
                    while (true)
                    {
                        // Read some bytes.
                        bytes_read = in_stream.Read(buffer, 0, block_size);
                        if (bytes_read == 0)
                        {
                            break;
                        }

                        // Write the bytes into the CryptoStream.
                        crypto_stream.Write(buffer, 0, bytes_read);
                    }
                } // using crypto_stream
            }
            catch
            {
            }

            crypto_transform.Dispose();
        }
Ejemplo n.º 8
0
        // Note that extension methods must be defined in a non-generic static class.

        // Encrypt or decrypt the data in in_bytes[] and return the result.
        public static byte[] CryptBytes(string password, byte[] in_bytes, bool encrypt)
        {
            // Make an AES service provider.
            AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();

            // Find a valid key size for this provider.
            int key_size_bits = 0;

            for (int i = 1024; i > 1; i--)
            {
                if (aes_provider.ValidKeySize(i))
                {
                    key_size_bits = i;
                    break;
                }
            }
            Debug.Assert(key_size_bits > 0);
            Console.WriteLine("Key size: " + key_size_bits);

            // Get the block size for this provider.
            int block_size_bits = aes_provider.BlockSize;

            // Generate the key and initialization vector.
            byte[] key  = null;
            byte[] iv   = null;
            byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
            MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);

            // Make the encryptor or decryptor.
            ICryptoTransform crypto_transform;

            if (encrypt)
            {
                crypto_transform = aes_provider.CreateEncryptor(key, iv);
            }
            else
            {
                crypto_transform = aes_provider.CreateDecryptor(key, iv);
            }

            // Create the output stream.
            using (MemoryStream out_stream = new MemoryStream())
            {
                // Attach a crypto stream to the output stream.
                using (CryptoStream crypto_stream = new CryptoStream(out_stream,
                                                                     crypto_transform, CryptoStreamMode.Write))
                {
                    // Write the bytes into the CryptoStream.
                    crypto_stream.Write(in_bytes, 0, in_bytes.Length);
                    try
                    {
                        crypto_stream.FlushFinalBlock();
                    }
                    catch (CryptographicException)
                    {
                        // Ignore this exception. The password is bad.
                    }
                    catch
                    {
                        // Re-throw this exception.
                        throw;
                    }

                    // return the result.
                    return(out_stream.ToArray());
                }
            }
        }