Ejemplo n.º 1
0
 public static string Decrypt(EncryptionAlgorithm algorithm, CiphertextFormat format, string data, Key key,
     byte[] salt, byte[] iv, PaddingMode paddingMode)
 {
     var _d = new byte[0];
     switch (format)
     {
         case CiphertextFormat.Base64:
         {
             _d = Convert.FromBase64String(data);
             break;
         }
         case CiphertextFormat.Hex:
         {
             _d = HexToByteArray(data);
             break;
         }
         case CiphertextFormat.Url:
         {
             var encoding = new UTF8Encoding();
             _d = encoding.GetBytes(HttpUtility.UrlDecode(data));
             break;
         }
     }
     return Decrypt(algorithm, _d, key, salt, iv, paddingMode);
 }
        public bool ShowDialog(Window owner, EncryptionAlgorithm value)
        {
            Owner = owner;

            AlgorithmBox.Focus();
            Keyboard.Focus(AlgorithmBox);

            AlgorithmBox.Items.Clear();
            foreach (var enumvalue in Enum.GetValues(typeof (EncryptionAlgorithm)))
            {
                AlgorithmBox.Items.Add(enumvalue);
            }

            AlgorithmBox.SelectedItem = value;

            if (ShowDialog() ?? false)
            {
                Algorithm = (EncryptionAlgorithm) AlgorithmBox.SelectedItem;
                return true;
            }
            else
            {
                Algorithm = EncryptionAlgorithm.Plain;
                return false;
            }
        }
 public static bool ValidateEncryptionAlgorithm(EncryptionAlgorithm value)
 {
     if ((value != EncryptionAlgorithm.None) && (value != EncryptionAlgorithm.Rc2))
     {
         return (value == EncryptionAlgorithm.Rc4);
     }
     return true;
 }
Ejemplo n.º 4
0
 public static bool ValidateEncryptionAlgorithm(EncryptionAlgorithm value)
 {
     //
     // note that EncryptionAlgorithm has disjoined values
     //
     return (value == EncryptionAlgorithm.None) ||
            (value == EncryptionAlgorithm.Rc2) ||
            (value == EncryptionAlgorithm.Rc4);
 }
Ejemplo n.º 5
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsRecipient"/> class.
		/// </summary>
		/// <remarks>
		/// The initial value of the <see cref="EncryptionAlgorithms"/> property will be set to
		/// the Triple-DES encryption algorithm, which should be safe to assume for all modern
		/// S/MIME v3.x client implementations.
		/// </remarks>
		/// <param name="certificate">The recipient's certificate.</param>
		/// <param name="recipientIdentifierType">The recipient identifier type.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="certificate"/> is <c>null</c>.
		/// </exception>
		public CmsRecipient (X509Certificate certificate, SubjectIdentifierType recipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber)
		{
			if (certificate == null)
				throw new ArgumentNullException (nameof (certificate));

			if (recipientIdentifierType == SubjectIdentifierType.IssuerAndSerialNumber)
				RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
			else
				RecipientIdentifierType = SubjectIdentifierType.SubjectKeyIdentifier;

			EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes };
			Certificate = certificate;
		}
		public virtual TlsCipher CreateCipher(TlsClientContext context,
			EncryptionAlgorithm encryptionAlgorithm, DigestAlgorithm digestAlgorithm)
		{
			switch (encryptionAlgorithm)
			{
				case EncryptionAlgorithm.cls_3DES_EDE_CBC:
					return CreateDesEdeCipher(context, 24, digestAlgorithm);
				case EncryptionAlgorithm.AES_128_CBC:
					return CreateAesCipher(context, 16, digestAlgorithm);
				case EncryptionAlgorithm.AES_256_CBC:
					return CreateAesCipher(context, 32, digestAlgorithm);
				default:
					throw new TlsFatalAlert(AlertDescription.internal_error);
			}
		}
Ejemplo n.º 7
0
 public static IEncryptionAlgorithm Create(EncryptionAlgorithm algoType)
 {
     IEncryptionAlgorithm encryptionInstance = null;
     switch (algoType) {
         case EncryptionAlgorithm.AES:
             encryptionInstance = new Encryption.AES();
             break;
         case EncryptionAlgorithm.Rijndael:
             encryptionInstance = new Encryption.Rijndael();
             break;
         default:
             throw new Exception("Incorrect use of EncryptionAlgoritm factory");
     }
     return encryptionInstance;
 }
Ejemplo n.º 8
0
        private PasspadDocument(EncryptionAlgorithm algo, SecureString pw, string content, string hint, string file)
        {
            fileAlgorithm = algo;
            Algorithm = algo;

            filePassword = pw;
            Password = pw;

            fileContent = content;
            Content = content;

            fileHint = hint;
            Hint = hint;

            File = file;
        }
