예제 #1
0
        static async Task <string> DecryptStringFromBytesAsync(byte[] cipherText, byte[] Key, byte[] IV)
        {
            string plaintext = string.Empty;

            using (var aes = new AesCng())
            {
                // Copy given key and IV into AES object
                aes.Key = Key;
                aes.IV  = IV;

                // Create decryptor
                ICryptoTransform decryptor = aes.CreateDecryptor();

                // Create memory stream that will read encrypted bytes from memory (byte[])
                using (var msDecrypt = new MemoryStream(cipherText))
                {
                    // Create crypto stream that does the decryption with the given decryptor
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        // Create reader with which we read the ciphertext for decryption
                        using (var srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read decrypted plaintext from crypto stream
                            plaintext = await srDecrypt.ReadToEndAsync();
                        }
                    }
                }
            }

            return(plaintext);
        }
예제 #2
0
 /// <summary>
 /// Decrypts a cipher text with a password using AES-256 CBC with SHA-256.
 /// </summary>
 /// <param name="cipherText">The cipher text to be decrypted.</param>
 /// <param name="password">The password to decrypt the cipher text with.</param>
 /// <returns>The decrypted text.</returns>
 public static string AESDecrypt(string cipherText, string password)
 {
     if (string.IsNullOrEmpty(cipherText))
     {
         return(string.Empty);
     }
     byte[] iv                  = new byte[16];
     byte[] passwordBytes       = Encoding.UTF8.GetBytes(password);
     byte[] cipherBytes         = Convert.FromBase64String(cipherText);
     byte[] hashedPasswordBytes = SHA256Managed.Create().ComputeHash(passwordBytes);
     Array.Copy(cipherBytes, iv, 16);
     byte[] decryptedBytes = null;
     using (AesCng AES = new AesCng())
     {
         AES.IV      = iv;
         AES.KeySize = 256;
         AES.Mode    = CipherMode.CBC;
         AES.Key     = hashedPasswordBytes;
         using ICryptoTransform decryptor = AES.CreateDecryptor();
         using MemoryStream msDecrypted   = new MemoryStream();
         using (CryptoStream csDecrypt = new CryptoStream(msDecrypted, decryptor, CryptoStreamMode.Write))
         {
             csDecrypt.Write(cipherBytes, 16, cipherBytes.Length - 16);
             csDecrypt.Close();
         }
         decryptedBytes = msDecrypted.ToArray();
     }
     return(Encoding.UTF8.GetString(decryptedBytes));
 }
예제 #3
0
        private byte[] DecryptBytes(string file)
        {
            byte[] encryptedByteArray = File.ReadAllBytes(file);
            using (Aes aes = new AesCng())
            {
                PasswordDeriveBytes pwDerivedBytes = new PasswordDeriveBytes(passwordTextBox.Text, new byte[] { 0x32, 0xF4, 0x83, 0xC });
                aes.Key = pwDerivedBytes.GetBytes(aes.KeySize / 8);
                aes.IV  = pwDerivedBytes.GetBytes(aes.BlockSize / 8);

                GCHandle gcHandle = GCHandle.Alloc(aes.Key, GCHandleType.Pinned);

                using (MemoryStream memStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(encryptedByteArray, 0, encryptedByteArray.Length);
                        cryptoStream.Close();
                        byte[] decryptedBytes = memStream.ToArray();
#if DEBUG
                        Console.WriteLine($"{ConsoleDateTag()} Decrypting {GetFileNameFromPath(file)} using password {passwordTextBox.Text}");
#endif
                        ZeroMemory(gcHandle.AddrOfPinnedObject(), aes.Key.Length);
                        return(decryptedBytes);
                    }
                }
            }
        }
예제 #4
0
        public byte[] Decrypt(byte[] secret, byte[] key, byte[] iv, byte[] aead_aad = null, byte[] aead_associated = null)
        {
            if (key.Length * 8 != this.KeySize)
            {
                throw new InvalidOperationException($"the given key has invalid size {key.Length * 8}, expect {this.KeySize}");
            }
            _aes.Key = key;
            _aes.IV  = iv;
            var decryptor = _aes.CreateDecryptor();

            return(decryptor.TransformFinalBlock(secret, 0, secret.Length));
        }
