public string EncryptString(string plainText, string keyName)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("PlainText cannot be empty");
            }
            if (keyName == null || keyName.Length <= 0)
            {
                throw new ArgumentNullException("Key Name cannot be empty");
            }

            var keyString = _secretStore.GetKey(keyName, _defaultKeyIndex);

            switch (_defaultAlgorithm)
            {
            case EncryptionAlgorithm.AES128_CBC:
                var aes128 = new AES128_CBC();
                return(aes128.Encrypt(plainText, keyString, _defaultAlgorithm, _defaultKeyIndex));

            case EncryptionAlgorithm.AES128_CTR:
            case EncryptionAlgorithm.AES256_CTR:
                var aesCTR = new AES_CTR();
                return(aesCTR.Encrypt(plainText, keyString, _defaultAlgorithm, _defaultKeyIndex));

            default:
                throw new NotImplementedException(_defaultAlgorithm.ToString());
            }
        }
コード例 #2
0
ファイル: Cryptography.cs プロジェクト: lionsguard/perenthia
        /// <summary>
        /// Gets an instance of the SymmetricAlgorithm class for the specified algorithm.
        /// </summary>
        /// <param name="algorithm">The EncryptionAlgorithm value specifying the type of crypto service provider to create.</param>
        /// <returns>A SymmetricAlgorithm instance for the specified algorithm preset with the specified Key and IV.</returns>
        private static SymmetricAlgorithm GetCryptoServiceProvider(EncryptionAlgorithm algorithm)
        {
            SymmetricAlgorithm crypto = null;

            switch (algorithm)
            {
            case EncryptionAlgorithm.Des:
                crypto = new DESCryptoServiceProvider();
                break;

            case EncryptionAlgorithm.Rc2:
                crypto = new RC2CryptoServiceProvider();
                break;

            case EncryptionAlgorithm.Rijndael:
                crypto = new RijndaelManaged();
                break;

            case EncryptionAlgorithm.TripleDes:
                crypto = new TripleDESCryptoServiceProvider();
                break;

            default:
                throw new NotSupportedException(String.Concat("The EncryptionAlgorithm value specified '",
                                                              algorithm.ToString(), "' is not supported."));
            }
            return(crypto);
        }
コード例 #3
0
        protected override void ProcessRecord()
        {
            var vgw = new CreateVirtualGatewayNetworkConnection
            {
                AuthenticationMethod        = AuthenticationMethod.ToString(),
                DestinationIpAddress        = DestinationIpAddress,
                DestinationPrefix           = DestinationPrefix,
                MainModeDiffieHellmanGroup  = DiffieHellmanGroup.ToString(),
                MainModeEncryptionAlgorithm = EncryptionAlgorithm.ToString(),
                MainModeIntegrityAlgorithm  = IntegrityAlgorithm.ToString(),
                MainModeSALifeTimeKiloBytes = MainModeSALifeTimeKiloBytes,
                MainModeSALifeTimeSeconds   = MainModeSALifeTimeSeconds,
                QuickModeAuthenticationTransformationConstant = AuthenticationTranformationConstant.ToString(),
                QuickModeCipherTransformationConstant         = CipherTransformationConstant.ToString(),
                QuickModeIdleDisconnectSeconds = QuickModeIdleDisconnectSeconds,
                QuickModePerfectForwardSecrecy = PerfectForwardSecrecy.ToString(),
                QuickModeSALifeTimeKiloBytes   = QuickModeSALifeTimeKiloBytes,
                QuickModeSALifeTimeSeconds     = QuickModeSALifeTimeSeconds,
                Name         = Name,
                SharedSecret = SharedSecret
            };

            var job = Create(Connection, vgw, VirtualGatewayId);


            if (Wait)
            {
                WriteObject(WaitJobFinished(job.Id, Connection, VirtualGatewayId));
            }
            else
            {
                WriteObject(job);
            }
        }
コード例 #4
0
        private async Task <Key> CreateTestKey(EncryptionAlgorithm algorithm)
        {
            string keyName = Recording.GenerateId();

            switch (algorithm.ToString())
            {
            case EncryptionAlgorithm.Rsa15Value:
            case EncryptionAlgorithm.RsaOaepValue:
            case EncryptionAlgorithm.RsaOaep256Value:
                return(await Client.CreateKeyAsync(keyName, KeyType.Rsa));

            default:
                throw new ArgumentException("Invalid Algorithm", nameof(algorithm));
            }
        }