Ejemplo n.º 9
0
        public static void SaveFile(string file, string text, string hint, SecureString password, EncryptionAlgorithm algorithm)
        {
            var data = AbstractEncryptionAlgorithm.GetAlgorithm(algorithm).Encode(text, password);
            var data64 = Convert.ToBase64String(data);

            StringBuilder result = new StringBuilder();

            result.AppendLine(string.Format("<hint>{0}</hint>", SecurityElement.Escape(hint)));
            result.AppendLine(string.Format("<encrypted algorithm=\"{0}\">", algorithm));
            for (int i = 0; i < Math.Ceiling(data64.Length / 64.0); i++)
            {
                result.AppendLine("    " + data64.Substring(i*64, Math.Min(64, data64.Length - i * 64)));
            }
            result.AppendLine("</encrypted>");

            File.WriteAllText(file, result.ToString(), Encoding.UTF8);
        }
Ejemplo n.º 10
0
        public static string ReadFile(XDocument xdoc, SecureString password, out EncryptionAlgorithm algorithm)
        {
            if (!Enum.TryParse(xdoc.Root?.Element("encrypted")?.Attribute("algorithm").Value ?? string.Empty, true, out algorithm))
            {
                algorithm = EncryptionAlgorithm.Plain;
                return null;
            }

            var data = (xdoc.Root?.Element("encrypted")?.Value ?? string.Empty)
                .Replace("\t", "")
                .Replace(" ", "")
                .Replace("\r", "")
                .Replace("\n", "")
                .Trim();

            var bdata = Convert.FromBase64String(data);

            return AbstractEncryptionAlgorithm.GetAlgorithm(algorithm).Decode(bdata, password);
        }
        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);
        }
        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);
        }
 /// <summary>
 /// �ṩ����ʵ�ֽ��ܵķ���
 /// </summary>
 /// <param name="algorithm"></param>
 /// <param name="bytesData">��Ҫ���ܵ���Ϣ</param>
 /// <returns></returns>
 public byte[] Decrypt(EncryptionAlgorithm algorithm, byte[] bytesData)
 {
     byte[] result = new byte[0];
     using (MemoryStream stream = new MemoryStream())
     {
         ICryptoTransform cryptoServiceProvider = GetDecryptoServiceProvider(algorithm);
         using (CryptoStream stream2 = new CryptoStream(stream, cryptoServiceProvider, CryptoStreamMode.Write))
         {
             try
             {
                 stream2.Write(bytesData, 0, bytesData.Length);
                 stream2.FlushFinalBlock();
                 stream2.Close();
                 result = stream.ToArray();
             }
             catch (Exception exception)
             {
                 throw new Exception("Error while writing decrypted data to the stream: \n" + exception.Message);
             }
         }
         stream.Close();
     }
     return result;
 }
 public static AbstractEncryptionAlgorithm GetAlgorithm(EncryptionAlgorithm algo)
 {
     switch (algo)
     {
         case EncryptionAlgorithm.Plain:
             return new AlgorithmPlain();
         case EncryptionAlgorithm.Blowfish:
             return new AlgorithmBlowfish();
         case EncryptionAlgorithm.Twofish:
             return new AlgorithmTwofish();
         case EncryptionAlgorithm.AES:
             return new AlgorithmAES();
         case EncryptionAlgorithm.TripleDES:
             return new AlgorithmTripleDES();
         case EncryptionAlgorithm.CAST:
             return new AlgorithmCAST();
         case EncryptionAlgorithm.XOR:
             return new AlgorithmXOR();
         case EncryptionAlgorithm.DES:
             return new AlgorithmDES();
         default:
             throw new NotImplementedException();
     }
 }