예제 #5
0
        protected static byte[] Decrypt(ECDiffieHellmanCng ecc, CngKey publicKey, byte[] bytes, int offset, int length)
        {
            using (AesCng aes = new AesCng()) {
                aes.KeySize   = 256;
                aes.BlockSize = 128;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.None;
                aes.Key       = ecc.DeriveKeyMaterial(publicKey);
                aes.IV        = new byte[16];

                using (var decryptor = aes.CreateDecryptor()) return(decryptor.TransformFinalBlock(bytes, offset, length));
            }
        }
예제 #6
0
        public static bool DecryptFile(string filename, string password)
        {
            FileStream file           = File.OpenRead(filename);
            string     outputFileName = $"{filename}.decrypted";

            if (!(File.Exists(filename) && !File.Exists(outputFileName)))
            {
                return(false);
            }

            // read magic first
            byte[] buff = new byte[8];
            int    read = file.Read(buff, 0, 8);
            bool   returnValue;

            if (Encoding.UTF8.GetString(buff) != "Malted__")
            {
                returnValue = false;
            }
            else
            {
                byte[] salt = new byte[8];
                read = file.Read(salt, 0, 8);

                var    deriveKey = new Rfc2898DeriveBytes(password, salt, 1_000_000, HashAlgorithmName.SHA256);
                byte[] tmpKey    = deriveKey.GetBytes(32 + 16);
                byte[] key       = new byte[32];
                byte[] iv        = new byte[16];
                Array.Copy(tmpKey, key, 32);
                Array.Copy(tmpKey, 32, iv, 0, 16);

                var aescng = new AesCng();
                aescng.Mode      = CipherMode.CBC;
                aescng.KeySize   = 256;
                aescng.BlockSize = 128;
                aescng.Padding   = PaddingMode.PKCS7;
                FileStream fileOutputStream = File.Create(outputFileName);
                var        decryptor        = aescng.CreateDecryptor(key, iv);

                using (CryptoStream csDecrypt = new CryptoStream(file, decryptor, CryptoStreamMode.Read))
                {
                    csDecrypt.CopyTo(fileOutputStream);
                }
                returnValue = true;
                fileOutputStream.Close();
            }

            file.Close();

            return(returnValue);
        }
예제 #7
0
 public override string Decrypt(string EncryptedMessage)
 {
     using (var stream = new MemoryStream(Convert.FromBase64String(EncryptedMessage)))
     {
         // Read initialization vector from beginning of encrypted message bytes.
         var initializationVector = new byte[_cipher.IV.Length];
         stream.Read(initializationVector, 0, initializationVector.Length);
         using (var decryptor = _cipher.CreateDecryptor(SharedKey, initializationVector))
             using (var cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
                 using (var streamReader = new StreamReader(cryptoStream))
                 {
                     return(streamReader.ReadToEnd());
                 }
     }
 }
예제 #8
0
        private static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, int nonSecretPayloadLength)
        {
            //Basic Usage Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException($"CryptKey needs to be {KeyBitSize} bit!", nameof(cryptKey));
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage));
            }


            var ivLength = (BlockBitSize / 8);

            using (var aes = new AesCng
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {
                //Grab IV from message
                var iv = new byte[ivLength];
                Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
                    using (var plainTextStream = new MemoryStream())
                    {
                        using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
                            using (var binaryWriter = new BinaryWriter(decrypterStream))
                            {
                                //Decrypt Cipher Text from Message
                                binaryWriter.Write(
                                    encryptedMessage,
                                    nonSecretPayloadLength + iv.Length,
                                    encryptedMessage.Length - nonSecretPayloadLength - iv.Length
                                    );
                            }
                        //Return Plain Text

                        var pt = plainTextStream.ToArray();
                        return(pt);
                    }
            }
        }