コード例 #5
0
        private async Task <KeyVaultKey> CreateTestKey(EncryptionAlgorithm algorithm)
        {
            string keyName = Recording.GenerateId();

            switch (algorithm.ToString())
            {
            case EncryptionAlgorithm.Rsa15Value:
            case EncryptionAlgorithm.RsaOaepValue:
            case EncryptionAlgorithm.RsaOaep256Value:
                return(await Client.CreateRsaKeyAsync(
                           new CreateRsaKeyOptions(keyName)));

            case EncryptionAlgorithm.A128CbcValue:
            case EncryptionAlgorithm.A128CbcPadValue:
            case EncryptionAlgorithm.A128GcmValue:
                return(await Client.CreateOctKeyAsync(
                           new CreateOctKeyOptions(keyName)
                {
                    KeySize = 128,
                }));

            case EncryptionAlgorithm.A192CbcValue:
            case EncryptionAlgorithm.A192CbcPadValue:
            case EncryptionAlgorithm.A192GcmValue:
                return(await Client.CreateOctKeyAsync(
                           new CreateOctKeyOptions(keyName)
                {
                    KeySize = 192,
                }));

            case EncryptionAlgorithm.A256CbcValue:
            case EncryptionAlgorithm.A256CbcPadValue:
            case EncryptionAlgorithm.A256GcmValue:
                return(await Client.CreateOctKeyAsync(
                           new CreateOctKeyOptions(keyName)
                {
                    KeySize = 256,
                }));

            default:
                throw new ArgumentException("Invalid Algorithm", nameof(algorithm));
            }
        }
コード例 #6
0
        public void CreateAuthenticatedEncryptor_RoundTripsData_AesGcmImplementation(EncryptionAlgorithm encryptionAlgorithm)
        {
            // Parse test input
            int keyLengthInBits = Int32.Parse(Regex.Match(encryptionAlgorithm.ToString(), @"^AES_(?<keyLength>\d{3})_GCM$").Groups["keyLength"].Value, CultureInfo.InvariantCulture);

            // Arrange
            var masterKey = Secret.Random(512 / 8);
            var control   = new CngGcmAuthenticatedEncryptor(
                keyDerivationKey: masterKey,
                symmetricAlgorithmHandle: CachedAlgorithmHandles.AES_GCM,
                symmetricAlgorithmKeySizeInBytes: (uint)(keyLengthInBits / 8));
            var test = CreateEncryptorInstanceFromDescriptor(CreateDescriptor(encryptionAlgorithm, ValidationAlgorithm.HMACSHA256 /* unused */, masterKey));

            // Act & assert - data round trips properly from control to test
            byte[] plaintext          = new byte[] { 1, 2, 3, 4, 5 };
            byte[] aad                = new byte[] { 2, 4, 6, 8, 0 };
            byte[] ciphertext         = control.Encrypt(new ArraySegment <byte>(plaintext), new ArraySegment <byte>(aad));
            byte[] roundTripPlaintext = test.Decrypt(new ArraySegment <byte>(ciphertext), new ArraySegment <byte>(aad));
            Assert.Equal(plaintext, roundTripPlaintext);
        }
        public void CreateAuthenticatedEncryptor_RoundTripsData_CngGcmImplementation(EncryptionAlgorithm encryptionAlgorithm)
        {
            // Parse test input
            int keyLengthInBits = Int32.Parse(Regex.Match(encryptionAlgorithm.ToString(), @"^AES_(?<keyLength>\d{3})_GCM$").Groups["keyLength"].Value, CultureInfo.InvariantCulture);

            // Arrange
            var masterKey = Secret.Random(512 / 8);
            var control = new GcmAuthenticatedEncryptor(
                keyDerivationKey: masterKey,
                symmetricAlgorithmHandle: CachedAlgorithmHandles.AES_GCM,
                symmetricAlgorithmKeySizeInBytes: (uint)(keyLengthInBits / 8));
            var test = CreateDescriptor(encryptionAlgorithm, ValidationAlgorithm.HMACSHA256 /* unused */, masterKey).CreateEncryptorInstance();

            // Act & assert - data round trips properly from control to test
            byte[] plaintext = new byte[] { 1, 2, 3, 4, 5 };
            byte[] aad = new byte[] { 2, 4, 6, 8, 0 };
            byte[] ciphertext = control.Encrypt(new ArraySegment<byte>(plaintext), new ArraySegment<byte>(aad));
            byte[] roundTripPlaintext = test.Decrypt(new ArraySegment<byte>(ciphertext), new ArraySegment<byte>(aad));
            Assert.Equal(plaintext, roundTripPlaintext);
        }
コード例 #8
0
        public void CreateAuthenticatedEncryptor_RoundTripsData_ManagedImplementation(EncryptionAlgorithm encryptionAlgorithm, ValidationAlgorithm validationAlgorithm)
        {
            // Parse test input
            int keyLengthInBits = Int32.Parse(Regex.Match(encryptionAlgorithm.ToString(), @"^AES_(?<keyLength>\d{3})_CBC$").Groups["keyLength"].Value, CultureInfo.InvariantCulture);

            // Arrange
            var masterKey = Secret.Random(512 / 8);
            var control   = new ManagedAuthenticatedEncryptor(
                keyDerivationKey: masterKey,
                symmetricAlgorithmFactory: () => new AesCryptoServiceProvider(),
                symmetricAlgorithmKeySizeInBytes: keyLengthInBits / 8,
                validationAlgorithmFactory: () => KeyedHashAlgorithm.Create(validationAlgorithm.ToString()));
            var test = CreateDescriptor(encryptionAlgorithm, validationAlgorithm, masterKey).CreateEncryptorInstance();

            // Act & assert - data round trips properly from control to test
            byte[] plaintext          = new byte[] { 1, 2, 3, 4, 5 };
            byte[] aad                = new byte[] { 2, 4, 6, 8, 0 };
            byte[] ciphertext         = control.Encrypt(new ArraySegment <byte>(plaintext), new ArraySegment <byte>(aad));
            byte[] roundTripPlaintext = test.Decrypt(new ArraySegment <byte>(ciphertext), new ArraySegment <byte>(aad));
            Assert.Equal(plaintext, roundTripPlaintext);
        }
