public async Task TestAddingSingleV2AsymmetricKeyWrap()
        {
            EncryptionParameters encryptionParameters = new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("allan"));
            IAsymmetricPublicKey publicKey            = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey1);
            await encryptionParameters.AddAsync(new UserPublicKey[] { new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey), });

            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(encryptionParameters, 1000);
            IEnumerable <V2AsymmetricKeyWrapHeaderBlock> wraps = documentHeaders.Headers.HeaderBlocks.OfType <V2AsymmetricKeyWrapHeaderBlock>();

            Assert.That(wraps.Count(), Is.EqualTo(1), "There should be one V2AsymmetricKeyWrapHeaderBlock found.");

            V2AsymmetricKeyWrapHeaderBlock block1 = wraps.First();

            ICryptoFactory cryptoFactory = Resolve.CryptoFactory.Create(encryptionParameters.CryptoId);

            IAsymmetricPrivateKey privateKey1 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey1);

            block1.SetPrivateKey(cryptoFactory, privateKey1);
            ICrypto cryptoFromAsymmetricKey = block1.Crypto(0);

            V2KeyWrapHeaderBlock symmetricKeyWrap = documentHeaders.Headers.HeaderBlocks.OfType <V2KeyWrapHeaderBlock>().First();
            ICrypto cryptoFromSymmetricKey        = cryptoFactory.CreateCrypto(symmetricKeyWrap.MasterKey, symmetricKeyWrap.MasterIV, 0);

            Assert.That(cryptoFromAsymmetricKey.Key, Is.EqualTo(cryptoFromSymmetricKey.Key), "The keys from Asymmetric and Symmetric should be equal.");

            IAsymmetricPrivateKey privateKey2 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey2);

            block1.SetPrivateKey(cryptoFactory, privateKey2);
            ICrypto cryptoFromAsymmetricKey1WithKey2 = block1.Crypto(0);

            Assert.That(cryptoFromAsymmetricKey1WithKey2, Is.Null, "There should be no valid key set and thus no ICrypto instance returned.");
        }
        public static async Task ChangeKeySharingAsync(this IEnumerable <string> files, IEnumerable <UserPublicKey> publicKeys)
        {
            EncryptionParameters encryptionParameters = new EncryptionParameters(Resolve.CryptoFactory.Default(New <ICryptoPolicy>()).CryptoId, New <KnownIdentities>().DefaultEncryptionIdentity);
            await encryptionParameters.AddAsync(await publicKeys.GetKnownPublicKeysAsync(New <KnownIdentities>().DefaultEncryptionIdentity));

            await ChangeEncryptionAsync(files, encryptionParameters);
        }
示例#3
0
        public async Task EncryptAsync(Stream clearIn, Stream encryptedOut, string fileName)
        {
            EncryptionParameters parameters = new EncryptionParameters(_cryptoId, _passphrase);
            await parameters.AddAsync(_publicKeys);

            EncryptedProperties properties = new EncryptedProperties(fileName);

            AxCryptFile.Encrypt(clearIn, encryptedOut, properties, parameters, _options, new ProgressContext());
        }
        private async Task <bool> EncryptFileOperationAsync()
        {
            _eventArgs.CryptoId = Resolve.CryptoFactory.Default(New <ICryptoPolicy>()).CryptoId;
            EncryptionParameters encryptionParameters = new EncryptionParameters(_eventArgs.CryptoId, _eventArgs.LogOnIdentity);
            await encryptionParameters.AddAsync(await (await GetWatchedFolderKeyShares(_eventArgs.OpenFileFullName)).ToAvailableKnownPublicKeysAsync(_eventArgs.LogOnIdentity));

            await New <AxCryptFile>().EncryptFileWithBackupAndWipeAsync(_eventArgs.OpenFileFullName, _eventArgs.SaveFileFullName, encryptionParameters, _progress);

            _eventArgs.Status = new FileOperationContext(String.Empty, ErrorStatus.Success);
            return(true);
        }