Ejemplo n.º 15
0
 public override void IsSupportedKeyWrapping_Success(Jwk key, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
 {
     base.IsSupportedKeyWrapping_Success(key, enc, alg);
 }
        /// <summary>
        /// Creates a new <see cref="MultipartEncrypted"/>.
        /// </summary>
        /// <remarks>
        /// Signs the entity using the supplied signer and digest algorithm and then encrypts to
        /// the specified recipients, encapsulating the result in a new multipart/encrypted part.
        /// </remarks>
        /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing
        /// the signed and encrypted version of the specified entity.</returns>
        /// <param name="signer">The signer to use to sign the entity.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="cipherAlgo">The encryption algorithm.</param>
        /// <param name="recipients">The recipients for the encrypted entity.</param>
        /// <param name="entity">The entity to sign and encrypt.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="recipients"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="entity"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// <para><paramref name="signer"/> cannot be used for signing.</para>
        /// <para>-or-</para>
        /// <para>One or more of the recipient keys cannot be used for encrypting.</para>
        /// <para>-or-</para>
        /// <para>No recipients were specified.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// The <paramref name="digestAlgo"/> was out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// <para>A default <see cref="OpenPgpContext"/> has not been registered.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="digestAlgo"/> is not supported.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="cipherAlgo"/> is not supported.</para>
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The user chose to cancel the password prompt.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">
        /// 3 bad attempts were made to unlock the secret key.
        /// </exception>
        public static MultipartEncrypted Create(PgpSecretKey signer, DigestAlgorithm digestAlgo, EncryptionAlgorithm cipherAlgo, IEnumerable <PgpPublicKey> recipients, MimeEntity entity)
        {
            if (signer == null)
            {
                throw new ArgumentNullException("signer");
            }

            if (recipients == null)
            {
                throw new ArgumentNullException("recipients");
            }

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            using (var ctx = (OpenPgpContext)CryptographyContext.Create("application/pgp-encrypted")) {
                return(Create(ctx, signer, digestAlgo, cipherAlgo, recipients, entity));
            }
        }
Ejemplo n.º 17
0
 public override AuthenticatedEncryptor CreateAuthenticatedEncryptor_Succeed(Jwk key, EncryptionAlgorithm enc)
 {
     return(base.CreateAuthenticatedEncryptor_Succeed(key, enc));
 }
Ejemplo n.º 18
0
 public override void IsSupportedKeyWrapping_Success(Jwk key, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
 {
     Assert.True(key.SupportKeyManagement(alg));
     Assert.False(key.SupportEncryption(enc));
 }
Ejemplo n.º 19
0
        private void CreateTestFile(CompressionAlgorithm[] compressionAlgorithms, bool enableEncryption, out uint treeId, out FILEID fileId, bool enableChainedCompression = false)
        {
            var capabilities = Capabilities_Values.NONE;

            if (enableEncryption)
            {
                capabilities |= Capabilities_Values.GLOBAL_CAP_ENCRYPTION;
            }
            EncryptionAlgorithm[] encryptionAlgorithms = null;
            if (enableEncryption)
            {
                encryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.ENCRYPTION_AES128_CCM, EncryptionAlgorithm.ENCRYPTION_AES128_GCM };
            }

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Starts a client by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT.");
            client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
            client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
            client.NegotiateWithContexts(
                Packet_Header_Flags_Values.NONE,
                TestConfig.RequestDialects,
                preauthHashAlgs: new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 },
                encryptionAlgs: encryptionAlgorithms,
                compressionAlgorithms: compressionAlgorithms,
                compressionFlags: enableChainedCompression ? SMB2_COMPRESSION_CAPABILITIES_Flags.SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED : SMB2_COMPRESSION_CAPABILITIES_Flags.SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE,
                capabilityValue: capabilities,
                checker: (Packet_Header header, NEGOTIATE_Response response) =>
            {
                BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, header.Status, "SUT MUST return STATUS_SUCCESS if the negotiation finished successfully.");

                if (TestConfig.IsWindowsPlatform)
                {
                    CheckCompressionAlgorithmsForWindowsImplementation(compressionAlgorithms);
                }
                else
                {
                    bool isExpectedNonWindowsCompressionContext = Enumerable.SequenceEqual(client.Smb2Client.CompressionInfo.CompressionIds, compressionAlgorithms);
                    {
                        BaseTestSite.Assert.IsTrue(isExpectedNonWindowsCompressionContext, "[MS-SMB2] section 3.3.5.4: Non-Windows implementation MUST set CompressionAlgorithms to the CompressionIds in request if they are all supported by SUT.");
                    }
                }
            });


            client.SessionSetup(
                TestConfig.DefaultSecurityPackage,
                TestConfig.SutComputerName,
                TestConfig.AccountCredential,
                TestConfig.UseServerGssToken);

            if (enableEncryption)
            {
                client.EnableSessionSigningAndEncryption(enableSigning: false, enableEncryption: true);
            }
            client.TreeConnect(uncSharePath, out treeId);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client sends CREATE request with desired access set to GENERIC_READ and GENERIC_WRITE to create a file.");
            Smb2CreateContextResponse[] serverCreateContexts;

            string fileName = GetTestFileName(uncSharePath);

            client.Create(
                treeId,
                fileName,
                CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
                out fileId,
                out serverCreateContexts,
                accessMask: AccessMask.GENERIC_READ | AccessMask.GENERIC_WRITE
                );
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageHelper"/> class.
 /// </summary>
 public PackageHelper()
 {
     Encryption = EncryptionAlgorithm.PkzipWeak;
 }