コード例 #9
0
        public void CreateAuthenticatedEncryptor_RoundTripsData_CngCbcImplementation(EncryptionAlgorithm encryptionAlgorithm, ValidationAlgorithm validationAlgorithm)
        {
            // Parse test input
            int    keyLengthInBits = Int32.Parse(Regex.Match(encryptionAlgorithm.ToString(), @"^AES_(?<keyLength>\d{3})_CBC$").Groups["keyLength"].Value, CultureInfo.InvariantCulture);
            string hashAlgorithm   = Regex.Match(validationAlgorithm.ToString(), @"^HMAC(?<hashAlgorithm>.*)$").Groups["hashAlgorithm"].Value;

            // Arrange
            var masterKey = Secret.Random(512 / 8);
            var control   = new CbcAuthenticatedEncryptor(
                keyDerivationKey: masterKey,
                symmetricAlgorithmHandle: CachedAlgorithmHandles.AES_CBC,
                symmetricAlgorithmKeySizeInBytes: (uint)(keyLengthInBits / 8),
                hmacAlgorithmHandle: BCryptAlgorithmHandle.OpenAlgorithmHandle(hashAlgorithm, hmac: true));
            var test = CreateDescriptor(encryptionAlgorithm, validationAlgorithm, masterKey).CreateEncryptorInstance();

            // Act & assert - data round trips properly from control to test
            byte[] plaintext          = new byte[] { 1, 2, 3, 4, 5 };
            byte[] aad                = new byte[] { 2, 4, 6, 8, 0 };
            byte[] ciphertext         = control.Encrypt(new ArraySegment <byte>(plaintext), new ArraySegment <byte>(aad));
            byte[] roundTripPlaintext = test.Decrypt(new ArraySegment <byte>(ciphertext), new ArraySegment <byte>(aad));
            Assert.Equal(plaintext, roundTripPlaintext);
        }
