示例#1
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="key"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static String Decrypt(String key, Byte[] bytes)
        {
            var aes = AesManaged.Create();

            //aes.IV=IV;
            aes.BlockSize = 128;
            aes.KeySize   = 128;
            aes.Key       = Encoding.UTF8.GetBytes(key.MD5().Substring(16));
            aes.Mode      = CipherMode.ECB;
            aes.Padding   = PaddingMode.Zeros;
            ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);

            aes.Dispose();
            Byte[] result;
            try {
                result = crypto.TransformFinalBlock(bytes, 0, bytes.Length);
            }catch (Exception exception) {
                Program.LoggerModule.Log("Helpers.AesEncrypt.Decrypt[Error]", $"数据解密异常,{exception.Message},{exception.StackTrace}");
                ConsoleColor cc = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Helpers.AesEncrypt.Decrypt => {exception.Message} | {exception.StackTrace}");
                Console.ForegroundColor = cc;
                return(null);
            } finally {
                crypto.Dispose();
                //aes.Dispose();
            }
            return(Encoding.UTF8.GetString(result));
        }
示例#2
0
        public static string Decrypt(string src, string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = _key;
            }
            else
            {
                if (key.Length > 32)
                {
                    key = key.Substring(0, 32);
                }
                else if (key.Length < 32)
                {
                    key = key.PadLeft(32, ' ');
                }
            }
            var byteskey = Encoding.UTF8.GetBytes(key);
            var bytessrc = Convert.FromBase64String(src);

            Aes aes = AesManaged.Create();

            aes.Key     = byteskey;
            aes.Mode    = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;

            var ct  = aes.CreateDecryptor();
            var res = ct.TransformFinalBlock(bytessrc, 0, bytessrc.Length);

            return(Encoding.UTF8.GetString(res));
        }
 /// <summary>
 /// Generates a key to use for encryption.
 /// </summary>
 /// <returns>The base64-encoded cryptokey.</returns>
 public static string GenerateKey()
 {
     using (var aes = AesManaged.Create())
     {
         return(Convert.ToBase64String(aes.Key));
     }
 }
示例#4
0
        public byte[] Decrypt(byte[] buffer)
        {
#if WINDOWS_STORE
            SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey aes    = provider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(this.key));
            IBuffer          result = CryptographicEngine.Decrypt(aes, CryptographicBuffer.CreateFromByteArray(buffer), CryptographicBuffer.CreateFromByteArray(this.iv));

            byte[] decrypted;
            CryptographicBuffer.CopyToByteArray(result, out decrypted);

            return(decrypted);
#else
            using (System.Security.Cryptography.Aes aes = AesManaged.Create())
            {
                aes.KeySize = 256;
                aes.Mode    = CipherMode.CBC;

                aes.IV  = iv;
                aes.Key = key;
                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                {
                    return(decryptor.TransformFinalBlock(buffer, 0, buffer.Length));
                }
            }
#endif
        }
示例#5
0
        public async Task <object> Process(JsonDocument request, ILambdaContext context)
        {
            var s3 = new AmazonS3Client();

            // easier than doing math on the timestamps in logs
            var timer = new Stopwatch();

            timer.Start();

            context.Logger.LogLine($"{timer.Elapsed}: Getting started.");
            using var stream = (await s3.GetObjectAsync(BUCKET, AES_DATA)).ResponseStream;

            // setup a decryptor
            using var aes = AesManaged.Create();
            aes.IV        = Convert.FromBase64String("EqYoED0ag4vlPnFkWZMCog==");
            aes.Key       = Convert.FromBase64String("Sgf9NocncDHSBqMXrMthXbToAQmthMpC6eJ6Hw51Ghg=");

            using var idecrypt = aes.CreateDecryptor();
            using var cstream  = new CryptoStream(stream, idecrypt, CryptoStreamMode.Read);
            using (var output = new S3UploadStream(s3, BUCKET, OUTPUT_KEY)) {
                await cstream.CopyToAsync(output);
            }
            context.Logger.LogLine($"{timer.Elapsed}: Done copying.");
            timer.Stop();

            return(new {
                AesFile = $"s3://{BUCKET}/{AES_DATA}",
                CsvFile = $"s3://{BUCKET}/{OUTPUT_KEY}",
                Status = "ok"
            });
        }