예제 #9
0
        private void DecryptButton_Click(object sender, EventArgs e)
        {
            RSA myRSAProv;

            if (CngKey.Exists(KeyContainerEncryptTextBox.Text))
            {
                myRSAProv = new RSACng(CngKey.Open(KeyContainerDecryptTextBox.Text));
            }
            else
            {
                myRSAProv = new RSACng(CngKey.Create(CngAlgorithm.Rsa, KeyContainerDecryptTextBox.Text));
            }

            RSAOAEPKeyExchangeDeformatter myKeyFormatter = new RSAOAEPKeyExchangeDeformatter(myRSAProv);
            AesCng mySymmProv = new AesCng();

            using (FileStream fs = new FileStream(FileDecryptTextBox.Text, FileMode.Open))
            {
                int    keyLength;
                byte[] encrKey;
                int    ivLength;
                byte[] IV;
                using (BinaryReader br = new BinaryReader(fs))
                {
                    keyLength = br.ReadInt32();
                    encrKey   = new byte[keyLength];
                    br.Read(encrKey, 0, keyLength);
                    ivLength = br.ReadInt32();
                    IV       = new byte[ivLength];
                    br.Read(IV, 0, ivLength);

                    byte[] Key = myKeyFormatter.DecryptKeyExchange(encrKey);
                    mySymmProv.Key = Key;
                    mySymmProv.IV  = IV;
                    using (CryptoStream cs = new CryptoStream(fs, mySymmProv.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        int    dataLen = (int)fs.Length - 4 - keyLength - 4 - ivLength;
                        byte[] data    = new byte[dataLen];
                        int    len     = cs.Read(data, 0, dataLen);
                        using (FileStream outStream = File.Open(FileDecryptTextBox.Text.Replace("encrypted", "decrypted"), FileMode.OpenOrCreate))
                        {
                            outStream.Write(data, 0, len);
                        }
                    }
                }
            }
            MessageBox.Show("Decryption completed.");
        }
예제 #10
0
        public static CngKey LoadPrivateKey(string path, SecureString password)
        {
            if (!new FileInfo(path).Exists)
            {
                throw new FileNotFoundException();
            }

            // We need to use the OS for all this

            byte[]      keyData = null;
            KeyFileType type;

            using (var file = new FileStream(path, FileMode.Open, FileAccess.Read))
                using (var reader = new BinaryReader(file)) {
                    type = (KeyFileType)reader.ReadUInt32();
                    if (type != KeyFileType.Private)
                    {
                        throw new ArgumentException();
                    }
                    keyData = reader.ReadBytes(EncryptedECPrivateBlobLength);
                }

            using (AesCng aes = new AesCng()) {
                aes.KeySize   = 256;
                aes.BlockSize = 128;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.None;
                aes.Key       = HashString(password);
                aes.IV        = new byte[16];

                byte[] paddedDecryptedECPrivateBlob = new byte[ECPrivateBlobLength];
                byte[] decryptedECPrivateBlob       = new byte[ECPrivateBlobLength];
                using (var decryptor = aes.CreateDecryptor()) {
                    paddedDecryptedECPrivateBlob = decryptor.TransformFinalBlock(keyData, 0, keyData.Length);
                    Buffer.BlockCopy(paddedDecryptedECPrivateBlob, 0, decryptedECPrivateBlob, 0, ECPrivateBlobLength);
                }

                return(CngKey.Import(decryptedECPrivateBlob, CngKeyBlobFormat.EccPrivateBlob));
            }
        }
예제 #11
0
        static async Task <string> Decrypt(byte[] bytes, byte[] key, byte[] vector)
        {
            string result;

            using (var aes = new AesCng())
            {
                aes.Key = key;
                aes.IV  = vector;
                using (var memoryStream = new MemoryStream(bytes))
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (var reader = new StreamReader(cryptoStream))
                        {
                            result = await reader.ReadToEndAsync();
                        }
                    }
                }
            }

            return(result);
        }