Ejemplo n.º 21
0
 public override void IsSupportedEncryption_Success(Jwk key, EncryptionAlgorithm enc)
 {
     base.IsSupportedEncryption_Success(key, enc);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EncryptionAgent"/> class.
 /// </summary>
 /// <param name="protocol">The protocol.</param>
 /// <param name="algorithm">The algorithm.</param>
 public EncryptionAgent(string protocol, EncryptionAlgorithm algorithm)
 {
     this.Protocol            = protocol;
     this.EncryptionAlgorithm = algorithm;
 }
        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);
        }
        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);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="encryptedText"></param>
        /// <param name="keyValue"></param>
        /// <param name="intVector"></param>
        /// <param name="algoType"></param>
        /// <returns>
        /// Returns the decrypted value to the parameterized encrypt text.
        /// </returns>
        public static string Decrypt(string encryptedText, string keyValue, string intVector, EncryptionAlgorithm algoType)
        {
            EncryptionAlgorithm algorithm = algoType;

            //  Init variables.
            //
            byte[] IV         = null;
            byte[] cipherText = null;
            byte[] key        = null;

            try
            {
                //  3Des only work with a 16 or 24 byte key.
                //
                key = Encoding.ASCII.GetBytes(keyValue);
                //
                //  Must be 16 bytes for Rijndael.
                //
                IV = Encoding.ASCII.GetBytes(intVector);

                //  Try to decrypt.
                //  Set up your decryption, give it the algorithm and initialization vector.
                //
                Decryptor dec = new Decryptor(algorithm);

                cipherText = Convert.FromBase64String(encryptedText);
                //
                //  Go ahead and decrypt.
                //
                byte[] plainText = dec.Decrypt(cipherText, key, IV);
                //
                //  Look at your plain text.
                //
                return(Encoding.ASCII.GetString(plainText));
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AesCbcHmacEncryptor"/> class.
 /// </summary>
 /// <param name="encryptionAlgorithm"></param>
 public AesCbcHmacEncryptor(EncryptionAlgorithm encryptionAlgorithm)
     : this(encryptionAlgorithm, new AesCbcEncryptor(encryptionAlgorithm))
 {
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Starts an explicit encryption context.
        /// </summary>
        /// <param name="keyAltName">The alternative key name.</param>
        /// <param name="encryptionAlgorithm">The algorithm.</param>
        /// <param name="message">The BSON message.</param>
        /// <returns>A encryption context. </returns>
        public CryptContext StartExplicitEncryptionContextWithKeyAltName(byte[] keyAltName, EncryptionAlgorithm encryptionAlgorithm, byte[] message)
        {
            ContextSafeHandle handle = Library.mongocrypt_ctx_new(_handle);

            unsafe
            {
                fixed(byte *p = keyAltName)
                {
                    IntPtr ptr = (IntPtr)p;

                    using (PinnedBinary pinned = new PinnedBinary(ptr, (uint)keyAltName.Length))
                    {
                        handle.Check(_status, Library.mongocrypt_ctx_setopt_key_alt_name(handle, pinned.Handle));
                    }
                }
            }

            handle.Check(_status, Library.mongocrypt_ctx_setopt_algorithm(handle, Helpers.EncryptionAlgorithmToString(encryptionAlgorithm), -1));

            unsafe
            {
                fixed(byte *p = message)
                {
                    IntPtr ptr = (IntPtr)p;

                    using (PinnedBinary pinned = new PinnedBinary(ptr, (uint)message.Length))
                    {
                        handle.Check(_status, Library.mongocrypt_ctx_explicit_encrypt_init(handle, pinned.Handle));
                    }
                }
            }

            return(new CryptContext(handle));
        }
Ejemplo n.º 28
0
        static void ValidateEncryption(EncryptionAlgorithm encryptionAlgorithm, string fileName, uint unsupportedAlgorithmId)
        {
            if (encryptionAlgorithm != EncryptionAlgorithm.PkzipWeak &&
#if AESCRYPTO
                encryptionAlgorithm != EncryptionAlgorithm.WinZipAes128 &&
                encryptionAlgorithm != EncryptionAlgorithm.WinZipAes256 &&
#endif
                encryptionAlgorithm != EncryptionAlgorithm.None)
            {
                // workitem 7968
                if (unsupportedAlgorithmId != 0)
                    throw new ZipException(string.Format("Cannot extract: Entry {0} is encrypted with an algorithm not supported by DotNetZip: {1}",
                                                         fileName, GetUnsupportedAlgorithm(unsupportedAlgorithmId)));
                throw new ZipException(string.Format("Cannot extract: Entry {0} uses an unsupported encryption algorithm ({1:X2})",
                                                     fileName, (int)encryptionAlgorithm));
            }
        }
Ejemplo n.º 29
0
        internal void VerifyCrcAfterExtract(Int32 calculatedCrc32, EncryptionAlgorithm encryptionAlgorithm, int expectedCrc32, Stream archiveStream, long uncompressedSize)
        {
#if AESCRYPTO
                // After extracting, Validate the CRC32
                if (calculatedCrc32 != expectedCrc32)
                {
                    // CRC is not meaningful with WinZipAES and AES method 2 (AE-2)
                    if ((encryptionAlgorithm != EncryptionAlgorithm.WinZipAes128 &&
                         encryptionAlgorithm != EncryptionAlgorithm.WinZipAes256)
                        || _WinZipAesMethod != 0x02)
                        throw new BadCrcException("CRC error: the file being extracted appears to be corrupted. " +
                                                  String.Format("Expected 0x{0:X8}, Actual 0x{1:X8}", expectedCrc32, calculatedCrc32));
                }

                // ignore MAC if the size of the file is zero
                if (uncompressedSize == 0)
                    return;

                // calculate the MAC
                if (encryptionAlgorithm == EncryptionAlgorithm.WinZipAes128 ||
                    encryptionAlgorithm == EncryptionAlgorithm.WinZipAes256)
                {
                    var wzs = _inputDecryptorStream as WinZipAesCipherStream;
                    _aesCrypto_forExtract.CalculatedMac = wzs.FinalAuthentication;

                    _aesCrypto_forExtract.ReadAndVerifyMac(archiveStream); // throws if MAC is bad
                    // side effect: advances file position.
                }

#else
            if (calculatedCrc32 != expectedCrc32)
                throw new BadCrcException("CRC error: the file being extracted appears to be corrupted. " +
                                          String.Format("Expected 0x{0:X8}, Actual 0x{1:X8}", expectedCrc32, calculatedCrc32));
#endif
        }
Ejemplo n.º 30
0
 internal DecryptTransformer(EncryptionAlgorithm deCryptId)
 {
     this.algorithmId = deCryptId;
 }
        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, false);

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

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

            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;
            }

            DecryptParameters decryptOptions = new DecryptParameters(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));
        }