示例#6
0
        public static Boolean Decrypt(String _key, Byte[] _bytes, out String _data)
        {
            var aes = AesManaged.Create();

            //aes.IV=IV;
            aes.BlockSize = 128;
            aes.KeySize   = 128;
            aes.Key       = Encoding.UTF8.GetBytes(_key.MD5().Substring(16));
            aes.Mode      = CipherMode.ECB;
            aes.Padding   = PaddingMode.Zeros;
            ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);

            Byte[] result = null;
            try {
                result = crypto.TransformFinalBlock(_bytes, 0, _bytes.Length);
            }catch (Exception exception) {
                crypto.Dispose();
                aes.Dispose();
                _data = null;
                return(false);
            }
            crypto.Dispose();
            aes.Dispose();
            _data = Encoding.UTF8.GetString(result);
            return(true);
        }
示例#7
0
文件: Program.cs 项目: zilo312/aa
        private static string DecryptString(string encryptedText, string password)
        {
            byte[] rawData = Convert.FromBase64String(encryptedText);
            Aes    aes     = AesManaged.Create();

            // setup the decryption algorithm
            int nBytes = aes.BlockSize >> 3;

            byte[] salt = new byte[nBytes];
            for (int i = 0; i < salt.Length; i++)
            {
                salt[i] = rawData[i];
            }

            Rfc2898DeriveBytes generateKeys = new Rfc2898DeriveBytes("password", salt);

            aes.Key = generateKeys.GetBytes(aes.BlockSize >> 3);
            aes.IV  = salt;

            using (MemoryStream stream = new MemoryStream())
                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                {
                    CryptoStream cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Write);

                    cryptoStream.Write(rawData, nBytes, rawData.Length - nBytes);
                    cryptoStream.Close();

                    byte[] decryptedData = stream.ToArray();

                    return(Encoding.UTF8.GetString(decryptedData));
                }
        }
示例#8
0
        public override void init(int mode, byte[] key, byte[] iv)
        {
            if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE)
            {
                throw new ArgumentOutOfRangeException();
            }
            ms             = new PipedMemoryStream();
            aesm           = AesManaged.Create();
            aesm.BlockSize = blockSize * 8;
            aesm.Padding   = PaddingMode.None;
            ICryptoTransform ict;

            if (key.Length > blockSize)
            {
                byte[] tmp = new byte[blockSize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }
            if (iv.Length > ivSize)
            {
                byte[] tmp = new byte[ivSize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (mode == ENCRYPT_MODE)
            {
                ict = aesm.CreateEncryptor(key, iv);
            }
            else
            {
                ict = aesm.CreateDecryptor(key, iv);
            }

            cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
        }
        public string Decrypt(string encryptedValue)
        {
            var value = string.Empty;

            using (var aes = AesManaged.Create())
            {
                aes.KeySize   = 256;
                aes.BlockSize = 128;
                var saltBytes   = Encoding.UTF8.GetBytes(_encryptionContext.Salt);
                var password    = new Rfc2898DeriveBytes(_encryptionContext.Key, saltBytes);
                var vectorBytes = password.GetBytes(aes.BlockSize / 8);
                using (var decryptor = aes.CreateDecryptor(password.GetBytes(aes.KeySize / 8), vectorBytes))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        var lockObject = new Object();

                        lock (lockObject)
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write))
                            {
                                var encryptedValueBytes = Convert.FromBase64String(encryptedValue);
                                cryptoStream.Write(encryptedValueBytes, 0, encryptedValueBytes.Length);
                                cryptoStream.FlushFinalBlock();

                                var valueBytes = memoryStream.ToArray();
                                value = Encoding.UTF8.GetString(valueBytes);
                            }
                        }
                    }
                }
            }

            return(value);
        }
示例#10
0
        protected override SymmetricAlgorithm CreateAlgorithm()
        {
#if UNITY_WEBPLAYER
            throw new NotSupportedException("CreateAlgorithm");
#else
            return(AesManaged.Create());
#endif
        }