コード例 #10
0
        public async Task EncryptLocalDecryptOnManagedHsm([EnumValues(
                                                               nameof(EncryptionAlgorithm.A128Cbc),
                                                               nameof(EncryptionAlgorithm.A192Cbc),
                                                               nameof(EncryptionAlgorithm.A256Cbc),
                                                               nameof(EncryptionAlgorithm.A128CbcPad),
                                                               nameof(EncryptionAlgorithm.A192CbcPad),
                                                               nameof(EncryptionAlgorithm.A256CbcPad))] EncryptionAlgorithm algorithm)
        {
            int        keySizeInBytes = algorithm.GetAesCbcEncryptionAlgorithm().KeySizeInBytes;
            JsonWebKey jwk            = KeyUtilities.CreateAesKey(keySizeInBytes, s_aesKeyOps);

            string      keyName = Recording.GenerateId();
            KeyVaultKey key     = await Client.ImportKeyAsync(
                new ImportKeyOptions(keyName, jwk));

            RegisterForCleanup(key.Name);

            CryptographyClient remoteClient = GetCryptoClient(key.Id, forceRemote: true);
            CryptographyClient localClient  = GetLocalCryptoClient(jwk);

            byte[] plaintext = new byte[32];
            Recording.Random.NextBytes(plaintext);

            byte[] iv = new byte[16];
            if (algorithm.GetAesCbcEncryptionAlgorithm() is AesCbc)
            {
                Recording.Random.NextBytes(iv);
            }

            EncryptParameters encryptParams = algorithm.ToString() switch
            {
                EncryptionAlgorithm.A128CbcValue => EncryptParameters.A128CbcParameters(plaintext, iv),
                EncryptionAlgorithm.A192CbcValue => EncryptParameters.A192CbcParameters(plaintext, iv),
                EncryptionAlgorithm.A256CbcValue => EncryptParameters.A256CbcParameters(plaintext, iv),

                EncryptionAlgorithm.A128CbcPadValue => EncryptParameters.A128CbcPadParameters(plaintext, iv),
                EncryptionAlgorithm.A192CbcPadValue => EncryptParameters.A192CbcPadParameters(plaintext, iv),
                EncryptionAlgorithm.A256CbcPadValue => EncryptParameters.A256CbcPadParameters(plaintext, iv),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            EncryptResult encrypted = await localClient.EncryptAsync(encryptParams);

            Assert.IsNotNull(encrypted.Ciphertext);

            DecryptParameters decryptParameters = algorithm.ToString() switch
            {
                EncryptionAlgorithm.A128CbcValue => DecryptParameters.A128CbcParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A192CbcValue => DecryptParameters.A192CbcParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A256CbcValue => DecryptParameters.A256CbcParameters(encrypted.Ciphertext, encrypted.Iv),

                EncryptionAlgorithm.A128CbcPadValue => DecryptParameters.A128CbcPadParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A192CbcPadValue => DecryptParameters.A192CbcPadParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A256CbcPadValue => DecryptParameters.A256CbcPadParameters(encrypted.Ciphertext, encrypted.Iv),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            DecryptResult decrypted = await remoteClient.DecryptAsync(decryptParameters);

            Assert.IsNotNull(decrypted.Plaintext);

            CollectionAssert.AreEqual(plaintext, decrypted.Plaintext);
        }
コード例 #11
0
ファイル: Zip64Tests.cs プロジェクト: mattleibow/Zip.Portable
        void _Zip64_Over65534Entries(Zip64Option z64option,
                                            EncryptionAlgorithm encryption,
                                            Ionic.Zlib.CompressionLevel compression)
        {
            // Emitting a zip file with > 65534 entries requires the use of ZIP64 in
            // the central directory.
            int numTotalEntries = _rnd.Next(4616)+65534;
            //int numTotalEntries = _rnd.Next(461)+6534;
            //int numTotalEntries = _rnd.Next(46)+653;
            string enc = encryption.ToString();
            if (enc.StartsWith("WinZip")) enc = enc.Substring(6);
            else if (enc.StartsWith("Pkzip")) enc = enc.Substring(0,5);
            string zipFileToCreate = String.Format("Zip64.ZF_Over65534.{0}.{1}.{2}.zip",
                                                   z64option.ToString(),
                                                   enc,
                                                   compression.ToString());

            _testTitle = String.Format("ZipFile #{0} 64({1}) E({2}), C({3})",
                                       numTotalEntries,
                                       z64option.ToString(),
                                       enc,
                                       compression.ToString());
            _txrx = TestUtilities.StartProgressMonitor(zipFileToCreate,
                                                       _testTitle,
                                                       "starting up...");

            _txrx.Send("pb 0 max 4"); // 3 stages: AddEntry, Save, Verify
            _txrx.Send("pb 0 value 0");

            string password = Path.GetRandomFileName();

            string statusString = String.Format("status Encrypt:{0} Compress:{1}...",
                                                enc,
                                                compression.ToString());

            int numSaved = 0;
            var saveProgress = new EventHandler<SaveProgressEventArgs>( (sender, e) => {
                    switch (e.EventType)
                    {
                        case ZipProgressEventType.Saving_Started:
                        _txrx.Send("status saving...");
                        _txrx.Send("pb 1 max " + numTotalEntries);
                        numSaved= 0;
                        break;

                        case ZipProgressEventType.Saving_AfterWriteEntry:
                        numSaved++;
                        if ((numSaved % 128) == 0)
                        {
                            _txrx.Send("pb 1 value " + numSaved);
                            _txrx.Send(String.Format("status Saving entry {0}/{1} ({2:N0}%)",
                                                     numSaved, numTotalEntries,
                                                     numSaved / (0.01 * numTotalEntries)
                                                     ));
                        }
                        break;

                        case ZipProgressEventType.Saving_Completed:
                        _txrx.Send("status Save completed");
                        _txrx.Send("pb 1 max 1");
                        _txrx.Send("pb 1 value 1");
                        break;
                    }
                });

            string contentFormatString =
                "This is the content for entry #{0}.\r\n\r\n" +
                "AAAAAAA BBBBBB AAAAA BBBBB AAAAA BBBBB AAAAA\r\n"+
                "AAAAAAA BBBBBB AAAAA BBBBB AAAAA BBBBB AAAAA\r\n";
            _txrx.Send(statusString);
            int dirCount= 0;
            using (var zip = new ZipFile())
            {
                _txrx.Send(String.Format("pb 1 max {0}", numTotalEntries));
                _txrx.Send("pb 1 value 0");

                zip.Password = password;
                zip.Encryption = encryption;
                zip.CompressionLevel = compression;
                zip.SaveProgress += saveProgress;
                zip.UseZip64WhenSaving = z64option;
                // save space when saving the file:
                zip.EmitTimesInWindowsFormatWhenSaving = false;
                zip.EmitTimesInUnixFormatWhenSaving = false;

                // add files:
                for (int m=0; m<numTotalEntries; m++)
                {
                    if (_rnd.Next(7)==0)
                    {
                        string entryName = String.Format("{0:D5}", m);
                        zip.AddDirectoryByName(entryName);
                        dirCount++;
                    }
                    else
                    {
                        string entryName = String.Format("{0:D5}.txt", m);
                        if (_rnd.Next(12)==0)
                        {
                            string contentBuffer = String.Format(contentFormatString, m);
                            byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer);
                            zip.AddEntry(entryName, contentBuffer);
                        }
                        else
                            zip.AddEntry(entryName, Stream.Null);
                    }

                    if (m % 1024 == 0)
                    {
                        _txrx.Send("pb 1 value " + m);
                        string msg = String.Format("status adding entry {0}/{1}  ({2:N0}%)",
                                            m, numTotalEntries, (m/(0.01*numTotalEntries)));
                        _txrx.Send(msg);
                    }
                }

                _txrx.Send("pb 0 step");
                _txrx.Send(statusString + " Saving...");
                zip.Save(zipFileToCreate);
            }

            _txrx.Send("pb 0 step");
            _txrx.Send("pb 1 value 0");
            _txrx.Send("status Reading...");

            // verify the zip by unpacking.
            _numFilesToExtract = numTotalEntries;
            _numExtracted= 1;
            _pb1Set = false;
            verb = "verify";
            BasicVerifyZip(zipFileToCreate, password, false, Zip64ExtractProgress);

            _txrx.Send("pb 0 step");
            _txrx.Send("status successful extract, now doing final count...");
            _txrx.Send("pb 1 value 0");
            Assert.AreEqual<int>(numTotalEntries-dirCount,
                                 TestUtilities.CountEntries(zipFileToCreate));
            _txrx.Send("pb 0 step");
        }
コード例 #12
0
ファイル: Streams.cs プロジェクト: mattleibow/Zip.Portable
        private void _Internal_ZOS_Create(string[] files,
                                                      EncryptionAlgorithm crypto,
                                                      bool seekable,
                                                      int cycle,
                                                      string format,
                                                      int fileOutputOption)
        {
            int BufferSize = 2048;

            for (int k = 0; k < compLevels.Length; k++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format(format, compLevels[k].ToString()));
                string password = Path.GetRandomFileName();

                TestContext.WriteLine("=================================");
                TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFileToCreate));
                TestContext.WriteLine("Encryption({0})  Compression({1})  pw({2})",
                                      crypto.ToString(), compLevels[k].ToString(), password);

                using (ZipOutputStream output = GetZipOutputStream(seekable, fileOutputOption, zipFileToCreate))
                {
                    if (crypto != EncryptionAlgorithm.None)
                    {
                        output.Password = password;
                        output.Encryption = crypto;
                    }
                    output.CompressionLevel = compLevels[k];

                    byte[] buffer = new byte[BufferSize];
                    int n;
                    foreach (var file in files)
                    {
                        TestContext.WriteLine("file: {0}", file);
                        output.PutNextEntry(file);
                        using (var input = File.OpenRead(file))
                        {
                            while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                output.Write(buffer, 0, n);
                            }
                        }
                    }
                }

                BasicVerifyZip(zipFileToCreate, password);

                Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate),
                                     "Trial ({0},{1}): The zip file created has the wrong number of entries.", cycle, k);
            }
        }