Ejemplo n.º 32
0
        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"));
        }
        public void TryWrapKey_WithoutStaticKey_Success(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            Jwk cek = TryWrapKey_Success(null, enc, alg);

            Assert.NotNull(cek);
        }
Ejemplo n.º 34
0
        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);
            }
        }
Ejemplo n.º 35
0
 public override KeyWrapper CreateKeyWrapper_Succeed(Jwk key, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
 {
     return(base.CreateKeyWrapper_Succeed(key, enc, alg));
 }
        /// <summary>
        /// This method will send ComNegotiate request before sending a Negotiate request to simulate windows client behaviour.
        /// If ComNegotiate failed, the Negotiate request will still be sent.      
        /// </summary>
        public uint MultiProtocolNegotiate(
            Smb2Client client,
            ushort creditCharge,
            ushort creditRequest,
            Packet_Header_Flags_Values flags,
            ulong messageId,
            DialectRevision[] dialects,
            SecurityMode_Values securityMode,
            Capabilities_Values capabilities,
            Guid clientGuid,
            out DialectRevision selectedDialect,
            out byte[] gssToken,
            out Packet_Header responseHeader,
            out NEGOTIATE_Response responsePayload)
        {
            uint status = client.MultiProtocolNegotiate(
                    new string[] { "SMB 2.002", "SMB 2.???" },
                    out selectedDialect,
                    out gssToken,
                    out responseHeader,
                    out responsePayload);

            if (responseHeader.Status != Smb2Status.STATUS_SUCCESS)
            {
                LogFailedStatus("ComNegotiate", responseHeader.Status);
            }

            // If server only supports Smb2002, no further SMB2 negotiate needed
            if (selectedDialect == DialectRevision.Smb2002)
            {
                return status;
            }

            PreauthIntegrityHashID[] preauthHashAlgs = null;
            EncryptionAlgorithm[] encryptionAlgs = null;

            // For back compatibility, if dialects contains SMB 3.11, preauthentication integrity context should be present.
            if (Array.IndexOf(dialects, DialectRevision.Smb311) >= 0)
            {
                preauthHashAlgs = new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 };
                encryptionAlgs = new EncryptionAlgorithm[] {
                EncryptionAlgorithm.ENCRYPTION_AES128_GCM,
                EncryptionAlgorithm.ENCRYPTION_AES128_CCM };
            }

            status = client.Negotiate(
                creditCharge,
                creditRequest,
                flags,
                messageId,
                dialects,
                securityMode,
                capabilities,
                clientGuid,
                out selectedDialect,
                out gssToken,
                out responseHeader,
                out responsePayload,
                0,
                preauthHashAlgs,
                encryptionAlgs);

            return status;
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="encryptionAlgorithm">Algorithm used to encrypt the package. Default is AES128</param>
 internal ExcelEncryption(EncryptionAlgorithm encryptionAlgorithm)
 {
     Algorithm = encryptionAlgorithm;
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Set the password and algorithm used by the Berkeley DB library to
 /// perform encryption and decryption.
 /// </summary>
 /// <param name="password">
 /// The password used to perform encryption and decryption.
 /// </param>
 /// <param name="alg">
 /// The algorithm used to perform encryption and decryption.
 /// </param>
 public void SetEncryption(String password, EncryptionAlgorithm alg)
 {
     encryptionIsSet = true;
     encryptPwd      = password;
     encryptAlg      = alg;
 }
 /// <summary>
 /// Set the password and algorithm used by the Berkeley DB library to
 /// perform encryption and decryption. 
 /// </summary>
 /// <param name="password">
 /// The password used to perform encryption and decryption.
 /// </param>
 /// <param name="alg">
 /// The algorithm used to perform encryption and decryption.
 /// </param>
 public void SetEncryption(String password, EncryptionAlgorithm alg)
 {
     encryptionIsSet = true;
     encryptPwd = password;
     encryptAlg = alg;
 }
        /// <summary>
        /// Creates a new <see cref="MultipartEncrypted"/>.
        /// </summary>
        /// <remarks>
        /// Signs the entity using the supplied signer and digest algorithm and then encrypts to
        /// the specified recipients, encapsulating the result in a new multipart/encrypted part.
        /// </remarks>
        /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing
        /// the signed and encrypted version of the specified entity.</returns>
        /// <param name="ctx">The OpenPGP cryptography context to use for singing and encrypting.</param>
        /// <param name="signer">The signer to use to sign the entity.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="cipherAlgo">The encryption algorithm.</param>
        /// <param name="recipients">The recipients for the encrypted entity.</param>
        /// <param name="entity">The entity to sign and encrypt.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="ctx"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="recipients"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="entity"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// <para><paramref name="signer"/> cannot be used for signing.</para>
        /// <para>-or-</para>
        /// <para>One or more of the recipient keys cannot be used for encrypting.</para>
        /// <para>-or-</para>
        /// <para>No recipients were specified.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// The <paramref name="digestAlgo"/> was out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// <para>The <paramref name="digestAlgo"/> is not supported.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="cipherAlgo"/> is not supported.</para>
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The user chose to cancel the password prompt.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">
        /// 3 bad attempts were made to unlock the secret key.
        /// </exception>
        public static MultipartEncrypted Create(OpenPgpContext ctx, PgpSecretKey signer, DigestAlgorithm digestAlgo, EncryptionAlgorithm cipherAlgo, IEnumerable <PgpPublicKey> recipients, MimeEntity entity)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            if (signer == null)
            {
                throw new ArgumentNullException("signer");
            }

            if (recipients == null)
            {
                throw new ArgumentNullException("recipients");
            }

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            using (var memory = new MemoryBlockStream()) {
                var options = FormatOptions.GetDefault();
                options.NewLineFormat = NewLineFormat.Dos;

                entity.WriteTo(options, memory);
                memory.Position = 0;

                var encrypted = new MultipartEncrypted();
                encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol;

                // add the protocol version part
                encrypted.Add(new ApplicationPgpEncrypted());

                // add the encrypted entity as the second part
                encrypted.Add(ctx.SignAndEncrypt(signer, digestAlgo, cipherAlgo, recipients, memory));

                return(encrypted);
            }
        }
Ejemplo n.º 41
0
 void RadioButton4_CheckedChanged(object sender, EventArgs e)
 {
     if (RadioButton1.Checked) {
         MahEncType = EncryptionAlgorithm.None;
     } else if (RadioButton2.Checked) {
         MahEncType = EncryptionAlgorithm.PkzipWeak;
     } else if (RadioButton3.Checked) {
         MahEncType = EncryptionAlgorithm.WinZipAes128;
     } else if (RadioButton4.Checked) {
         MahEncType = EncryptionAlgorithm.WinZipAes256;
     } else {
         MessageBox.Show("Error: Invalid Encryption Type!");
     }
 }
 private static int GetKeyStrengthInBits(EncryptionAlgorithm a)
 {
     if (a == EncryptionAlgorithm.WinZipAes256) return 256;
     else if (a == EncryptionAlgorithm.WinZipAes128) return 128;
     return -1;
 }
Ejemplo n.º 43
0
 public DirectKeyUnwrapper(Jwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
     : base(key, encryptionAlgorithm, algorithm)
 {
 }
Ejemplo n.º 44
0
        private void FetchSmb2EncryptionInfo(Smb2Info smb2Info)
        {
            EncryptionAlgorithm[] excludedEncryptionAlogrithms;
            if (smb2Info.MaxSupportedDialectRevision < DialectRevision.Smb311)
            {
                excludedEncryptionAlogrithms = new EncryptionAlgorithm[]
                {
                    EncryptionAlgorithm.ENCRYPTION_NONE,
                    EncryptionAlgorithm.ENCRYPTION_INVALID,
                    EncryptionAlgorithm.ENCRYPTION_AES256_CCM,
                    EncryptionAlgorithm.ENCRYPTION_AES256_GCM
                };
            }
            else
            {
                excludedEncryptionAlogrithms = new EncryptionAlgorithm[]
                {
                    EncryptionAlgorithm.ENCRYPTION_NONE,
                    EncryptionAlgorithm.ENCRYPTION_INVALID
                };
            }

            var possibleEncryptionAlogrithms = Enum.GetValues(typeof(EncryptionAlgorithm)).Cast <EncryptionAlgorithm>().Except(excludedEncryptionAlogrithms);

            logWriter.AddLog(DetectLogLevel.Information, $"Available EncryptionAlgorithms ==> {String.Join(";", possibleEncryptionAlogrithms.Select(encryptionAlgorithm => encryptionAlgorithm.ToString()))}");

            // Iterate all the possible encryption algorithms since we get back only one encryption algorithm in response.
            var result = possibleEncryptionAlogrithms.Where(encryptionAlgorithm =>
            {
                using (var client = new Smb2Client(new TimeSpan(0, 0, defaultTimeoutInSeconds)))
                {
                    client.ConnectOverTCP(SUTIpAddress);

                    DialectRevision selectedDialect;
                    byte[] gssToken;
                    Packet_Header responseHeader;
                    NEGOTIATE_Response responsePayload;

                    uint status = client.Negotiate(
                        0,
                        1,
                        Packet_Header_Flags_Values.NONE,
                        0,
                        new DialectRevision[] { DialectRevision.Smb311 },
                        SecurityMode_Values.NEGOTIATE_SIGNING_ENABLED,
                        Capabilities_Values.NONE,
                        Guid.NewGuid(),
                        out selectedDialect,
                        out gssToken,
                        out responseHeader,
                        out responsePayload,
                        preauthHashAlgs: new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 },
                        encryptionAlgs: new EncryptionAlgorithm[] { encryptionAlgorithm }
                        );

                    if (status == Smb2Status.STATUS_SUCCESS && client.SelectedCipherID == encryptionAlgorithm)
                    {
                        logWriter.AddLog(DetectLogLevel.Information, $"Encryption algorithm: {encryptionAlgorithm} is supported by SUT.");
                        return(true);
                    }
                    else
                    {
                        logWriter.AddLog(DetectLogLevel.Information, $"Encryption algorithm: {encryptionAlgorithm} is not supported by SUT.");
                        return(false);
                    }
                }
            });

            smb2Info.SutSupportedEncryptionAlgorithms = result.ToArray();
        }
Ejemplo n.º 45
0
 private void _Internal_ZOS_Create(string[] files,
                                               EncryptionAlgorithm crypto,
                                               bool seekable,
                                               int cycle,
                                               string format)
 {
     _Internal_ZOS_Create(files, crypto, seekable, cycle, format, 0);
 }
Ejemplo n.º 46
0
 internal EncryptTransformer(EncryptionAlgorithm algId)
 {
     //Save the algorithm being used.
     algorithmID = algId;
 }
Ejemplo n.º 47
0
		/// <summary>
		/// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate.
		/// </summary>
		/// <param name="certificate">The certificate.</param>
		/// <param name="algorithms">The encryption algorithm capabilities of the client (in preferred order).</param>
		/// <param name="timestamp">The timestamp.</param>
		protected override void UpdateSecureMimeCapabilities (X509Certificate certificate, EncryptionAlgorithm[] algorithms, DateTime timestamp)
		{
			capabilities[certificate] = algorithms;
		}
Ejemplo n.º 48
0
 public Decryptor(EncryptionAlgorithm algId)
 {
     transformer = new DecryptTransformer(algId);
 }
Ejemplo n.º 49
0
 internal DecryptTransformer(EncryptionAlgorithm decryptId)
 {
     this.algorithmID = decryptId;
 }
 public AesGcmKeyUnwrapper(SymmetricJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
     : base(key, encryptionAlgorithm, algorithm)
 {
     ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
 }
Ejemplo n.º 51
0
        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");
        }
        /// <summary>
        /// This method will send ComNegotiate request before sending a Negotiate request to simulate windows client behaviour.
        /// If ComNegotiate failed, the Negotiate request will still be sent.
        /// </summary>
        public uint MultiProtocolNegotiate(
            Smb2Client client,
            ushort creditCharge,
            ushort creditRequest,
            Packet_Header_Flags_Values flags,
            ulong messageId,
            DialectRevision[] dialects,
            SecurityMode_Values securityMode,
            Capabilities_Values capabilities,
            Guid clientGuid,
            out DialectRevision selectedDialect,
            out byte[] gssToken,
            out Packet_Header responseHeader,
            out NEGOTIATE_Response responsePayload)
        {
            uint status = client.MultiProtocolNegotiate(
                new string[] { "SMB 2.002", "SMB 2.???" },
                out selectedDialect,
                out gssToken,
                out responseHeader,
                out responsePayload);

            if (responseHeader.Status != Smb2Status.STATUS_SUCCESS)
            {
                LogFailedStatus("ComNegotiate", responseHeader.Status);
            }

            // If server only supports Smb2002, no further SMB2 negotiate needed
            if (selectedDialect == DialectRevision.Smb2002)
            {
                return(status);
            }

            PreauthIntegrityHashID[] preauthHashAlgs = null;
            EncryptionAlgorithm[]    encryptionAlgs  = null;

            // For back compatibility, if dialects contains SMB 3.11, preauthentication integrity context should be present.
            if (Array.IndexOf(dialects, DialectRevision.Smb311) >= 0)
            {
                preauthHashAlgs = new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 };
                encryptionAlgs  = new EncryptionAlgorithm[] {
                    EncryptionAlgorithm.ENCRYPTION_AES128_GCM,
                    EncryptionAlgorithm.ENCRYPTION_AES128_CCM
                };
            }

            status = client.Negotiate(
                creditCharge,
                creditRequest,
                flags,
                messageId,
                dialects,
                securityMode,
                capabilities,
                clientGuid,
                out selectedDialect,
                out gssToken,
                out responseHeader,
                out responsePayload,
                0,
                preauthHashAlgs,
                encryptionAlgs);

            return(status);
        }
