public async Task TestHandleSessionEvents(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); MockAxCryptFile mock = new MockAxCryptFile(); int callTimes = 0; mock.EncryptFilesUniqueWithBackupAndWipeMockAsync = async(IEnumerable <IDataContainer> folderInfos, EncryptionParameters encryptionParameters, IProgressContext progress) => { await Task.Delay(0); if (folderInfos.First().FullName == @"C:\My Documents\".NormalizeFilePath()) { ++callTimes; } }; Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>(); SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock, mockStatusChecker.Object); FakeDataStore.AddFolder(@"C:\My Documents"); LogOnIdentity key = new LogOnIdentity("passphrase"); await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\My Documents", key.Tag)); List <SessionNotification> sessionEvents = new List <SessionNotification>(); sessionEvents.Add(new SessionNotification(SessionNotificationType.WatchedFolderAdded, new LogOnIdentity("passphrase1"), @"C:\My Documents\")); sessionEvents.Add(new SessionNotification(SessionNotificationType.WatchedFolderAdded, new LogOnIdentity("passphrase"), @"C:\My Documents\")); foreach (SessionNotification sessionEvent in sessionEvents) { await handler.HandleNotificationAsync(sessionEvent); } Assert.That(callTimes, Is.EqualTo(2)); }
public static void AssemblySetupCrypto(CryptoImplementation cryptoImplementation) { switch (cryptoImplementation) { case CryptoImplementation.Mono: TypeMap.Register.New <AxCryptHMACSHA1>(() => PortableFactory.AxCryptHMACSHA1()); TypeMap.Register.New <HMACSHA512>(() => PortableFactory.HMACSHA512()); TypeMap.Register.New <Aes>(() => PortableFactory.AesManaged()); TypeMap.Register.New <CryptoStreamBase>(() => PortableFactory.CryptoStream()); TypeMap.Register.New <Sha1>(() => PortableFactory.SHA1Managed()); TypeMap.Register.New <Sha256>(() => PortableFactory.SHA256Managed()); break; case CryptoImplementation.WindowsDesktop: TypeMap.Register.New <AxCryptHMACSHA1>(() => PortableFactory.AxCryptHMACSHA1()); TypeMap.Register.New <HMACSHA512>(() => new Mono.Cryptography.HMACSHA512Wrapper(new Axantum.AxCrypt.Desktop.Cryptography.HMACSHA512CryptoServiceProvider())); TypeMap.Register.New <Aes>(() => new Mono.Cryptography.AesWrapper(new System.Security.Cryptography.AesCryptoServiceProvider())); TypeMap.Register.New <CryptoStreamBase>(() => PortableFactory.CryptoStream()); TypeMap.Register.New <Sha1>(() => PortableFactory.SHA1Managed()); TypeMap.Register.New <Sha256>(() => PortableFactory.SHA256Managed()); break; case CryptoImplementation.BouncyCastle: TypeMap.Register.New <AxCryptHMACSHA1>(() => BouncyCastleCryptoFactory.AxCryptHMACSHA1()); TypeMap.Register.New <HMACSHA512>(() => BouncyCastleCryptoFactory.HMACSHA512()); TypeMap.Register.New <Aes>(() => BouncyCastleCryptoFactory.Aes()); TypeMap.Register.New <CryptoStreamBase>(() => BouncyCastleCryptoFactory.CryptoStream()); TypeMap.Register.New <Sha1>(() => BouncyCastleCryptoFactory.Sha1()); TypeMap.Register.New <Sha256>(() => BouncyCastleCryptoFactory.Sha256()); break; } }
public static void TestSubkeyMethods(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); SymmetricKey key = new SymmetricKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }); Subkey subkey = null; Assert.Throws <ArgumentNullException>(() => { subkey = new Subkey(null, HeaderSubkey.Data); }); Assert.Throws <InternalErrorException>(() => { subkey = new Subkey(key, HeaderSubkey.None); }); subkey = new Subkey(key, HeaderSubkey.Data); Assert.That(subkey.Key.Size, Is.EqualTo(128), "A Subkey is exactly 16 bytes."); Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0x5f, 0xfe, 0x14, 0x56, 0xd5, 0x94, 0xf9, 0x22, 0x42, 0xe3, 0x66, 0x8f, 0x8c, 0xe6, 0xea, 0xc6 }), "Comparing with a pre-calculated value assumed to be correct."); subkey = new Subkey(key, HeaderSubkey.Headers); Assert.That(subkey.Key.Size, Is.EqualTo(128), "A Subkey is exactly 16 bytes."); Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0x1c, 0x81, 0x0e, 0xe7, 0x65, 0xe7, 0x0b, 0x8f, 0x7a, 0xa3, 0x2b, 0x03, 0x05, 0x07, 0xf8, 0x8a }), "Comparing with a pre-calculated value assumed to be correct."); subkey = new Subkey(key, HeaderSubkey.Hmac); Assert.That(subkey.Key.Size, Is.EqualTo(128), "A Subkey is exactly 16 bytes."); Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0xdb, 0xf1, 0x84, 0x11, 0x2e, 0xb9, 0x11, 0x16, 0x59, 0x71, 0x2b, 0xaf, 0xcf, 0xf2, 0xab, 0x24 }), "Comparing with a pre-calculated value assumed to be correct."); subkey = new Subkey(key, HeaderSubkey.Validator); Assert.That(subkey.Key.Size, Is.EqualTo(128), "A Subkey is exactly 16 bytes."); Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0x45, 0x22, 0xa0, 0x3d, 0x98, 0x00, 0x9d, 0x55, 0x45, 0xed, 0x42, 0xfb, 0xd8, 0x35, 0x78, 0xd0 }), "Comparing with a pre-calculated value assumed to be correct."); Assert.That(new Subkey(key, HeaderSubkey.Hmac).Key.GetBytes(), Is.EquivalentTo(new Subkey(key, HeaderSubkey.Hmac).Key.GetBytes()), "The subkey generation should be stable."); }
public async Task TestNotificationEncryptPendingFilesInLoggedOnFolders(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); FakeDataStore.AddFolder(@"C:\My Documents\"); Mock <AxCryptFile> mock = new Mock <AxCryptFile>(); mock.Setup(acf => acf.EncryptFoldersUniqueWithBackupAndWipeAsync(It.IsAny <IEnumerable <IDataContainer> >(), It.IsAny <EncryptionParameters>(), It.IsAny <IProgressContext>())); Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>(); SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock.Object, mockStatusChecker.Object); LogOnIdentity defaultKey = new LogOnIdentity("default"); await Resolve.KnownIdentities.SetDefaultEncryptionIdentity(defaultKey); await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\My Documents\", defaultKey.Tag)); List <SessionNotification> sessionEvents = new List <SessionNotification>(); sessionEvents.Add(new SessionNotification(SessionNotificationType.EncryptPendingFiles)); foreach (SessionNotification sessionEvent in sessionEvents) { await handler.HandleNotificationAsync(sessionEvent); } mock.Verify(acf => acf.EncryptFoldersUniqueWithBackupAndWipeAsync(It.Is <IEnumerable <IDataContainer> >(infos => infos.Any((i) => i.FullName == @"C:\My Documents\".NormalizeFolderPath())), It.IsAny <EncryptionParameters>(), It.IsAny <IProgressContext>()), Times.Exactly(1)); }
public static void TestInvalidArguments(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); SymmetricKey key = new SymmetricKey(128); SymmetricIV iv = new SymmetricIV(128); Assert.Throws <ArgumentNullException>(() => { if (new V1AesCrypto(new V1Aes128CryptoFactory(), null, SymmetricIV.Zero128) == null) { } }); Assert.Throws <ArgumentNullException>(() => { if (new V1AesCrypto(new V1Aes128CryptoFactory(), null, iv) == null) { } }); Assert.DoesNotThrow(() => { if (new V1AesCrypto(new V1Aes128CryptoFactory(), key, iv) == null) { } }); }
public static void TestPrematureEndOfFile(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); V1DocumentHeaders headers = new V1DocumentHeaders(new Passphrase("passphrase"), 10); using (MemoryStream stream = new MemoryStream()) { headers.WriteWithoutHmac(stream); stream.Position = 0; using (V1AxCryptReader reader = new V1AxCryptReader(new LookAheadStream(stream))) { AxCryptItemType lastItemType = AxCryptItemType.Undefined; while (reader.Read()) { lastItemType = reader.CurrentItemType; } Assert.That(lastItemType, Is.EqualTo(AxCryptItemType.Data)); Assert.That(reader.CurrentItemType, Is.EqualTo(AxCryptItemType.Data)); reader.SetStartOfData(); Assert.That(reader.Read(), Is.False); Assert.That(reader.CurrentItemType, Is.EqualTo(AxCryptItemType.EndOfStream)); Assert.That(reader.Read(), Is.False); Assert.That(reader.CurrentItemType, Is.EqualTo(AxCryptItemType.EndOfStream)); } } }
public static void TestHeaderBlockFactory(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); V1DocumentHeaders headers = new V1DocumentHeaders(new Passphrase("passphrase"), 10); using (MemoryStream stream = new MemoryStream()) { headers.WriteWithoutHmac(stream); stream.Position = 0; UnversionedAxCryptReader reader = new UnversionedAxCryptReader(new LookAheadStream(stream)); bool unexpectedHeaderTypeFound = false; while (reader.Read()) { if (reader.CurrentItemType != AxCryptItemType.HeaderBlock) { continue; } switch (reader.CurrentHeaderBlock.HeaderBlockType) { case HeaderBlockType.Preamble: case HeaderBlockType.Version: case HeaderBlockType.Data: case HeaderBlockType.Unrecognized: break; default: unexpectedHeaderTypeFound = !(reader.CurrentHeaderBlock is UnrecognizedHeaderBlock); break; } } Assert.That(unexpectedHeaderTypeFound, Is.False); } }
public async Task TestHandleSessionEventLogOn(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); MockAxCryptFile mock = new MockAxCryptFile(); bool called = false; int folderCount = -1; mock.EncryptFilesUniqueWithBackupAndWipeMockAsync = async(IEnumerable <IDataContainer> folderInfos, EncryptionParameters encryptionParameters, IProgressContext progress) => { folderCount = folderInfos.Count(); called = true; await Task.Delay(0); }; Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>(); SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock, mockStatusChecker.Object); FakeDataStore.AddFolder(@"C:\WatchedFolder"); LogOnIdentity key = new LogOnIdentity("passphrase"); await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\WatchedFolder", key.Tag)); await handler.HandleNotificationAsync(new SessionNotification(SessionNotificationType.SignIn, key)); Assert.That(called, Is.True); Assert.That(folderCount, Is.EqualTo(1), "There should be one folder passed for encryption as a result of the event."); }
public async Task TestHandleSessionEventLogOffWithWatchedFolders(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); MockAxCryptFile mock = new MockAxCryptFile(); bool called = false; mock.EncryptFilesUniqueWithBackupAndWipeMockAsync = async(IEnumerable <IDataContainer> folderInfos, EncryptionParameters encryptionParameters, IProgressContext progress) => { await Task.Delay(0); called = true; }; Mock <IStatusChecker> mockStatusChecker = new Mock <IStatusChecker>(); await Resolve.KnownIdentities.SetDefaultEncryptionIdentity(new LogOnIdentity("passphrase")); SessionNotificationHandler handler = new SessionNotificationHandler(Resolve.FileSystemState, Resolve.KnownIdentities, New <ActiveFileAction>(), mock, mockStatusChecker.Object); FakeDataStore.AddFolder(@"C:\WatchedFolder"); await Resolve.FileSystemState.AddWatchedFolderAsync(new WatchedFolder(@"C:\WatchedFolder", Resolve.KnownIdentities.DefaultEncryptionIdentity.Tag)); called = false; await handler.HandleNotificationAsync(new SessionNotification(SessionNotificationType.EncryptPendingFiles)); await handler.HandleNotificationAsync(new SessionNotification(SessionNotificationType.SignOut, Resolve.KnownIdentities.DefaultEncryptionIdentity)); Assert.That(called, Is.True, nameof(AxCryptFile.EncryptFoldersUniqueWithBackupAndWipeAsync) + " should be called when a signing out."); }
public static void TestConstructorWithKnownDefaultIdentity(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); _identities.Add(Passphrase.Empty); NewPasswordViewModel npvm = new NewPasswordViewModel(String.Empty, String.Empty); Assert.That(npvm.PasswordText, Is.EqualTo(String.Empty)); }
public static void TestExtensions_UserAsymmetricKeysToAccountKeyAndBack(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); UserKeyPair originalKeys = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); AccountKey accountKey = originalKeys.ToAccountKey(new Passphrase("password")); UserKeyPair roundtripKeys = accountKey.ToUserKeyPair(new Passphrase("password")); Assert.That(originalKeys, Is.EqualTo(roundtripKeys)); }
public static void TestThumbprint(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); Passphrase key1 = new Passphrase("genericPassphrase"); SymmetricKeyThumbprint originalThumbprint = key1.Thumbprint; Assert.That(originalThumbprint, Is.EqualTo(key1.Thumbprint), "The thumbprints should be the same."); }
public static void TestFileNameInfoAnsiName(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); V1AesCrypto headerCrypto = new V1AesCrypto(new V1Aes128CryptoFactory(), new V1DerivedKey(new Passphrase("nonterminating")).DerivedKey, SymmetricIV.Zero128); V1FileNameInfoEncryptedHeaderBlock fileInfoHeaderBlock = new V1FileNameInfoEncryptedHeaderBlock(headerCrypto); fileInfoHeaderBlock.FileName = "Dépôsé.txt"; Assert.That(fileInfoHeaderBlock.FileName, Is.EqualTo("Dépôsé.txt")); }
public static void TestExtensions_DecryptToBadArgumentsCausingEarlyException(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); Stream nullStream = null; ICryptoTransform nullEncryptor = null; ICryptoTransform encryptor = new V2AesCrypto(SymmetricKey.Zero256, SymmetricIV.Zero128, 0).DecryptingTransform(); Assert.Throws <ArgumentNullException>(() => nullStream.DecryptTo(Stream.Null, encryptor, true)); Assert.Throws <ArgumentNullException>(() => Stream.Null.DecryptTo(nullStream, encryptor, true)); Assert.Throws <ArgumentNullException>(() => Stream.Null.DecryptTo(Stream.Null, nullEncryptor, true)); }
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 static void TestValidateWrongPassphraseWithRealFile(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); FakeDataStore.AddFile(@"C:\My Folder\MyFile-txt.axx", new MemoryStream(Resources.helloworld_key_a_txt)); NewPasswordViewModel npvm = new NewPasswordViewModel(String.Empty, @"C:\My Folder\MyFile-txt.axx"); npvm.PasswordText = "b"; npvm.Verification = "b"; Assert.That(npvm[nameof(NewPasswordViewModel.PasswordText)], Is.Not.EqualTo("")); Assert.That(npvm.ValidationError, Is.EqualTo((int)ValidationError.WrongPassphrase)); }
public static void TestPassphraseConstructor(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); V1DerivedKey passphrase = new V1DerivedKey(new Passphrase("A Passphrase")); SymmetricKey derivedKey = passphrase.DerivedKey; Assert.That(derivedKey.Size, Is.EqualTo(128), "The default derived key is 128 bits."); Assert.Throws <ArgumentNullException>(() => { passphrase = new V1DerivedKey(null); }); }
public static void TestNonTerminatingFileName(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); UnicodeFileNameInfoHeaderBlockForTest unicodeFileInfoHeaderBlock = new UnicodeFileNameInfoHeaderBlockForTest(new V1AesCrypto(new V1Aes128CryptoFactory(), new V1DerivedKey(new Passphrase("passphrase")).DerivedKey, SymmetricIV.Zero128)); unicodeFileInfoHeaderBlock.FileName = "ABCDEFGHIJ.LMN"; unicodeFileInfoHeaderBlock.SetBadNameWithoutEndingNul(); Assert.Throws <InvalidOperationException>(() => { string fileName = unicodeFileInfoHeaderBlock.FileName; // Avoid FxCop errors Object.Equals(fileName, null); }); }
public static void TestNonUtcFileTimes(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); FileInfoEncryptedHeaderBlock fileInfoHeaderBlock = new FileInfoEncryptedHeaderBlock(new V1AesCrypto(new V1Aes128CryptoFactory(), new V1DerivedKey(new Passphrase("nonutc")).DerivedKey, SymmetricIV.Zero128)); DateTime utcNow = New <INow>().Utc; DateTime localNow = utcNow.ToLocalTime(); fileInfoHeaderBlock.CreationTimeUtc = localNow; Assert.That(fileInfoHeaderBlock.CreationTimeUtc.Kind, Is.EqualTo(DateTimeKind.Utc), "The local time should be converted to UTC by the setter."); Assert.That(fileInfoHeaderBlock.CreationTimeUtc, Is.EqualTo(utcNow), "The setter should have set the time to value of local time converted to UTC."); fileInfoHeaderBlock.LastAccessTimeUtc = localNow; Assert.That(fileInfoHeaderBlock.LastAccessTimeUtc.Kind, Is.EqualTo(DateTimeKind.Utc), "The local time should be converted to UTC by the setter."); Assert.That(fileInfoHeaderBlock.LastAccessTimeUtc, Is.EqualTo(utcNow), "The setter should have set the time to value of local time converted to UTC."); fileInfoHeaderBlock.LastWriteTimeUtc = localNow; Assert.That(fileInfoHeaderBlock.LastWriteTimeUtc.Kind, Is.EqualTo(DateTimeKind.Utc), "The local time should be converted to UTC by the setter."); Assert.That(fileInfoHeaderBlock.LastWriteTimeUtc, Is.EqualTo(utcNow), "The setter should have set the time to value of local time converted to UTC."); }
public static void TestGetCryptoFromHeaders(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); Headers headers = new Headers(); V2DocumentHeaders documentHeaders = new V2DocumentHeaders(new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("passphrase")), 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; V2KeyWrapHeaderBlock keyWrap = headers.FindHeaderBlock <V2KeyWrapHeaderBlock>(); IDerivedKey key = new V2Aes256CryptoFactory().RestoreDerivedKey(new Passphrase("passphrase"), keyWrap.DerivationSalt, keyWrap.DerivationIterations); keyWrap.SetDerivedKey(new V2Aes256CryptoFactory(), key); Assert.That(dataEncryptingKey, Is.EqualTo(keyWrap.MasterKey)); key = new V2Aes256CryptoFactory().RestoreDerivedKey(new Passphrase("wrong"), keyWrap.DerivationSalt, keyWrap.DerivationIterations); keyWrap.SetDerivedKey(new V2Aes256CryptoFactory(), key); Assert.That(dataEncryptingKey, Is.Not.EqualTo(keyWrap.MasterKey)); } } }
public TestV2AlgorithmVerifierEncryptedHeaderBlock(CryptoImplementation cryptoImplementation) { _cryptoImplementation = cryptoImplementation; }
public TestKeyWrap(CryptoImplementation cryptoImplementation) { _cryptoImplementation = cryptoImplementation; }
public TestAxCryptFile(CryptoImplementation cryptoImplementation) { _cryptoImplementation = cryptoImplementation; }
public TestV2AxCryptDocument(CryptoImplementation cryptoImplementation) { _cryptoImplementation = cryptoImplementation; }
public static void TestExtensions_AccountKeyToUserAsymmericKeysWithOnlyPublicKey(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); UserKeyPair originalKeys = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); IAsymmetricKeyPair partialKeyPair = Resolve.AsymmetricFactory.CreateKeyPair(originalKeys.KeyPair.PublicKey.ToString(), String.Empty); UserKeyPair originalPartialKeys = new UserKeyPair(originalKeys.UserEmail, originalKeys.Timestamp, partialKeyPair); AccountKey accountKey = originalPartialKeys.ToAccountKey(Passphrase.Empty); UserKeyPair roundtripKeys = accountKey.ToUserKeyPair(Passphrase.Empty); Assert.That(roundtripKeys, Is.EqualTo(originalPartialKeys)); }
public static void TestExtensions_UserAsymmetricKeysToAccountKeyAndBackUsingDataProtection(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); UserKeyPair originalKeys = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); AccountKey accountKey = originalKeys.ToAccountKey(Passphrase.Empty); UserKeyPair roundtripKeys = accountKey.ToUserKeyPair(Passphrase.Empty); Assert.That(accountKey.KeyPair.PrivateEncryptedPem.Length, Is.GreaterThan(0)); Assert.That(originalKeys, Is.EqualTo(roundtripKeys)); }
public static void TestHmacStream(CryptoImplementation cryptoImplementation) { SetupAssembly.AssemblySetupCrypto(cryptoImplementation); Assert.Throws <ArgumentNullException>(() => { using (V1HmacStream hmacStream = new V1HmacStream(null)) { } }); SymmetricKey key = new SymmetricKey(new byte[16]); using (V1HmacStream hmacStream = new V1HmacStream(key)) { Assert.That(hmacStream.CanRead, Is.False, "HmacStream does not support reading."); Assert.That(hmacStream.CanSeek, Is.False, "HmacStream does not support seeking."); Assert.That(hmacStream.CanWrite, Is.True, "HmacStream does support writing."); Assert.Throws <NotSupportedException>(() => { byte[] buffer = new byte[5]; hmacStream.Read(buffer, 0, buffer.Length); }); Assert.Throws <NotSupportedException>(() => { hmacStream.Seek(0, SeekOrigin.Begin); }); Assert.Throws <NotSupportedException>(() => { hmacStream.SetLength(0); }); Assert.Throws <ArgumentNullException>(() => { hmacStream.ReadFrom(null); }); hmacStream.Write(new byte[10], 0, 10); using (Stream dataStream = new MemoryStream()) { dataStream.Write(new byte[10], 0, 10); dataStream.Position = 0; hmacStream.ReadFrom(dataStream); } Assert.That(hmacStream.Position, Is.EqualTo(20), "There are 20 bytes written so the position should be 20."); Assert.That(hmacStream.Length, Is.EqualTo(20), "There are 20 bytes written so the position should be 20."); hmacStream.Flush(); Assert.That(hmacStream.Position, Is.EqualTo(20), "Nothing should change after Flush(), this is not a buffered stream."); Assert.That(hmacStream.Length, Is.EqualTo(20), "Nothing should change after Flush(), this is not a buffered stream."); Assert.Throws <NotSupportedException>(() => { hmacStream.Position = 0; }, "Position is not supported."); Hmac dataHmac = hmacStream.HmacResult; Assert.That(dataHmac.GetBytes(), Is.EquivalentTo(new byte[] { 0x62, 0x6f, 0x2c, 0x61, 0xc7, 0x68, 0x00, 0xb3, 0xa6, 0x8d, 0xf9, 0x55, 0x95, 0xbc, 0x1f, 0xd1 }), "The HMAC of 20 bytes of zero with 128-bit AesKey all zero should be this."); Assert.Throws <InvalidOperationException>(() => { hmacStream.Write(new byte[1], 0, 1); }, "Can't write to the stream after checking and thus finalizing the HMAC"); // This also implicitly covers double-dispose since we're in a using block. hmacStream.Dispose(); Assert.Throws <ObjectDisposedException>(() => { Hmac invalidDataHmac = hmacStream.HmacResult; // Remove FxCop warning Object.Equals(invalidDataHmac, null); }); Assert.Throws <ObjectDisposedException>(() => { hmacStream.Write(new byte[1], 0, 1); }); Assert.Throws <ObjectDisposedException>(() => { using (Stream stream = new MemoryStream()) { hmacStream.ReadFrom(stream); } }); } }
public TestFileOperationsController(CryptoImplementation cryptoImplementation) { _cryptoImplementation = cryptoImplementation; }
public TestKnownPublicKeys(CryptoImplementation cryptoImplementation) { _cryptoImplementation = cryptoImplementation; }
public TestSymmetricKeyThumbprint(CryptoImplementation cryptoImplementation) { _cryptoImplementation = cryptoImplementation; }