コード例 #13
0
ファイル: Streams.cs プロジェクト: mattleibow/Zip.Portable
        private void _ZOS_z64Over65534Entries
            (Zip64Option z64option,
             EncryptionAlgorithm encryption,
             Ionic.Zlib.CompressionLevel compression)
        {
            TestContext.WriteLine("_ZOS_z64Over65534Entries hello: {0}",
                                  DateTime.Now.ToString("G"));
            int fileCount = _rnd.Next(14616) + 65536;
            //int fileCount = _rnd.Next(146) + 5536;
            TestContext.WriteLine("entries: {0}", fileCount);
            var txrxLabel =
                String.Format("ZOS  #{0} 64({3}) E({1}) C({2})",
                              fileCount,
                              encryption.ToString(),
                              compression.ToString(),
                              z64option.ToString());

            TestContext.WriteLine("label: {0}", txrxLabel);
            string zipFileToCreate =
                String.Format("ZOS.Zip64.over65534.{0}.{1}.{2}.zip",
                              z64option.ToString(), encryption.ToString(),
                              compression.ToString());

            TestContext.WriteLine("zipFileToCreate: {0}", zipFileToCreate);

            _txrx = TestUtilities.StartProgressMonitor(zipFileToCreate,
                                                       txrxLabel, "starting up...");

            TestContext.WriteLine("generating {0} entries ", fileCount);
            _txrx.Send("pb 0 max 3"); // 2 stages: Write, Count, Verify
            _txrx.Send("pb 0 value 0");

            string password = Path.GetRandomFileName();

            string statusString = String.Format("status Encryption:{0} Compression:{1}",
                                                encryption.ToString(),
                                                compression.ToString());

            _txrx.Send(statusString);

            int dirCount = 0;

            using (FileStream fs = File.Create(zipFileToCreate))
            {
                using (var output = new ZipOutputStream(fs))
                {
                    _txrx.Send("test " + txrxLabel);
                    System.Threading.Thread.Sleep(400);
                    _txrx.Send("pb 1 max " + fileCount);
                    _txrx.Send("pb 1 value 0");

                    output.Password = password;
                    output.Encryption = encryption;
                    output.CompressionLevel = compression;
                    output.EnableZip64 = z64option;
                    for (int k = 0; k < fileCount; k++)
                    {
                        if (_rnd.Next(7) == 0)
                        {
                            // make it a directory
                            string entryName = String.Format("{0:D4}/", k);
                            output.PutNextEntry(entryName);
                            dirCount++;
                        }
                        else
                        {
                            string entryName = String.Format("{0:D4}.txt", k);
                            output.PutNextEntry(entryName);

                            // only a few entries are non-empty
                            if (_rnd.Next(18) == 0)
                            {
                                var block = TestUtilities.GenerateRandomAsciiString();
                                string content = String.Format("This is the content for entry #{0}.\n", k);
                                int n = _rnd.Next(4) + 1;
                                for (int j=0; j < n; j++)
                                    content+= block;

                                byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                                output.Write(buffer, 0, buffer.Length);
                            }
                        }
                        if (k % 1024 == 0)
                            _txrx.Send(String.Format("status saving ({0}/{1}) {2:N0}%",
                                                     k, fileCount,
                                                     ((double)k) / (0.01 * fileCount)));
                        else if (k % 256 == 0)
                            _txrx.Send("pb 1 value " + k);
                    }
                }
            }

            _txrx.Send("pb 1 max 1");
            _txrx.Send("pb 1 value 1");
            _txrx.Send("pb 0 step");

            System.Threading.Thread.Sleep(400);

            TestContext.WriteLine("Counting entries ... " + DateTime.Now.ToString("G"));
            _txrx.Send("status Counting entries...");
            Assert.AreEqual<int>
                (fileCount - dirCount,
                 TestUtilities.CountEntries(zipFileToCreate),
                 "{0}: The zip file created has the wrong number of entries.",
                 zipFileToCreate);
            _txrx.Send("pb 0 step");
            System.Threading.Thread.Sleep(140);

            // basic verify. The output is really large, so we pass emitOutput=false .
            _txrx.Send("status Verifying...");
            TestContext.WriteLine("Verifying ... " + DateTime.Now.ToString("G"));
            _numExtracted = 0;
            _numFilesToExtract = fileCount;
            _txrx.Send("pb 1 max " + fileCount);
            System.Threading.Thread.Sleep(200);
            _txrx.Send("pb 1 value 0");
            BasicVerifyZip(zipFileToCreate, password, false, Streams_ExtractProgress);
            _txrx.Send("pb 0 step");
            System.Threading.Thread.Sleep(800);
            TestContext.WriteLine("Done ... " + DateTime.Now.ToString("G"));
        }