示例#11
0
        public void WrapUnwrapSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            #region Snippet:KeysSample6KeyClient
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample6CreateKey
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey);
            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");
            #endregion

            #region Snippet:KeysSample6CryptographyClient
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample6GenerateKey
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");
            #endregion

            #region Snippet:KeysSample6WrapKey
            WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData);
            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");
            #endregion

            #region Snippet:KeysSample6UnwrapKey
            UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);
            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");
            #endregion

            #region Snippet:KeysSample6DeleteKey
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }
            #endregion

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
        public DataEncryption()
        {
            //
            // TODO: Add constructor logic here
            //
            Aes managedCrypt = AesManaged.Create();

            Aes crypt = Aes.Create("SHA-512");

            crypt.CreateEncryptor();
        }
示例#13
0
        // Decrypt a byte array into a byte array using a key and an IV
        public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
        {
            // Create a MemoryStream that is going to accept the
            // decrypted bytes
            MemoryStream ms = new MemoryStream();

            // Create a symmetric algorithm.
            // We are going to use Rijndael because it is strong and
            // available on all platforms.
            // You can use other algorithms, to do so substitute the next
            // line with something like
            //     TripleDES alg = TripleDES.Create();
            //Rijndael alg = Rijndael.Create();
            Aes alg = AesManaged.Create();

            // Now set the key and the IV.
            // We need the IV (Initialization Vector) because the algorithm
            // is operating in its default
            // mode called CBC (Cipher Block Chaining). The IV is XORed with
            // the first block (8 byte)
            // of the data after it is decrypted, and then each decrypted
            // block is XORed with the previous
            // cipher block. This is done to make encryption more secure.
            // There is also a mode called ECB which does not need an IV,
            // but it is much less secure.
            alg.Key = Key;
            alg.IV  = IV;

            // Create a CryptoStream through which we are going to be
            // pumping our data.
            // CryptoStreamMode.Write means that we are going to be
            // writing data to the stream
            // and the output will be written in the MemoryStream
            // we have provided.
            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);

            // Write the data and make it do the decryption
            cs.Write(cipherData, 0, cipherData.Length);

            // Close the crypto stream (or do FlushFinalBlock).
            // This will tell it that we have done our decryption
            // and there is no more data coming in,
            // and it is now a good time to remove the padding
            // and finalize the decryption process.
            cs.Close();

            // Now get the decrypted data from the MemoryStream.
            // Some people make a mistake of using GetBuffer() here,
            // which is not the right way.
            byte[] decryptedData = ms.ToArray();

            return(decryptedData);
        }
        public void WrapUnwrapSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // First create a RSA key which will be used to wrap and unwrap another key
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");

            // Let's create the CryptographyClient which can perform cryptographic operations with the key we just created.
            // Again we are using the default Azure credential as above.
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());

            // Next we'll generate a symmetric key which we will wrap
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");

            // Wrap the key using RSAOAEP with the created key.
            WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData);

            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");

            // Now unwrap the encrypted key. Note that the same algorithm must always be used for both wrap and unwrap
            UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);

            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");

            // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

            // To ensure the key is deleted on server before we try to purge it.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
示例#15
0
        // Old AES_ENCRYPTION definition:
        static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }
            byte[] encrypted;

            // Create an AES object
            // with the specified key and IV.
            using (Aes aesAlg = AesManaged.Create())
            {
                aesAlg.BlockSize = 128;
                aesAlg.KeySize   = 128;
                aesAlg.Mode      = CipherMode.CBC;
                aesAlg.Padding   = PaddingMode.PKCS7;
                // Should set Key and IV here.  Good approach:
                // derive them from a password via Cryptography.Rfc2898DeriveBytes
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            // Return the encrypted bytes from the memory stream.
            return(encrypted);
        }
示例#16
0
        /// <summary>
        /// Decrypts a string using Advanced Encryption Standard (AES).
        /// </summary>
        /// <param name="cipherText">The encrypted bytes.</param>
        /// <param name="key">The 32-byte encryption key to use.</param>
        /// <param name="iv">A 16-byte initialization vector to use.</param>
        /// <returns>The decrypted string.</returns>
#pragma warning disable CA1707 // Identifiers should not contain underscores (this class is obsolete, we won't fix it)
        public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] key, byte[] iv)