Ejemplo n.º 53
0
 public Decryptor(EncryptionAlgorithm algId)
 {
     transformer = new DecryptTransformer(algId);
 }
Ejemplo n.º 54
0
 internal DecryptTransformer(EncryptionAlgorithm deCryptId)
 {
     algorithmID = deCryptId;
 }
        internal static int GetLengthOfCryptoHeaderBytes(EncryptionAlgorithm a)
        {
            //if ((_BitField & 0x01) != 0x01) return 0;
            if (a == EncryptionAlgorithm.None) return 0;

#if AESCRYPTO
            if (a == EncryptionAlgorithm.WinZipAes128 ||
                a == EncryptionAlgorithm.WinZipAes256)
            {
                int KeyStrengthInBits = GetKeyStrengthInBits(a);
                int sizeOfSaltAndPv = ((KeyStrengthInBits / 8 / 2) + 2);
                return sizeOfSaltAndPv;
            }
#endif
            if (a == EncryptionAlgorithm.PkzipWeak)
                return 12;
            throw new ZipException("internal error");
        }
Ejemplo n.º 56
0
 /// <summary>
 /// Enable the encryption algorithm.
 /// </summary>
 /// <remarks>
 /// Enables the encryption algorithm.
 /// </remarks>
 /// <param name="algorithm">The encryption algorithm.</param>
 public void Enable(EncryptionAlgorithm algorithm)
 {
     enabledEncryptionAlgorithms |= 1 << (int)algorithm;
 }