コード例 #14
0
ファイル: Streams.cs プロジェクト: mattleibow/Zip.Portable
        private void _Internal_AddEntry_WriteDelegate(string[] files,
                                                      EncryptionAlgorithm crypto,
                                                      bool seekable,
                                                      int cycle,
                                                      string format,
                                                      int ignored)
        {
            int bufferSize = 2048;
            byte[] buffer = new byte[bufferSize];
            int n;

            for (int k = 0; k < compLevels.Length; k++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format(format, compLevels[k].ToString()));
                string password = TestUtilities.GenerateRandomPassword();

                using (var zip = new ZipFile())
                {
                    TestContext.WriteLine("=================================");
                    TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFileToCreate));
                    TestContext.WriteLine("Encryption({0})  Compression({1})  pw({2})",
                                          crypto.ToString(), compLevels[k].ToString(), password);

                    zip.Password = password;
                    zip.Encryption = crypto;
                    zip.CompressionLevel = compLevels[k];

                    foreach (var file in files)
                    {
                        zip.AddEntry(file, (name, output) =>
                            {
                                using (var input = File.OpenRead(name))
                                {
                                    while ((n = input.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        output.Write(buffer, 0, n);
                                    }
                                }
                            });
                    }


                    if (!seekable)
                    {
                        // conditionally use a non-seekable output stream
                        using (var raw = File.Create(zipFileToCreate))
                        {
                            using (var ns = new Ionic.Zip.Tests.NonSeekableOutputStream(raw))
                            {
                                zip.Save(ns);
                            }
                        }
                    }
                    else
                        zip.Save(zipFileToCreate);
                }

                BasicVerifyZip(Path.GetFileName(zipFileToCreate), password);

                Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate),
                                     "Trial ({0},{1}): The zip file created has the wrong number of entries.", cycle, k);
            }
        }
コード例 #15
0
        public static byte[] Encrypt(byte[] message, string recipientCert, EncryptionAlgorithm encryptionAlgorithm)
        {
            var cert         = new X509Certificate2(recipientCert);
            var contentInfo  = new ContentInfo(message);
            var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(new Oid(encryptionAlgorithm.ToString())));

            var recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);

            envelopedCms.Encrypt(recipient);

            var encoded = envelopedCms.Encode();

            return(encoded);
        }