예제 #12
0
        public void AesCngCreateEncryptor()
        {
            using var aes = new AesCng();
            using var rng = new RNGCryptoServiceProvider();

            var noParams = aes.CreateEncryptor(); // Compliant

            aes.GenerateKey();
            var withGeneratedKey = aes.CreateEncryptor(); // Compliant

            var constantIV   = new byte[16];
            var withConstant = aes.CreateEncryptor(aes.Key, constantIV); // Noncompliant

            aes.GenerateIV();
            aes.CreateEncryptor();
            var withGeneratedKeyAndIV = aes.CreateEncryptor(aes.Key, aes.IV);

            aes.CreateDecryptor(aes.Key, constantIV); // Compliant, we do not check CreateDecryptor

            rng.GetBytes(constantIV);
            var fromRng = aes.CreateEncryptor(aes.Key, constantIV);
        }
        public void AuthenticatedSymmetricAlgorithmVerifierTestNegativeAuthenticationEncryptStandardDecryptTest()
        {
            byte[] plaintext  = Encoding.UTF8.GetBytes("Plaintext");
            byte[] ciphertext = null;

            byte[] key = null;
            SymmetricEncryptionState encryptionState = null;

            using (AuthenticatedSymmetricAlgorithm encryptAes = new AuthenticatedAesCng().EnableLogging())
            {
                key           = encryptAes.Key;
                encryptAes.IV = new byte[] { 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

                using (IAuthenticatedCryptoTransform encryptor = encryptAes.CreateAuthenticatedEncryptor())
                    using (MemoryStream ms = new MemoryStream())
                        using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                        {
                            cs.Write(plaintext, 0, plaintext.Length);
                            cs.FlushFinalBlock();

                            ciphertext      = ms.ToArray();
                            encryptionState = encryptAes.GetLastEncryptionState();
                        }
            }

            using (SymmetricAlgorithm decryptAes = new AesCng().EnableDecryptionVerification(encryptionState))
            {
                decryptAes.Key = key;

                using (MemoryStream ms = new MemoryStream())
                    using (CryptoStream cs = new CryptoStream(ms, decryptAes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(ciphertext, 0, ciphertext.Length);
                        cs.FlushFinalBlock();
                    }
            }

            Assert.Fail("Decryption should have failed.");
        }
예제 #14
0
 private string DecryptPayload(string cipher, string key)
 {
     try
     {
         byte[] cipherBytes = Convert.FromBase64String(cipher);
         using (AesCng aes = new AesCng())
         {
             byte[] keyBytes = CreatePasswordFromKey(key);
             aes.Key = keyBytes;
             aes.IV  = _iv;
             using (ICryptoTransform cryptoTransform = aes.CreateDecryptor())
             {
                 byte[] plainBytes = cryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
                 return(Encoding.UTF8.GetString(plainBytes));
             }
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.ToString());
         return(string.Empty);
     }
 }
예제 #15
0
        /// <summary></summary>
        public byte[] DecryptAes(byte[] abEncrypted, byte[] abKey)
        {
            byte[] abReturn = null;

            if ((abEncrypted != null) && (abEncrypted.Length > ciAesBlockLength) && (abKey != null))
            {
                _AesServices.Padding = PaddingMode.PKCS7;

                for (int i = 0; i < ciAesBlockLength; i++)
                {
                    _abInitialisationVector[i] = abEncrypted[i];
                }

                using (ICryptoTransform AesDecryptor = _AesServices.CreateDecryptor(abKey, _abInitialisationVector))
                {
                    using (MemoryStream EncryptedStream = new MemoryStream(abEncrypted, ciAesBlockLength, abEncrypted.Length - ciAesBlockLength))
                    {
                        try
                        {
                            using (CryptoStream AesCryptoStream = new CryptoStream(EncryptedStream, AesDecryptor, CryptoStreamMode.Read))
                            {
                                using (MemoryStream DecryptedStream = new MemoryStream())
                                {
                                    AesCryptoStream.CopyTo(DecryptedStream);
                                    abReturn = DecryptedStream.ToArray();
                                }
                            }
                        }
                        catch (CryptographicException)
                        {
                            //
                        }
                    }
                }
            }
            return(abReturn);
        }
예제 #16
0
        private void DecryptButton_Click(object sender, EventArgs e)
        {
            using (FileStream fStream = File.OpenRead(FileDecryptTextBox.Text))
            {
                byte[] salt;
                int    saltLength;
                byte[] iv;
                int    ivLength;
                using (BinaryReader reader = new BinaryReader(fStream))
                {
                    saltLength = reader.ReadInt32();
                    salt       = reader.ReadBytes(saltLength);
                    ivLength   = reader.ReadInt32();
                    iv         = reader.ReadBytes(ivLength);


                    AesCng             algorithm    = new AesCng();
                    Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(PasswordDecryptTextBox.Text, salt);
                    byte[]             key          = keyGenerator.GetBytes(algorithm.KeySize / 8);

                    ICryptoTransform cryptoTransformer = algorithm.CreateDecryptor(key, iv);

                    using (CryptoStream cStream = new CryptoStream(fStream, cryptoTransformer, CryptoStreamMode.Read))
                    {
                        using (BinaryReader sReader = new BinaryReader(cStream))
                        {
                            byte[] data = sReader.ReadBytes((int)fStream.Length - 4 - saltLength - 4 - ivLength);
                            using (FileStream outStream = File.Open(FileDecryptTextBox.Text.Replace("encrypted", "decrypted"), FileMode.OpenOrCreate))
                            {
                                outStream.Write(data, 0, data.Length);
                            }
                        }
                    }
                }
            }
            MessageBox.Show("Decryption completed.");
        }
예제 #17
0
        public CngKey GetDecryptionKey()
        {
            byte[]      keyData = null;
            KeyFileType type;

            using (var file = new System.IO.FileStream(DecryptionKeyFile, System.IO.FileMode.Open))
                using (var reader = new System.IO.BinaryReader(file)) {
                    type = (KeyFileType)reader.ReadUInt32();
                    if (type != KeyFileType.Private)
                    {
                        throw new CommandLineArgumentException("Decryption Key File must contain a private key");
                    }
                    keyData = reader.ReadBytes(EncryptedECPrivateBlobLength);
                }

            Console.Write("Enter Decryption Key Password: ");
            string p1 = Console.ReadLine();

            using (AesCng aes = new AesCng()) {
                aes.KeySize   = 256;
                aes.BlockSize = 128;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.None;
                aes.Key       = HashString(p1);
                aes.IV        = new byte[16];

                byte[] paddedDecryptedECPrivateBlob = new byte[ECPrivateBlobLength];
                byte[] decryptedECPrivateBlob       = new byte[ECPrivateBlobLength];
                using (var decryptor = aes.CreateDecryptor()) {
                    paddedDecryptedECPrivateBlob = decryptor.TransformFinalBlock(keyData, 0, keyData.Length);
                    Buffer.BlockCopy(paddedDecryptedECPrivateBlob, 0, decryptedECPrivateBlob, 0, ECPrivateBlobLength);
                }

                return(CngKey.Import(decryptedECPrivateBlob, CngKeyBlobFormat.EccPrivateBlob));
            }
        }
        public void FileHeaderSaveLoadTest()
        {
            ConfigurationTest.Initialize();

            using (var io = ConfigurationTest.CreateMemoryIO()) {
                SimpleClusterIO cio = new SimpleClusterIO(io);

                Random            r   = new Random(Seed);
                FileHeaderCluster csc = new FileHeaderCluster(Address);
                csc.Initialize();

                int      fileID             = r.Next();
                int      nextClusterAddress = r.Next();
                int      bytesUsed          = r.Next();
                DateTime writeTime          = new DateTime(2005, 1, 1);
                int      parentID           = r.Next();
                string   name = r.Next().ToString();

                // File System Cluster fields
                csc.FileID             = fileID;
                csc.NextClusterAddress = nextClusterAddress;
                csc.BytesUsed          = bytesUsed;
                csc.WriteTime          = writeTime;

                // File Header fields
                csc.ParentID = parentID;
                csc.Name     = name;

                byte[] data = new byte[FileHeaderCluster.DataSize];
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (byte)(r.Next() & byte.MaxValue);
                }

                csc.Data.Set(0, data);
                cio.Save(csc);

                int       offset = 0;
                DataBlock b      = new DataBlock(
                    io.Bytes,
                    Address * Configuration.Geometry.BytesPerCluster,
                    Configuration.Geometry.BytesPerCluster);

                byte[] marker = b.ToByteArray(offset, Constants.SrfsMarker.Length);
                Assert.IsTrue(marker.SequenceEqual(Constants.SrfsMarker));
                offset += marker.Length;

                byte[] version = b.ToByteArray(offset, Constants.CurrentVersion.Length);
                Assert.IsTrue(version.SequenceEqual(Constants.CurrentVersion));
                offset += version.Length;

                Guid guid = new Guid(b.ToByteArray(offset, Constants.GuidLength));
                Assert.AreEqual(guid, Configuration.FileSystemID);
                offset += Constants.GuidLength;

                byte[] signatureBytes = b.ToByteArray(offset, Signature.Length);
                offset += Signature.Length;

                byte[] thumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length);
                Assert.IsTrue(thumbprintBytes.SequenceEqual(Configuration.CryptoSettings.SigningKeyThumbprint.Bytes));
                offset += KeyThumbprint.Length;

                byte[] hashBytes = b.ToByteArray(offset, 32);
                offset += 32;

                ClusterType clusterType = (ClusterType)b.ToByte(offset);
                Assert.AreEqual(clusterType, ClusterType.FileHeader);
                offset += sizeof(ClusterType);

                Assert.AreEqual(fileID, b.ToInt32(offset));
                offset += sizeof(int);

                Assert.AreEqual(nextClusterAddress, b.ToInt32(offset));
                offset += sizeof(int);

                Assert.AreEqual(bytesUsed, b.ToInt32(offset));
                offset += sizeof(int);

                Assert.AreEqual(writeTime, new DateTime(b.ToInt64(offset)));
                offset += sizeof(long);

                Assert.AreEqual(parentID, b.ToInt32(offset));
                offset += sizeof(int);

                int nameLength = b.ToByte(offset);
                offset += sizeof(byte);
                Assert.AreEqual(name, b.ToString(offset, nameLength));
                offset += Constants.MaximumNameLength * sizeof(char);

                byte[] encryptionThumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length);
                Assert.IsTrue(encryptionThumbprintBytes.SequenceEqual(Configuration.CryptoSettings.EncryptionKeyThumbprint.Bytes));
                offset += KeyThumbprint.Length;

                byte[] publicKeyBytes = b.ToByteArray(offset, PublicKey.Length);
                offset += PublicKey.Length;

                int dataLength = Configuration.Geometry.BytesPerCluster - offset;
                int padding    = dataLength % 16;
                dataLength -= padding;
                Assert.AreEqual(data.Length, dataLength);
                offset += padding;

                using (ECDiffieHellmanCng dest = new ECDiffieHellmanCng(Configuration.CryptoSettings.DecryptionKey))
                    using (AesCng aes = new AesCng()) {
                        aes.KeySize   = 256;
                        aes.BlockSize = 128;
                        aes.Mode      = CipherMode.CBC;
                        aes.Padding   = PaddingMode.None;
                        aes.Key       = dest.DeriveKeyMaterial(new PublicKey(publicKeyBytes).GetCngKey());
                        aes.IV        = new byte[16];

                        using (var decryptor = aes.CreateDecryptor()) {
                            byte[] decryptedData = b.TransformFinalBlock(decryptor, offset, dataLength);
                            for (int i = 0; i < dataLength; i++)
                            {
                                Assert.AreEqual(data[i], decryptedData[i]);
                            }
                        }
                    }

                FileHeaderCluster csc2 = new FileHeaderCluster(Address);
                cio.Load(csc2);

                Assert.IsTrue(csc2.Marker.SequenceEqual(Constants.SrfsMarker));
                Assert.IsTrue(csc2.Version.SequenceEqual(Constants.CurrentVersion));
                Assert.AreEqual(csc2.VolumeID, Configuration.FileSystemID);
                Assert.AreEqual(csc2.Type, ClusterType.FileHeader);
                Assert.AreEqual(csc2.FileID, fileID);
                Assert.AreEqual(csc2.NextClusterAddress, nextClusterAddress);
                Assert.AreEqual(csc2.BytesUsed, bytesUsed);
                Assert.AreEqual(csc2.WriteTime, writeTime);
                Assert.AreEqual(csc2.ParentID, parentID);
                Assert.AreEqual(csc2.Name, name);

                for (int i = 0; i < dataLength; i++)
                {
                    Assert.AreEqual(data[i], csc2.Data.ToByte(i));
                }
            }
        }