#pragma warning restore CA1707 // Identifiers should not contain underscores
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException(nameof(cipherText));
            }

            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException(nameof(iv));
            }

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (var aes = AesManaged.Create())
            {
                aes.Key = key;
                aes.IV  = iv;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                // Create the streams used for decryption.
                using (MemoryStream memoryStream = new MemoryStream(cipherText))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader decryptReader = new StreamReader(cryptoStream))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = decryptReader.ReadToEnd();
                        }
                    }
                }
            }

            return(plaintext);
        }
示例#17
0
        static String ValidateEncryptionKey(String EncryptionKey)
        {
            String newKey = null;

            if (String.IsNullOrWhiteSpace(EncryptionKey))
            {
                var aes = AesManaged.Create();
                aes.GenerateKey();
                newKey = System.Convert.ToBase64String(aes.Key);
                _warnings.Add($"Using encryption key {newKey}");
                return(newKey);
            }
            return(EncryptionKey);
        }
示例#18
0
        public static byte[] DecryptAndDecompressFile(FileStream stream)
        {
            if (stream.Length < 4)
            {
                throw new SiiFormatException(SiiFormatException.ParseError.InvalidSize);
            }

            stream.Seek(0, SeekOrigin.Begin);

            using var binaryReader = new BinaryReader(stream, Encoding.UTF8, true);
            var    signatureChars = binaryReader.ReadChars(4);
            string signature      = new string(signatureChars);

            if (signature == "SiiN") // File is not encrypted or compressed
            {
                byte[] bytes = binaryReader.ReadBytes((int)stream.Length - 4);
                return(bytes);
            }

            if (signature != "ScsC") // ScsC is the only valid alternative (binary is not supported).
            {
                throw new SiiFormatException(SiiFormatException.ParseError.InvalidSignature);
            }

            ScsCHeader scscHeader = ScsCHeader.DeserializeFromStream(stream);

            byte[] decryptedBytes = new byte[scscHeader.DataSize];

            using (Aes aes = AesManaged.Create())
            {
                aes.IV   = scscHeader.InitVector;
                aes.Key  = Key;
                aes.Mode = CipherMode.CBC;

                using ICryptoTransform decryptor = aes.CreateDecryptor();
                using CryptoStream cryptoStream  = new CryptoStream(stream, decryptor, CryptoStreamMode.Read, true);
                cryptoStream.Read(decryptedBytes);
            }

            using (var outputMemoryStream = new MemoryStream())
                using (var memoryStream = new MemoryStream(decryptedBytes))
                    using (var inflater = new InflaterInputStream(memoryStream))
                    {
                        inflater.CopyTo(outputMemoryStream);

                        byte[] decompressedBytes = outputMemoryStream.ToArray();
                        return(decompressedBytes);
                    }
        }
示例#19
0
        /// <summary>
        /// Encrypts a string using Advanced Encryption Standard (AES).
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="key">The 32-byte encryption key to use.</param>
        /// <param name="iv">A 16-byte initialization vector to use.</param>
        /// <returns>The initialization vector and the encrypted bytes.</returns>
#pragma warning disable CA1707 // Identifiers should not contain underscores (this class is obsolete, we won't fix it)
        public static Tuple <byte[], byte[]> EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv = null)
#pragma warning restore CA1707 // Identifiers should not contain underscores
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException(nameof(plainText));
            }

            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException(nameof(key));
            }

            byte[] encrypted;

            // Create an Aes object
            // with the specified key and IV.
            using (var aes = AesManaged.Create())
            {
                aes.Key = key;
                if (iv != null)
                {
                    // if custom iv use that
                    aes.IV = iv;
                }

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                // Create the streams used for encryption.
                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (var cryptoWriter = new StreamWriter(cryptoStream))
                        {
                            // Write all data to the stream.
                            cryptoWriter.Write(plainText);
                        }

                        encrypted = memoryStream.ToArray();
                    }
                }

                // Return the encrypted bytes from the memory stream.
                return(new Tuple <byte[], byte[]>(aes.IV, encrypted));
            }
        }