Ejemplo n.º 57
0
        bool ExtractToStream(Stream archiveStream, Stream output, EncryptionAlgorithm encryptionAlgorithm, int expectedCrc32)
        {
            if (_ioOperationCanceled)
                return true;

            try
            {
                var calculatedCrc32 = ExtractAndCrc(archiveStream, output,
                    _CompressionMethod_FromZipFile, _CompressedFileDataSize,
                    UncompressedSize);

                if (_ioOperationCanceled)
                    return true;

                VerifyCrcAfterExtract(calculatedCrc32, encryptionAlgorithm, expectedCrc32, archiveStream, UncompressedSize);
                return false;
            }
            finally
            {
                var zss = archiveStream as ZipSegmentedStream;
                if (zss != null)
                {
#if NETCF
                    zss.Close();
#else
                    // need to dispose it
                    zss.Dispose();
#endif
                    _archiveStream = null;
                }
            }
        }
Ejemplo n.º 58
0
 /// <summary>
 /// Disable the encryption algorithm.
 /// </summary>
 /// <remarks>
 /// Disables the encryption algorithm.
 /// </remarks>
 /// <param name="algorithm">The encryption algorithm.</param>
 public void Disable(EncryptionAlgorithm algorithm)
 {
     enabledEncryptionAlgorithms &= ~(1 << (int)algorithm);
 }
Ejemplo n.º 59
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="encryptionAlgorithm">Algorithm used to encrypt the package. Default is AES128</param>
 internal ExcelEncryption(EncryptionAlgorithm encryptionAlgorithm)
 {
     Algorithm = encryptionAlgorithm;
 }        
Ejemplo n.º 60
0
 /// <summary>
 /// Check whether the specified encryption algorithm is enabled.
 /// </summary>
 /// <remarks>
 /// Determines whether the specified encryption algorithm is enabled.
 /// </remarks>
 /// <returns><c>true</c> if the specified encryption algorithm is enabled; otherwise, <c>false</c>.</returns>
 /// <param name="algorithm">The encryption algorithm.</param>
 public bool IsEnabled(EncryptionAlgorithm algorithm)
 {
     return((enabledEncryptionAlgorithms & (1 << (int)algorithm)) != 0);
 }