示例#5
0
        public static async Task TestGetTwoAsymmetricCryptosFromHeaders(CryptoImplementation cryptoImplementation)
        {
            SetupAssembly.AssemblySetupCrypto(cryptoImplementation);

            Headers headers = new Headers();

            EncryptionParameters parameters = new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("secrets"));
            IAsymmetricPublicKey publicKey1 = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey1);
            IAsymmetricPublicKey publicKey2 = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey2);
            await parameters.AddAsync(new UserPublicKey[] { new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey1), new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey2), });

            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(parameters, 10);

            using (V2HmacStream <MemoryStream> stream = V2HmacStream.Create <MemoryStream>(new V2HmacCalculator(new SymmetricKey(new byte[0])), new MemoryStream()))
            {
                documentHeaders.WriteStartWithHmac(stream);
                stream.Flush();
                stream.Chained.Position = 0;

                using (V2AxCryptReader reader = new V2AxCryptReader(new LookAheadStream(stream.Chained)))
                {
                    while (reader.Read())
                    {
                        if (reader.CurrentItemType == AxCryptItemType.HeaderBlock)
                        {
                            headers.HeaderBlocks.Add(reader.CurrentHeaderBlock);
                        }
                    }

                    SymmetricKey dataEncryptingKey = documentHeaders.Headers.FindHeaderBlock <V2KeyWrapHeaderBlock>().MasterKey;

                    IEnumerable <V2AsymmetricKeyWrapHeaderBlock> readerAsymmetricKeys = headers.HeaderBlocks.OfType <V2AsymmetricKeyWrapHeaderBlock>();
                    Assert.That(readerAsymmetricKeys.Count(), Is.EqualTo(2), "There should be two asymmetric keys in the headers.");

                    V2AsymmetricKeyWrapHeaderBlock asymmetricKey1 = readerAsymmetricKeys.First();
                    IAsymmetricPrivateKey          privateKey1    = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey1);
                    asymmetricKey1.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey1);
                    Assert.That(dataEncryptingKey, Is.EqualTo(asymmetricKey1.Crypto(0).Key), "The asymmetric wrapped key should be the one in the ICrypto instance.");

                    IAsymmetricPrivateKey privateKey2 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey2);
                    asymmetricKey1.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey2);
                    Assert.That(asymmetricKey1.Crypto(0), Is.Null, "The ICrypto instance should be null, since the private key was wrong.");

                    V2AsymmetricKeyWrapHeaderBlock asymmetricKey2 = readerAsymmetricKeys.Last();
                    asymmetricKey2.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey2);
                    Assert.That(dataEncryptingKey, Is.EqualTo(asymmetricKey2.Crypto(0).Key), "The asymmetric wrapped key should be the one in the ICrypto instance.");

                    asymmetricKey2.SetPrivateKey(new V2Aes256CryptoFactory(), privateKey1);
                    Assert.That(asymmetricKey2.Crypto(0), Is.Null, "The ICrypto instance should be null, since the private key was wrong.");
                }
            }
        }
        public async Task TestEncryptFileWhenDestinationExists()
        {
            IDataStore sourceInfo = New <IDataStore>(_davidCopperfieldTxtPath);
            IDataStore expectedDestinationInfo = New <IDataStore>(AxCryptFile.MakeAxCryptFileName(sourceInfo));

            using (Stream stream = expectedDestinationInfo.OpenWrite())
            {
            }

            FileOperationsController controller = new FileOperationsController();
            string        destinationPath       = String.Empty;
            LogOnIdentity logOnIdentity         = null;

            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("allan");
            };
            controller.QuerySaveFileAs += (object sender, FileOperationEventArgs e) =>
            {
                e.SaveFileFullName = Path.Combine(Path.GetDirectoryName(e.SaveFileFullName), "alternative-name.axx");
            };
            Guid cryptoId = Guid.Empty;

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
                logOnIdentity   = e.LogOnIdentity;
                cryptoId        = e.CryptoId;
            };

            FileOperationContext status = await controller.EncryptFileAsync(New <IDataStore>(_davidCopperfieldTxtPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");

            Assert.That(Path.GetFileName(destinationPath), Is.EqualTo("alternative-name.axx"), "The alternative name should be used, since the default existed.");
            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(destinationInfo.IsAvailable, "After encryption the destination file should be created.");

            EncryptionParameters encryptionParameters = new EncryptionParameters(cryptoId, logOnIdentity);
            await encryptionParameters.AddAsync(logOnIdentity.PublicKeys);

            Headers           headers = new Headers();
            AxCryptReaderBase reader  = headers.CreateReader(new LookAheadStream(destinationInfo.OpenRead()));

            using (IAxCryptDocument document = AxCryptReaderBase.Document(reader))
            {
                document.Load(logOnIdentity.Passphrase, cryptoId, headers);
                Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the passphrase given.");
            }
        }
        public static async Task TestEncryptWithTwoAsymmetricKeysAndOneCorrectPrivateKey()
        {
            EncryptionParameters encryptionParameters = new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("allan"));
            IAsymmetricPublicKey publicKey1           = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey1);
            await encryptionParameters.AddAsync(new UserPublicKey[] { new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey1), });

            IAsymmetricPublicKey publicKey2 = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey2);
            await encryptionParameters.AddAsync(new UserPublicKey[] { new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey2), });

            byte[] plainText = Resolve.RandomGenerator.Generate(25000);

            byte[] output = EncrytionHelper(encryptionParameters, "TestEncryptWithTwoAsymmetricKeysAndOneCorrectPrivateKey.txt", AxCryptOptions.EncryptWithCompression, plainText);

            DecryptionParameter   decryptionParameter0 = new DecryptionParameter(new Passphrase("niklas"), new V2Aes256CryptoFactory().CryptoId);
            IAsymmetricPrivateKey privateKey1          = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey1);
            DecryptionParameter   decryptionParameter1 = new DecryptionParameter(privateKey1, new V2Aes256CryptoFactory().CryptoId);
            IAsymmetricPrivateKey privateKey2          = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey2);
            DecryptionParameter   decryptionParameter2 = new DecryptionParameter(privateKey2, new V2Aes256CryptoFactory().CryptoId);

            byte[] decryptedText = DecryptionHelper(new DecryptionParameter[] { decryptionParameter0, decryptionParameter1, decryptionParameter2, }, output);

            Assert.That(decryptedText, Is.Not.Null, "The deryption failed because no valid decryption parameter was found.");
            Assert.That(decryptedText, Is.EquivalentTo(plainText), "The decrypted text should be the same as was originally encrypted.");
        }