コード例 #16
0
        public void EncryptDecryptRoundtrips(EncryptionAlgorithm algorithm)
        {
            // Use a 256-bit key which will be truncated based on the selected algorithm.
            byte[] k   = new byte[] { 0xe2, 0x7e, 0xd0, 0xc8, 0x45, 0x12, 0xbb, 0xd5, 0x5b, 0x6a, 0xf4, 0x34, 0xd2, 0x37, 0xc1, 0x1f, 0xeb, 0xa3, 0x11, 0x87, 0x0f, 0x80, 0xf2, 0xc2, 0xe3, 0x36, 0x42, 0x60, 0xf3, 0x1c, 0x82, 0xc8 };
            byte[] iv  = new byte[] { 0x89, 0xb8, 0xad, 0xbf, 0xb0, 0x73, 0x45, 0xe3, 0x59, 0x89, 0x32, 0xa0, 0x9c, 0x51, 0x74, 0x41 };
            byte[] aad = Encoding.UTF8.GetBytes("test");

            JsonWebKey key = new JsonWebKey(new[] { KeyOperation.Encrypt, KeyOperation.Decrypt })
            {
                K = k,
            };

            AesCryptographyProvider provider = new AesCryptographyProvider(key, null);

            byte[] plaintext = Encoding.UTF8.GetBytes("plaintext");

            if (algorithm.IsAesGcm())
            {
                iv = iv.Take(AesGcmProxy.NonceByteSize);
            }

            EncryptOptions encryptOptions = new EncryptOptions(algorithm, plaintext, iv, aad);
            EncryptResult  encrypted      = provider.Encrypt(encryptOptions, default);

#if !NETCOREAPP3_1
            if (algorithm.IsAesGcm())
            {
                Assert.IsNull(encrypted);
                Assert.Ignore($"AES-GCM is not supported on {RuntimeInformation.FrameworkDescription} on {RuntimeInformation.OSDescription}");
            }
#endif
            Assert.IsNotNull(encrypted);

            switch (algorithm.ToString())
            {
            // TODO: Move to new test to make sure CryptoClient and LocalCryptoClient initialize a null ICM for AES-CBC(PAD).
            case EncryptionAlgorithm.A128CbcValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0x63, 0x23, 0x21, 0xaf, 0x94, 0xf9, 0xe1, 0x21, 0xc2, 0xbd, 0xb1, 0x1b, 0x04, 0x89, 0x8c, 0x3a },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A192CbcValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0x95, 0x9d, 0x75, 0x91, 0x09, 0x8b, 0x70, 0x0b, 0x9c, 0xfe, 0xaf, 0xcd, 0x60, 0x1f, 0xaa, 0x79 },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A256CbcValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0xf4, 0xe8, 0x5a, 0xa4, 0xa8, 0xb3, 0xff, 0xc3, 0x85, 0x89, 0x17, 0x9a, 0x70, 0x09, 0x96, 0x7f },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A128CbcPadValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0xec, 0xb2, 0x63, 0x4c, 0xe0, 0x04, 0xe0, 0x31, 0x2d, 0x9a, 0x77, 0xb2, 0x11, 0xe5, 0x28, 0x7f },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A192CbcPadValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0xc3, 0x4e, 0x1b, 0xe7, 0x6e, 0xa1, 0xf1, 0xc3, 0x24, 0xae, 0x05, 0x1b, 0x0e, 0x32, 0xac, 0xb4 },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A256CbcPadValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0x4e, 0xbd, 0x78, 0xda, 0x90, 0x73, 0xc8, 0x97, 0x67, 0x2b, 0xa1, 0x0a, 0x41, 0x67, 0xf8, 0x99 },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A128GcmValue:
            case EncryptionAlgorithm.A192GcmValue:
            case EncryptionAlgorithm.A256GcmValue:
                Assert.IsNotNull(encrypted.Ciphertext);
                Assert.IsNotNull(encrypted.Iv);
                Assert.IsNotNull(encrypted.AuthenticationTag);
                CollectionAssert.AreEqual(aad, encrypted.AdditionalAuthenticatedData);
                break;
            }

            DecryptOptions decryptOptions = algorithm.IsAesGcm() ?
                                            new DecryptOptions(algorithm, encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag, encrypted.AdditionalAuthenticatedData) :
                                            new DecryptOptions(algorithm, encrypted.Ciphertext, encrypted.Iv);

            DecryptResult decrypted = provider.Decrypt(decryptOptions, default);
            Assert.IsNotNull(decrypted);

            // AES-CBC will be zero-padded.
            StringAssert.StartsWith("plaintext", Encoding.UTF8.GetString(decrypted.Plaintext));
        }