示例#20
0
        // Old AES_DECRYPTION function:
        static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");


            // Declare the string used to hold
            // the decrypted text.
            string plaintext = "";

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = AesManaged.Create())
            {

                aesAlg.BlockSize = 128;
                aesAlg.KeySize = 128;
                aesAlg.Mode = CipherMode.CBC;
                aesAlg.Padding = PaddingMode.PKCS7;
                // Should set Key and IV here.  Good approach: 
                // derive them from a password via Cryptography.Rfc2898DeriveBytes 
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }
        /// <summary>
        /// 対称アルゴリズムによる
        /// 暗号化サービスプロバイダを生成
        /// </summary>
        /// <param name="esa">
        /// 対称アルゴリズムによる
        /// 暗号化サービスプロバイダの種類
        /// </param>
        /// <returns>
        /// 対称アルゴリズムによる
        /// 暗号化サービスプロバイダ
        /// </returns>
        private static SymmetricAlgorithm CreateSymmetricAlgorithm(EnumSymmetricAlgorithm esa)
        {
            SymmetricAlgorithm sa = null;

            // AesCryptoServiceProvider, AesManagedは.NET Framework 3.5からの提供。
            // 暗号化プロバイダ選択の優先順は、高い順に、Managed → CAPI(CSP) → CNG。
            // Aesは、ManagedがあるのでCAPI(CSP)のAesCryptoServiceProviderを削除。
            // サポート範囲の変更により、今後、CAPI(CSP)とCNGの優先順位の反転を検討。

            //if (esa == EnumSymmetricAlgorithm.AesCryptoServiceProvider)
            //{
            //    // AesCryptoServiceProviderサービスプロバイダ
            //    sa = AesCryptoServiceProvider.Create(); // devps(1703)
            //}
            //else
            if (esa == EnumSymmetricAlgorithm.AesManaged)
            {
                // AesManagedサービスプロバイダ
                sa = AesManaged.Create(); // devps(1703)
            }
            else if (esa == EnumSymmetricAlgorithm.DESCryptoServiceProvider)
            {
                // DESCryptoServiceProviderサービスプロバイダ
                sa = DESCryptoServiceProvider.Create(); // devps(1703)
            }
            else if (esa == EnumSymmetricAlgorithm.RC2CryptoServiceProvider)
            {
                // RC2CryptoServiceProviderサービスプロバイダ
                sa = RC2CryptoServiceProvider.Create(); // devps(1703)
            }
            else if (esa == EnumSymmetricAlgorithm.RijndaelManaged)
            {
                // RijndaelManagedサービスプロバイダ
                sa = RijndaelManaged.Create(); // devps(1703)
            }
            else if (esa == EnumSymmetricAlgorithm.TripleDESCryptoServiceProvider)
            {
                // TripleDESCryptoServiceProviderサービスプロバイダ
                sa = TripleDESCryptoServiceProvider.Create(); // devps(1703)
            }
            else
            {
                throw new ArgumentException(
                          PublicExceptionMessage.ARGUMENT_INJUSTICE, "EnumSymmetricAlgorithm esa");
            }

            return(sa);
        }
示例#22
0
        /// <summary>
        /// Decrypts a string passed in.
        /// </summary>
        /// <param customerName="stringToDecrypt">String that needs to be deciphered.</param>
        /// <param customerName="ProductPassword">Code to unlock this productPassword.</param>
        /// <returns></returns>
        public static string DecryptString(string stringToDecrypt, string password)
        {
            // initial value
            string decryptedValue = "";

            try
            {
                // if both strings exist
                if (TextHelper.Exists(stringToDecrypt, password))
                {
                    var ivAndCiphertext = Convert.FromBase64String(stringToDecrypt);
                    if (ivAndCiphertext.Length >= 16)
                    {
                        var iv         = new byte[16];
                        var ciphertext = new byte[ivAndCiphertext.Length - 16];
                        Array.Copy(ivAndCiphertext, 0, iv, 0, iv.Length);
                        Array.Copy(ivAndCiphertext, iv.Length, ciphertext, 0, ciphertext.Length);

                        using (var aes = AesManaged.Create())
                            using (var pbkdf2 = new Rfc2898DeriveBytes(password, _pepper, 32767))
                            {
                                var key = pbkdf2.GetBytes(32);

                                aes.Mode    = CipherMode.CBC;
                                aes.Padding = PaddingMode.PKCS7;
                                aes.Key     = key;
                                aes.IV      = iv;

                                // create a new Decryptor
                                using (var aesTransformer = aes.CreateDecryptor())
                                {
                                    // get a byte array of the plain text
                                    var plaintext = aesTransformer.TransformFinalBlock(ciphertext, 0, ciphertext.Length);

                                    // set the return value
                                    decryptedValue = Encoding.UTF8.GetString(plaintext);
                                }
                            }
                    }
                }
            }
            catch
            {
            }

            // return value
            return(decryptedValue);
        }