示例#8
0
        private static async Task AddSharingParameters(EncryptionParameters parameters, ActiveFile activeFile, FileLock encryptedFileLock)
        {
            if (New <LicensePolicy>().Capabilities.Has(LicenseCapability.KeySharing))
            {
                EncryptedProperties properties = EncryptedProperties.Create(encryptedFileLock.DataStore);
                await parameters.AddAsync(properties.SharedKeyHolders);

                return;
            }

            if (activeFile.IsShared)
            {
                await New <IPopup>().ShowAsync(PopupButtons.Ok, Texts.InformationTitle, Texts.KeySharingRemovedInFreeModeWarningText, Common.DoNotShowAgainOptions.KeySharingRemovedInFreeModeWarning);
            }
        }
        private async Task EncryptWatchedFoldersIfSupportedAsync(LogOnIdentity identity, LicenseCapabilities capabilities, IProgressContext progress)
        {
            if (!capabilities.Has(LicenseCapability.SecureFolders))
            {
                return;
            }
            foreach (WatchedFolder watchedFolder in _fileSystemState.WatchedFolders.Where(wf => wf.Tag.Matches(identity.Tag)))
            {
                EncryptionParameters encryptionParameters = new EncryptionParameters(Resolve.CryptoFactory.Default(New <ICryptoPolicy>()).CryptoId, identity);
                await encryptionParameters.AddAsync(await watchedFolder.KeyShares.ToAvailableKnownPublicKeysAsync(identity));

                IDataContainer folder = New <IDataContainer>(watchedFolder.Path);
                progress.Display = folder.Name;
                await _axCryptFile.EncryptFoldersUniqueWithBackupAndWipeAsync(new IDataContainer[] { folder }, encryptionParameters, progress);
            }
        }
        private async Task HandleNotificationInternalAsync(SessionNotification notification, IProgressContext progress)
        {
            if (Resolve.Log.IsInfoEnabled)
            {
                Resolve.Log.LogInfo("Received notification type '{0}'.".InvariantFormat(notification.NotificationType));
            }
            EncryptionParameters encryptionParameters;

            switch (notification.NotificationType)
            {
            case SessionNotificationType.WatchedFolderAdded:
            case SessionNotificationType.WatchedFolderOptionsChanged:
                progress.NotifyLevelStart();
                try
                {
                    foreach (string fullName in notification.FullNames)
                    {
                        WatchedFolder watchedFolder = _fileSystemState.WatchedFolders.First(wf => wf.Path == fullName);

                        encryptionParameters = new EncryptionParameters(Resolve.CryptoFactory.Default(New <ICryptoPolicy>()).CryptoId, notification.Identity);
                        await encryptionParameters.AddAsync(await watchedFolder.KeyShares.ToAvailableKnownPublicKeysAsync(notification.Identity));

                        IDataContainer container = New <IDataContainer>(watchedFolder.Path);
                        progress.Display = container.Name;
                        IDataContainer[] dc = new IDataContainer[] { container };
                        await _axCryptFile.EncryptFoldersUniqueWithBackupAndWipeAsync(dc, encryptionParameters, progress);
                    }
                }
                finally
                {
                    progress.NotifyLevelFinished();
                }
                progress.Totals.ShowNotification();
                break;

            case SessionNotificationType.WatchedFolderRemoved:
                foreach (string fullName in notification.FullNames)
                {
                    IDataContainer removedFolderInfo = New <IDataContainer>(fullName);
                    progress.Display = removedFolderInfo.Name;
                    if (removedFolderInfo.IsAvailable)
                    {
                        await _axCryptFile.DecryptFilesInsideFolderUniqueWithWipeOfOriginalAsync(removedFolderInfo, notification.Identity, _statusChecker, progress).Free();
                    }
                }
                break;

            case SessionNotificationType.SignIn:
                await EncryptWatchedFoldersIfSupportedAsync(notification.Identity, notification.Capabilities, progress);

                break;

            case SessionNotificationType.SignOut:
                New <IInternetState>().Clear();
                New <ICache>().RemoveItem(CacheKey.RootKey);
                New <UserPublicKeyUpdateStatus>().Clear();
                break;

            case SessionNotificationType.EncryptPendingFiles:
                await _activeFileAction.ClearExceptionState();

                await _activeFileAction.PurgeActiveFiles(progress);

                if (_knownIdentities.DefaultEncryptionIdentity != LogOnIdentity.Empty)
                {
                    await EncryptWatchedFoldersIfSupportedAsync(_knownIdentities.DefaultEncryptionIdentity, notification.Capabilities, progress);
                }
                break;

            case SessionNotificationType.UpdateActiveFiles:
                await _fileSystemState.UpdateActiveFiles(notification.FullNames);

                break;

            case SessionNotificationType.ActiveFileChange:
            case SessionNotificationType.SessionStart:
            case SessionNotificationType.WatchedFolderChange:
            case SessionNotificationType.ProcessExit:
            case SessionNotificationType.KnownKeyChange:
            case SessionNotificationType.SessionChange:
            case SessionNotificationType.WorkFolderChange:
                await _activeFileAction.CheckActiveFiles(progress);

                break;

            case SessionNotificationType.LicensePolicyChanged:
            case SessionNotificationType.RefreshLicensePolicy:
                break;

            default:
                throw new InvalidOperationException("Unhandled notification received");
            }
        }