コード例 #17
0
        public async Task AesGcmEncryptDecrypt([EnumValues(
                                                    nameof(EncryptionAlgorithm.A128Gcm),
                                                    nameof(EncryptionAlgorithm.A192Gcm),
                                                    nameof(EncryptionAlgorithm.A256Gcm)
                                                    )] EncryptionAlgorithm algorithm)
        {
            int keySizeInBytes = algorithm.ToString() switch
            {
                EncryptionAlgorithm.A128GcmValue => 128 >> 3,
                EncryptionAlgorithm.A192GcmValue => 192 >> 3,
                EncryptionAlgorithm.A256GcmValue => 256 >> 3,

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            JsonWebKey jwk = KeyUtilities.CreateAesKey(keySizeInBytes, s_aesKeyOps);

            string      keyName = Recording.GenerateId();
            KeyVaultKey key     = await Client.ImportKeyAsync(
                new ImportKeyOptions(keyName, jwk));

            RegisterForCleanup(key.Name);

            CryptographyClient remoteClient = GetCryptoClient(key.Id, forceRemote: true);

            byte[] plaintext = new byte[32];
            Recording.Random.NextBytes(plaintext);

            byte[] iv = new byte[16];
            if (algorithm.GetAesCbcEncryptionAlgorithm() is AesCbc)
            {
                Recording.Random.NextBytes(iv);
            }

            EncryptParameters encryptParams = algorithm.ToString() switch
            {
                // TODO: Re-record with random additionalAuthenticatedData once the "aad" issue is fixed with Managed HSM.
                EncryptionAlgorithm.A128GcmValue => EncryptParameters.A128GcmParameters(plaintext),
                EncryptionAlgorithm.A192GcmValue => EncryptParameters.A192GcmParameters(plaintext),
                EncryptionAlgorithm.A256GcmValue => EncryptParameters.A256GcmParameters(plaintext),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            EncryptResult encrypted = await remoteClient.EncryptAsync(encryptParams);

            Assert.IsNotNull(encrypted.Ciphertext);

            DecryptParameters decryptParameters = algorithm.ToString() switch
            {
                // TODO: Re-record with random additionalAuthenticatedData once the "aad" issue is fixed with Managed HSM.
                EncryptionAlgorithm.A128GcmValue => DecryptParameters.A128GcmParameters(encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag),
                EncryptionAlgorithm.A192GcmValue => DecryptParameters.A192GcmParameters(encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag),
                EncryptionAlgorithm.A256GcmValue => DecryptParameters.A256GcmParameters(encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            DecryptResult decrypted = await remoteClient.DecryptAsync(decryptParameters);

            Assert.IsNotNull(decrypted.Plaintext);

            CollectionAssert.AreEqual(plaintext, decrypted.Plaintext);
        }
        public void CreateAuthenticatedEncryptor_RoundTripsData_ManagedImplementation(EncryptionAlgorithm encryptionAlgorithm, ValidationAlgorithm validationAlgorithm)
        {
            // Parse test input
            int keyLengthInBits = Int32.Parse(Regex.Match(encryptionAlgorithm.ToString(), @"^AES_(?<keyLength>\d{3})_CBC$").Groups["keyLength"].Value, CultureInfo.InvariantCulture);

            // Arrange
            var masterKey = Secret.Random(512 / 8);
            var control = new ManagedAuthenticatedEncryptor(
                keyDerivationKey: masterKey,
                symmetricAlgorithmFactory: () => new AesCryptoServiceProvider(),
                symmetricAlgorithmKeySizeInBytes: keyLengthInBits / 8,
                validationAlgorithmFactory: () => KeyedHashAlgorithm.Create(validationAlgorithm.ToString()));
            var test = CreateDescriptor(encryptionAlgorithm, validationAlgorithm, masterKey).CreateEncryptorInstance();

            // Act & assert - data round trips properly from control to test
            byte[] plaintext = new byte[] { 1, 2, 3, 4, 5 };
            byte[] aad = new byte[] { 2, 4, 6, 8, 0 };
            byte[] ciphertext = control.Encrypt(new ArraySegment<byte>(plaintext), new ArraySegment<byte>(aad));
            byte[] roundTripPlaintext = test.Decrypt(new ArraySegment<byte>(ciphertext), new ArraySegment<byte>(aad));
            Assert.Equal(plaintext, roundTripPlaintext);
        }
コード例 #19
0
ファイル: Cryptography.cs プロジェクト: mobytoby/beastmud
 /// <summary>
 /// Gets an instance of the SymmetricAlgorithm class for the specified algorithm.
 /// </summary>
 /// <param name="algorithm">The EncryptionAlgorithm value specifying the type of crypto service provider to create.</param>
 /// <returns>A SymmetricAlgorithm instance for the specified algorithm preset with the specified Key and IV.</returns>
 private static SymmetricAlgorithm GetCryptoServiceProvider(EncryptionAlgorithm algorithm)
 {
     SymmetricAlgorithm crypto = null;
     switch (algorithm)
     {
         case EncryptionAlgorithm.Des:
             crypto = new DESCryptoServiceProvider();
             break;
         case EncryptionAlgorithm.Rc2:
             crypto = new RC2CryptoServiceProvider();
             break;
         case EncryptionAlgorithm.Rijndael:
             crypto = new RijndaelManaged();
             break;
         case EncryptionAlgorithm.TripleDes:
             crypto = new TripleDESCryptoServiceProvider();
             break;
         default:
             throw new NotSupportedException(String.Concat("The EncryptionAlgorithm value specified '",
                 algorithm.ToString(), "' is not supported."));
     }
     return crypto;
 }