示例#23
0
        public static string RFIDecrypt(string cipherText, string encryptionKey)
        {
            // will return plain text
            string plainText = string.Empty;

            try {
                if (!String.IsNullOrWhiteSpace(cipherText))
                {
                    // get salted cipher array
                    byte[] saltedCipherBytes = Convert.FromBase64String(cipherText);

                    // create array to hold salt
                    byte[] salt = new byte[16];

                    // create array to hold cipher
                    byte[] cipherBytes = new byte[saltedCipherBytes.Length - salt.Length];

                    // copy salt/cipher to arrays
                    Array.Copy(saltedCipherBytes, 0, salt, 0, salt.Length);
                    Array.Copy(saltedCipherBytes, salt.Length, cipherBytes, 0, saltedCipherBytes.Length - salt.Length);

                    // create new password derived bytes using password/salt
                    using (Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, salt)) {
                        using (Aes aes = AesManaged.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);

                            // Open a new memory stream to write the encrypted data to
                            using (MemoryStream ms = new MemoryStream()) {
                                // Create a crypto stream to perform decryption
                                using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) {
                                    // write decrypted data to memory
                                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                                }
                                // convert decrypted array to plain text string
                                plainText = Encoding.Unicode.GetString(ms.ToArray());
                            }
                            aes.Clear();
                        }
                    }
                }
            }
            catch (Exception) {
                return(string.Empty);
            }
            return(plainText);
        }
示例#24
0
        public VelostiScsi()
        {
            this.Aes         = AesManaged.Create();
            this.Aes.KeySize = 256;
            this.IsBusy      = false;

            this.Worker = new BackgroundWorker();
            this.Worker.WorkerReportsProgress      = true;
            this.Worker.WorkerSupportsCancellation = true;
            this.Worker.DoWork             += new DoWorkEventHandler(TaskWorker_DoWork);
            this.Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(TaskWorker_RunWorkerCompleted);

            this.timer = new Thread(timer_Elapsed);
            this.timer.IsBackground = true;
            this.timer.Start();
        }
示例#25
0
        // Encrypt a file into another file using a password
        public static void Encrypt(string fileIn, string fileOut, string Password)
        {
            // First we are going to open the file streams
            FileStream fsIn  = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);

            // Then we are going to derive a Key and an IV from the
            // Password and create an algorithm
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                                                              new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                                                           0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            //Rijndael alg = Rijndael.Create();
            Aes alg = AesManaged.Create();

            alg.Key = pdb.GetBytes(32);
            alg.IV  = pdb.GetBytes(16);

            // Now create a crypto stream through which we are going
            // to be pumping data.
            // Our fileOut is going to be receiving the encrypted bytes.
            CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write);

            // Now will will initialize a buffer and will be processing
            // the input file in chunks.
            // This is done to avoid reading the whole file (which can
            // be huge) into memory.
            int bufferLen = 4096;

            byte[] buffer = new byte[bufferLen];
            int    bytesRead;

            do
            {
                // read a chunk of data from the input file
                bytesRead = fsIn.Read(buffer, 0, bufferLen);

                // encrypt it
                cs.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);

            // close everything

            // this will also close the unrelying fsOut stream
            cs.Close();
            fsIn.Close();
        }
示例#26
0
        /// <summary>
        /// Decrypt the giving <see cref="Byte"> <see cref="Array"/>.
        /// </summary>
        /// <param name="cipherText">The <see cref="Byte"> <see cref="Array"/> that contains data to decrypt.</param>
        /// <param name="Key">The <see cref="Byte"> <see cref="Array"/> that contains the key.</param>
        /// <param name="IV">The <see cref="Byte"> <see cref="Array"/> that contains the initialize vector.</param>
        /// <returns>The decrypted data.</returns>
        public static byte[] Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(cipherText, null) || cipherText.Length <= 0)
            {
                throw (new ArgumentNullException("cipherText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("IV"));
            }

            // Declare the string used to hold the decrypted text
            byte[] clearBytes = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = AesManaged.Create())
            {
                aesAlg.Key     = Key;
                aesAlg.IV      = IV;
                aesAlg.Padding = PaddingMode.Zeros;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
                    {
                        csDecrypt.Write(cipherText, 0, cipherText.Length);
                        csDecrypt.Flush();
                        csDecrypt.Close();
                    }

                    clearBytes = msDecrypt.ToArray();
                }
            }

            return(clearBytes);
        }
