/// <summary> /// Checks the key pair (private and public key) of a user. /// </summary> /// <param name="userKeyPair">The key pair to check.</param> /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException"/> private static void ValidateUserKeyPair(UserKeyPair userKeyPair) { if (userKeyPair == null) { throw new InvalidKeyPairException("User key pair cannot be null."); } }
private static string EncryptPrivateKey(UserKeyPair keys, Passphrase passphrase) { if (keys.KeyPair.PrivateKey == null) { return(String.Empty); } byte[] privateKeyPemBytes = Encoding.UTF8.GetBytes(keys.KeyPair.PrivateKey.ToString()); if (passphrase == Passphrase.Empty) { byte[] encryptedPrivateKeyBytes = New <IProtectedData>().Protect(privateKeyPemBytes, null); return(Convert.ToBase64String(encryptedPrivateKeyBytes)); } StringBuilder encryptedPrivateKey = new StringBuilder(); using (StringWriter writer = new StringWriter(encryptedPrivateKey)) { using (Stream stream = new MemoryStream(privateKeyPemBytes)) { EncryptionParameters encryptionParameters = new EncryptionParameters(Resolve.CryptoFactory.Preferred.CryptoId, passphrase); EncryptedProperties properties = new EncryptedProperties("private-key.pem"); using (MemoryStream encryptedStream = new MemoryStream()) { AxCryptFile.Encrypt(stream, encryptedStream, properties, encryptionParameters, AxCryptOptions.EncryptWithCompression, new ProgressContext()); writer.Write(Convert.ToBase64String(encryptedStream.ToArray())); } } } return(encryptedPrivateKey.ToString()); }
public void GenerateMissingFileKeys(long?nodeId = null, int limit = int.MaxValue) { _client.Executor.CheckApiServerVersion(); #region Parameter Validation nodeId.NullableMustPositive(nameof(nodeId)); limit.MustPositive(nameof(limit)); #endregion UserKeyPair userKeyPair = _client.AccountImpl.GetAndCheckUserKeyPair(); int currentBatchOffset = 0; const int batchLimit = 10; while (currentBatchOffset < limit) { IRestRequest currentBatchRequest = _client.Builder.GetMissingFileKeys(nodeId, batchLimit, currentBatchOffset); ApiMissingFileKeys missingFileKeys = _client.Executor.DoSyncApiCall <ApiMissingFileKeys>(currentBatchRequest, RequestType.GetMissingFileKeys); HandlePendingMissingFileKeys(missingFileKeys, userKeyPair.UserPrivateKey); currentBatchOffset += missingFileKeys.Items.Count; if (missingFileKeys.Items.Count < batchLimit) { break; } } }
public async Task TestManageAccountViewModelChangePassword() { UserKeyPair key1 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); UserKeyPair key2 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); var mockUserAsymmetricKeysStore = new Mock <AccountStorage>((IAccountService)null); mockUserAsymmetricKeysStore.Setup <Task <IEnumerable <UserKeyPair> > >(f => f.AllKeyPairsAsync()).Returns(Task.FromResult((IEnumerable <UserKeyPair>) new UserKeyPair[] { key1, key2 })); string passphraseUsed = String.Empty; mockUserAsymmetricKeysStore.Setup(f => f.ChangePassphraseAsync(It.IsAny <Passphrase>())) .Callback <Passphrase>((passphrase) => { passphraseUsed = passphrase.Text; }).Returns(Task.FromResult(true)); ManageAccountViewModel viewModel = await ManageAccountViewModel.CreateAsync(mockUserAsymmetricKeysStore.Object); IEnumerable <AccountProperties> emailsList = null; viewModel.BindPropertyChanged(nameof(ManageAccountViewModel.AccountProperties), (IEnumerable <AccountProperties> emails) => emailsList = emails); Assert.That(emailsList.Count(), Is.EqualTo(2), "There should be two accounts now."); Assert.That(emailsList.First().EmailAddress, Is.EqualTo("*****@*****.**"), "The first should be '*****@*****.**'"); Assert.That(emailsList.Last().EmailAddress, Is.EqualTo("*****@*****.**"), "The last should be '*****@*****.**'"); await viewModel.ChangePassphraseAsync.ExecuteAsync("allan").Free(); Assert.That(passphraseUsed, Is.EqualTo("allan")); }
private FileDownload CreateFileDownloadInternally(string actionId, long nodeId, Stream output, IFileDownloadCallback callback) { _client.Executor.CheckApiServerVersion(); #region Parameter Validation CheckDownloadActionId(actionId); nodeId.MustPositive(nameof(nodeId)); output.CheckStreamCanWrite(nameof(output)); #endregion FileDownload download = null; Node nodeToDownload = GetNode(nodeId); // Validation will be done in "GetNode" if (nodeToDownload.IsEncrypted.GetValueOrDefault(false)) { UserKeyPair keyPair = _client.AccountImpl.GetAndCheckUserKeyPair(); download = new EncFileDownload(_client, actionId, nodeToDownload, output, keyPair.UserPrivateKey); } else { download = new FileDownload(_client, actionId, nodeToDownload, output); } _runningDownloads.Add(actionId, download); download.AddFileDownloadCallback(callback); download.AddFileDownloadCallback(this); return(download); }
private FileUpload CreateFileUploadInternally(string actionId, FileUploadRequest request, Stream input, long fileSize = -1, IFileUploadCallback callback = null) { _client.Executor.CheckApiServerVersion(); #region Parameter Validation CheckUploadActionId(actionId); request.MustNotNull(nameof(request)); request.ParentId.MustPositive(nameof(request.ParentId)); request.Name.MustNotNullOrEmptyOrWhitespace(nameof(request.Name)); input.CheckStreamCanRead(nameof(input)); #endregion FileUpload upload; if (IsNodeEncrypted(request.ParentId)) { UserKeyPair keyPair = _client.AccountImpl.GetAndCheckUserKeyPair(); upload = new EncFileUpload(_client, actionId, request, input, keyPair.UserPublicKey, fileSize); } else { upload = new FileUpload(_client, actionId, request, input, fileSize); } _runningUploads.Add(actionId, upload); upload.AddFileUploadCallback(callback); upload.AddFileUploadCallback(this); return(upload); }
public Node EnableRoomEncryption(EnableRoomEncryptionRequest request) { _client.Executor.CheckApiServerVersion(); #region Parameter Validation request.MustNotNull(nameof(request)); request.DataRoomRescueKeyPassword.MustNotNullOrEmptyOrWhitespace(nameof(request.DataRoomRescueKeyPassword), true); request.Id.MustPositive(nameof(request.Id)); #endregion ApiUserKeyPair apiDataRoomRescueKey = null; if (request.DataRoomRescueKeyPassword != null) { try { UserKeyPair cryptoPair = Crypto.Sdk.Crypto.GenerateUserKeyPair(request.DataRoomRescueKeyPassword); apiDataRoomRescueKey = UserMapper.ToApiUserKeyPair(cryptoPair); } catch (CryptoException ce) { DracoonClient.Log.Debug(Logtag, $"Generation of user key pair failed with '{ce.Message}'!"); throw new DracoonCryptoException(CryptoErrorMapper.ParseCause(ce), ce); } } ApiEnableRoomEncryptionRequest apiEnableRoomEncryptionRequest = RoomMapper.ToApiEnableRoomEncryptionRequest(request, apiDataRoomRescueKey); IRestRequest restRequest = _client.Builder.PutEnableRoomEncryption(request.Id, apiEnableRoomEncryptionRequest); ApiNode result = _client.Executor.DoSyncApiCall <ApiNode>(restRequest, RequestType.PutEnableRoomEncryption); return(NodeMapper.FromApiNode(result)); }
public void CreateCertificate() { CertificateManager _certificator = new CertificateManager(); var keypair = new UserKeyPair(_certificator.GeneratePair()); var certificate = _certificator.GenerateCertificate("Elton John", RegisterTokenOptions.ISSUER, keypair.PrivatKey, keypair.PublicKey); File.WriteAllBytes("testCertificate.crt", _certificator.ConvertToByte(certificate)); }
internal static ApiUserKeyPair ToApiUserKeyPair(UserKeyPair userKeyPair) { ApiUserKeyPair apiUserKeyPair = new ApiUserKeyPair { PublicKeyContainer = ToApiUserPublicKey(userKeyPair.UserPublicKey), PrivateKeyContainer = ToApiUserPrivateKey(userKeyPair.UserPrivateKey) }; return(apiUserKeyPair); }
private static string GetLogonStatus(bool isLoggedOn) { if (isLoggedOn) { UserKeyPair activeKeyPair = Resolve.KnownIdentities.DefaultEncryptionIdentity.ActiveEncryptionKeyPair; return(activeKeyPair != UserKeyPair.Empty ? Texts.AccountLoggedOnStatusText.InvariantFormat(activeKeyPair.UserEmail) : Texts.LoggedOnStatusText); } return(Texts.LoggedOffStatusText); }
private bool TestCheckUserKeyPair(byte[] ukpFileBytes, string pw) { UserKeyPair ukp = new UserKeyPair() { UserPrivateKey = TestUtilities.ReadTestResource <UserPrivateKey>(ukpFileBytes) }; return(Crypto.CheckUserKeyPair(ukp, pw)); }
internal static UserKeyPair FromApiUserKeyPair(ApiUserKeyPair apiUserKeyPair) { UserKeyPair userKeyPair = new UserKeyPair { UserPublicKey = FromApiUserPublicKey(apiUserKeyPair.PublicKeyContainer), UserPrivateKey = FromApiUserPrivateKey(apiUserKeyPair.PrivateKeyContainer) }; return(userKeyPair); }
public void SetUserKeyPair() { _client.Executor.CheckApiServerVersion(); UserKeyPair cryptoPair = GenerateNewUserKeyPair(_client.EncryptionPassword); ApiUserKeyPair apiUserKeyPair = UserMapper.ToApiUserKeyPair(cryptoPair); IRestRequest request = _client.Builder.SetUserKeyPair(apiUserKeyPair); _client.Executor.DoSyncApiCall <VoidResponse>(request, RequestType.SetUserKeyPair); }
public static void TestExtensions_AccountKeyToUserAsymmetricKeysWithWrongPassphrase(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("wrong password")); Assert.That(roundtripKeys, Is.Null); }
public void ReadCertificate() { X509CertificateParser certParser = new X509CertificateParser(); FileStream fs = new FileStream("testCertificate.crt", FileMode.Open); X509Certificate cert = certParser.ReadCertificate(fs); fs.Close(); var publicKeyByte = cert.GetPublicKey() as RsaKeyParameters; UserKeyPair pair = new UserKeyPair(publicKeyByte); }
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 void TestEquals() { UserKeyPair userKeyPair1 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); UserKeyPair userKeyPair1Copy = new UserKeyPair(userKeyPair1.UserEmail, userKeyPair1.Timestamp, userKeyPair1.KeyPair); Assert.That(userKeyPair1, Is.EqualTo(userKeyPair1Copy)); UserKeyPair userKeyPair2 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); Assert.That(userKeyPair1, Is.Not.EqualTo(userKeyPair2)); }
public void TestPrivatKey() { CertificateManager _certificator = new CertificateManager(); var keypair = new UserKeyPair(_certificator.GeneratePair()); var certificate = _certificator.GenerateCertificate("Elton John", RegisterTokenOptions.ISSUER, keypair.PrivatKey, keypair.PublicKey); FileModel file = new FileModel(Guid.NewGuid() + ".pkf", keypair.PrivatKeyByte); File.WriteAllBytes(file.Name, file.Data); file.Data = File.ReadAllBytes(file.Name); var newPair = new UserKeyPair(file.Data); }
public async Task TestSimpleCreateAsymmetricKeysStore() { FakeDataStore.AddFolder(@"C:\Temp"); IDataContainer workFolder = New <IDataContainer>(@"C:\Temp"); AccountStorage store = new AccountStorage(new LocalAccountService(new LogOnIdentity(EmailAddress.Parse(@"*****@*****.**"), new Passphrase("secret")), workFolder)); UserKeyPair userKeyPair = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); await store.ImportAsync(userKeyPair); Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PrivateKey, Is.Not.Null); Assert.That((await store.AllKeyPairsAsync()).First().KeyPair.PublicKey, Is.Not.Null); }
private async Task <object> CreateAccountAction() { if (String.IsNullOrEmpty(UserEmail)) { return(null); } AccountStorage accountStorage = new AccountStorage(New <LogOnIdentity, IAccountService>(new LogOnIdentity(EmailAddress.Parse(UserEmail), new Passphrase(PasswordText)))); UserKeyPair userKeys = new UserKeyPair(EmailAddress.Parse(UserEmail), New <INow>().Utc, New <KeyPairService>().New()); await accountStorage.ImportAsync(userKeys); return(null); }
public void TestAsymmetricIdentityButDifferentPassphraseMatches() { UserKeyPair key1 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); UserKeyPair key2 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); IdentityPublicTag tag1 = new IdentityPublicTag(new LogOnIdentity(new UserKeyPair[] { key1 }, new Passphrase("allan"))); IdentityPublicTag tag2 = new IdentityPublicTag(new LogOnIdentity(new UserKeyPair[] { key2 }, new Passphrase("niklas"))); Assert.That(tag1.Matches(tag2), "tag1 should match tag2 since they are based on the same asymmetric user email and passphrase."); Assert.That(tag2.Matches(tag1), "tag2 should match tag1 since they are based on the same asymmetric user email and passphrase."); Assert.That(tag1.Matches(tag1), "tag1 should match tag1 since they are the same instance."); Assert.That(tag2.Matches(tag2), "tag2 should match tag2 since they are the same instance."); }
public void TestDifferentAsymmetricIdentityAndSamePassphraseDoesNotMatch() { UserKeyPair key1 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); UserKeyPair key2 = new UserKeyPair(EmailAddress.Parse("*****@*****.**"), 512); IdentityPublicTag tag1 = new IdentityPublicTag(new LogOnIdentity(new UserKeyPair[] { key1 }, new Passphrase("allan"))); IdentityPublicTag tag2 = new IdentityPublicTag(new LogOnIdentity(new UserKeyPair[] { key2 }, new Passphrase("allan"))); Assert.That(!tag1.Matches(tag2), "tag1 should not match tag2 since they are based on different asymmetric user email even if passphrase is the same."); Assert.That(!tag2.Matches(tag1), "tag2 should not match tag1 since they are based on different asymmetric user email even if passphrase is the same."); Assert.That(tag1.Matches(tag1), "tag1 should match tag1 since they are the same instance."); Assert.That(tag2.Matches(tag2), "tag2 should match tag2 since they are the same instance."); }
public void SetUp() { DsaParametersGenerator paramGen = new DsaParametersGenerator(); _dsaParameters = paramGen.GenerateParameters(1024, 160, 160); _dsaParameters.HashFunction = new Hasher(Hasher.HashImplementation.Sha1); UserKeyGenerator keyGen = new UserKeyGenerator(_dsaParameters); _keyPair = keyGen.GenerateKeyPair(); _dsaAlgorithm = new DsaAlgorithm(_dsaParameters); }
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)); }
/// <summary> /// Convert the internal representation of a key pair to the external account key representation. /// </summary> /// <param name="keys">The key pair.</param> /// <param name="passphrase">The passphrase to encrypt it with.</param> /// <returns>A representation suitable for serialization and external storage.</returns> public static AccountKey ToAccountKey(this UserKeyPair keys, Passphrase passphrase) { if (keys == null) { throw new ArgumentNullException(nameof(keys)); } string encryptedPrivateKey = EncryptPrivateKey(keys, passphrase); KeyPair keyPair = new KeyPair(keys.KeyPair.PublicKey.ToString(), encryptedPrivateKey); AccountKey accountKey = new AccountKey(keys.UserEmail.Address, keys.KeyPair.PublicKey.Thumbprint.ToString(), keyPair, keys.Timestamp, PrivateKeyStatus.PassphraseKnown); return(accountKey); }
public void GenerateNewUserKeyPair_Success() { // ARRANGE UserKeyPair expected = FactoryUser.UserKeyPair; IInternalDracoonClient c = FactoryClients.InternalDracoonClientMock(true); DracoonAccountImpl a = new DracoonAccountImpl(c); Mock.Arrange(() => Crypto.Sdk.Crypto.GenerateUserKeyPair(Arg.AnyString)).Returns(FactoryUser.UserKeyPair).Occurs(1); // ACT UserKeyPair actual = a.GenerateNewUserKeyPair(c.EncryptionPassword); // ASSERT Assert.Equal(expected, actual, new UserKeyPairComparer()); Mock.Assert(() => Crypto.Sdk.Crypto.GenerateUserKeyPair(Arg.AnyString)); }
internal UserKeyPair GetAndCheckUserKeyPair() { try { IRestRequest request = _client.Builder.GetUserKeyPair(); ApiUserKeyPair result = _client.Executor.DoSyncApiCall <ApiUserKeyPair>(request, RequestType.GetUserKeyPair); UserKeyPair userKeyPair = UserMapper.FromApiUserKeyPair(result); if (Crypto.Sdk.Crypto.CheckUserKeyPair(userKeyPair, _client.EncryptionPassword)) { return(userKeyPair); } throw new DracoonCryptoException(DracoonCryptoCode.INVALID_PASSWORD_ERROR); } catch (CryptoException ce) { DracoonClient.Log.Debug(Logtag, $"Check of user key pair failed with '{ce.Message}'!"); throw new DracoonCryptoException(CryptoErrorMapper.ParseCause(ce), ce); } }
/// <summary> /// Cheks if a user key pair can be unlocked. /// </summary> /// <param name="userKeyPair">The user key pair which should be unlocked.</param> /// <param name="password">The password which secures the private key</param> /// <returns>True if the user key pair could be unlocked. Otherwise false.</returns> /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException">If the provided key pair is invalid.</exception> /// <exception cref="Dracoon.Crypto.Sdk.CryptoException">If an unexpected error in the decryption of the private key occured.</exception> public static bool CheckUserKeyPair(UserKeyPair userKeyPair, String password) { ValidateUserKeyPair(userKeyPair); ValidateUserPrivateKey(userKeyPair.UserPrivateKey); if (password == null || password.Length == 0) { return(false); } try { DecryptPrivateKey(userKeyPair.UserPrivateKey.PrivateKey, password); } catch (InvalidPasswordException) { return(false); } return(true); }
static void Main(String[] args) { // --- INITIALIZATION --- // Generate key pair UserKeyPair userKeyPair = Crypto.GenerateUserKeyPair(USER_PASSWORD); // Check key pair if (!Crypto.CheckUserKeyPair(userKeyPair, USER_PASSWORD)) { Trace.WriteLine("Invalid user password!"); return; } byte[] plainData = Encoding.UTF8.GetBytes(DATA); Trace.WriteLine("Plain Data:"); Trace.WriteLine(Encoding.UTF8.GetString(plainData)); Trace.WriteLine("Plain Data: (BASE64)"); Trace.WriteLine(Convert.ToBase64String(plainData)); // --- ENCRYPTION --- // Generate plain file key PlainFileKey fileKey = Crypto.GenerateFileKey(); // Encrypt blocks byte[] encData = EncryptData(fileKey, plainData); // Encrypt file key EncryptedFileKey encFileKey = Crypto.EncryptFileKey(fileKey, userKeyPair.UserPublicKey); Trace.WriteLine("Encrypted Data: (Base64)"); Trace.WriteLine(Convert.ToBase64String(encData)); // --- DECRYPTION --- // Decrypt file key PlainFileKey decFileKey = Crypto.DecryptFileKey(encFileKey, userKeyPair.UserPrivateKey, USER_PASSWORD); // Decrypt blocks byte[] decData = DecryptData(decFileKey, encData); Trace.WriteLine("Decrypted Data:"); Trace.WriteLine(Encoding.UTF8.GetString(decData)); Trace.WriteLine("Decrypted Data: (BASE64)"); Trace.WriteLine(Convert.ToBase64String(plainData)); }
public async Task <FileModel> GeneratePrivateKey(CurrentUser currentUser) { var userRepository = _storage.GetRepository <User>(); var certificateFileRepository = _storage.GetFileRepository(FileTypeEnum.Certificate); var keypair = new UserKeyPair(_certificator.GeneratePair()); var certificate = _certificator.GenerateCertificate(currentUser.FullName, RegisterTokenOptions.ISSUER, keypair.PrivatKey, keypair.PublicKey); var user = await userRepository.Get(x => x.Id == currentUser.Id); string name = "certificate_" + user.FullName.Replace(" ", "_"); user.CertificateId = await certificateFileRepository.Save(_certificator.ConvertToByte(certificate), name); await userRepository.Update(user); FileModel file = new FileModel(Guid.NewGuid() + ".pkf", keypair.PrivatKeyByte); return(file); }