예제 #19
0
파일: Program.cs 프로젝트: OMV0102/infbez3
        // функция для СИММ. Шифрования массива байт заданным алгоритмом и режимом, на выходе массив байт
        // аргументы: вход. байты; ключ; вектор инициализации; алгоритм AES / 3DES; режим шифруем / расшифровываем
        public static Byte[] SimmAlg(Byte[] arrayByte_in, Byte[] key, Byte[] iv, string selectedAlgSimm, bool EncryptIsTrue)
        {
            byte[]           arrayByte_out = new byte[0]; // Выходная последовательность байт после шифрования/расшифровки
            ICryptoTransform cryptoTransform;

            try
            {
                switch (selectedAlgSimm) // Получение хеша определенным алгоритмом
                {
                case "AES":
                    AesCng aescng = new AesCng(); // объект класса у алгоритма AES
                    aescng.Key = key;             // присваиваем ключ из аргумента
                    aescng.IV  = iv;              // присваиваем вектор из аргумента
                    if (EncryptIsTrue == true)    // если вызвали для ШИФРования AES
                    {
                        // создали объект-шифратор
                        cryptoTransform = aescng.CreateEncryptor();
                    }
                    else      // если вызвали для РАСшифровки AES
                    {
                        // создали объект-расшифратор
                        cryptoTransform = aescng.CreateDecryptor();
                    }
                    // получили байты на выходе
                    arrayByte_out = cryptoTransform.TransformFinalBlock(arrayByte_in, 0, arrayByte_in.Length);

                    aescng.Dispose();          // освобождаем ресурсы
                    cryptoTransform.Dispose(); // освобождаем ресурсы
                    break;

                case "3DES":
                    TripleDESCng tripledescng = new TripleDESCng(); // объект класса у алгоритма AES
                    tripledescng.Key = key;                         //  присваиваем ключ из аргумента
                    tripledescng.IV  = iv;                          //  присваиваем вектор из аргумента
                    if (EncryptIsTrue == true)                      // если вызвали для ШИФРования AES
                    {
                        // создали объект-шифратор
                        cryptoTransform = tripledescng.CreateEncryptor();
                    }
                    else      // если вызвали для РАСшифровки 3DES
                    {
                        // создали объект-расшифратор
                        cryptoTransform = tripledescng.CreateDecryptor();
                    }
                    // получили байты на выходе
                    arrayByte_out = cryptoTransform.TransformFinalBlock(arrayByte_in, 0, arrayByte_in.Length);

                    tripledescng.Dispose();     // освобождаем ресурсы
                    cryptoTransform.Dispose();  // освобождаем ресурсы
                    break;

                default: break;
                }
            }
            catch (Exception error)
            {
                //MessageBox.Show(error.Message, "НЕПРЕДВИДЕННАЯ ОШИБКА", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (EncryptIsTrue == true) // если шифрование
                {
                    MessageBox.Show(error.Message, "НЕПРЕДВИДЕННАЯ ОШИБКА", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                //MessageBox.Show("Ключ или вектор инициализации не подходят", "Ошибка шифрования", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    MessageBox.Show("Заданные ключ или вектор инициализации не подходят для заданного шифра!\nРасшифровка не возможна.", "Ошибка расшифровки", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            return(arrayByte_out);
        }