示例#27
0
        /// <summary>
        /// Encrypt the giving <see cref="Byte"> <see cref="Array"/>.
        /// </summary>
        /// <param name="plainText">The <see cref="Byte"> <see cref="Array"/> that contains data to encrypt.</param>
        /// <param name="Key">The <see cref="Byte"> <see cref="Array"/> that contains the key.</param>
        /// <param name="IV">The <see cref="Byte"> <see cref="Array"/> that contains the initialize vector.</param>
        /// <returns>The encrypted data.</returns>
        public static byte[] Encrypt(byte[] plainText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(plainText, null) || plainText.Length <= 0)
            {
                throw (new ArgumentNullException("plainText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("IV"));
            }

            byte[] encrypted = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = AesManaged.Create())
            {
                aesAlg.Key     = Key;
                aesAlg.IV      = IV;
                aesAlg.Padding = PaddingMode.Zeros;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(plainText, 0, plainText.Length);
                        csEncrypt.Flush();
                        csEncrypt.Close();
                    }

                    encrypted = msEncrypt.ToArray();
                }
            }

            // Return the encrypted bytes from the memory stream
            return(encrypted);
        }
示例#28
0
 private static byte[] DecryptDataUsingAes(byte[] key, byte[] salt, byte[] data)
 {
     using (var aes = AesManaged.Create())
     {
         aes.Mode    = CipherMode.CBC;
         aes.Padding = PaddingMode.Zeros;
         using (var decryptor = aes.CreateDecryptor(key, salt))
         {
             using (var cryptoStream = new CryptoStream(new MemoryStream(data, false), decryptor, CryptoStreamMode.Read))
                 using (var outputStream = new MemoryStream(data.Length))
                 {
                     cryptoStream.CopyTo(outputStream);
                     return(outputStream.ToArray());
                 }
         }
     }
 }
示例#29
0
 public override void init(int mode, byte[] key, byte[] iv)
 {
     for (int i = 0; i < counter.Length; i++)
     {
         counter[i] = 0;
     }
     for (int i = 0; i < counterBytes.Length; i++)
     {
         counterBytes[i] = 0;
     }
     aesm           = AesManaged.Create();
     aesm.BlockSize = blockSize * 8;
     //aesm.KeySize = blockSize*8;
     aesm.Key = key;
     aesm.IV  = iv;
     ms       = new MemoryStream(blockSize);
 }
        private static SymmetricAlgorithm GetOrCreateSymmetricAlgorithm(AmazonS3Client s3Client, string bucketName)
        {
            SymmetricAlgorithm result = AesManaged.Create();

            try
            {
                // look for the s3 object that tells us the KMS key has been created
                GetObjectRequest getObjectRequest = new GetObjectRequest()
                {
                    BucketName = bucketName,
                    Key        = KeySymmetricKey
                };

                using (var getObjectResponse = s3Client.GetObject(getObjectRequest))
                    using (var stream = getObjectResponse.ResponseStream)
                    {
                        byte[] keyBytes = new byte[32];
                        stream.Read(keyBytes, 0, keyBytes.Length);
                        result.Key = keyBytes;
                        return(result);
                    }
            }
            catch (AmazonS3Exception e)
            {
                if (NoSuchKeyErrorCode.Equals(e.ErrorCode))
                {
                    //create the symmetric key
                    result.GenerateKey();

                    //save the KMS key ID into s3
                    PutObjectRequest putObjectRequest = new PutObjectRequest
                    {
                        BucketName  = bucketName,
                        Key         = KeySymmetricKey,
                        InputStream = new MemoryStream(result.Key)
                    };
                    s3Client.PutObject(putObjectRequest);
                    return(result);
                }
                else
                {
                    throw;
                }
            }
        }