コード例 #1
0
ファイル: KafkaServer.cs プロジェクト: szawaski/Zerra
 public KafkaServer(string host, SymmetricKey encryptionKey)
 {
     this.host             = host;
     this.encryptionKey    = encryptionKey;
     this.commandExchanges = new List <CommandConsumer>();
     this.eventExchanges   = new List <EventConsumer>();
 }
コード例 #2
0
        void OpenSqliteConnection(int flags, SymmetricKey encryptionKey, out sqlite3 db)
        {
            LastErrorCode = raw.sqlite3_open_v2(Path, out db, flags, null);
            if (LastErrorCode != raw.SQLITE_OK)
            {
                Path = null;
                var errMessage = "Failed to open SQLite storage engine at path {0}".Fmt(Path);
                throw new CouchbaseLiteException(errMessage, StatusCode.DbError);
            }

#if !__ANDROID__ && !NET_3_5 && VERBOSE
            var i   = 0;
            var val = raw.sqlite3_compileoption_get(i);
            while (val != null)
            {
                Log.V(TAG, "Sqlite Config: {0}".Fmt(val));
                val = raw.sqlite3_compileoption_get(++i);
            }
#endif

            Log.D(TAG, "Open {0} (flags={1}{2})", Path, flags, (encryptionKey != null ? ", encryption key given" : ""));

            raw.sqlite3_create_collation(db, "JSON", null, CouchbaseSqliteJsonUnicodeCollationFunction.Compare);
            raw.sqlite3_create_collation(db, "JSON_ASCII", null, CouchbaseSqliteJsonAsciiCollationFunction.Compare);
            raw.sqlite3_create_collation(db, "JSON_RAW", null, CouchbaseSqliteJsonRawCollationFunction.Compare);
            raw.sqlite3_create_collation(db, "REVID", null, CouchbaseSqliteRevIdCollationFunction.Compare);
        }
コード例 #3
0
        public byte[] UnwrapMasterKey(SymmetricKey keyEncryptingKey, byte fileVersionMajor)
        {
            if (keyEncryptingKey == null)
            {
                throw new ArgumentNullException("keyEncryptingKey");
            }

            byte[]       wrappedKeyData         = GetKeyData();
            Salt         salt                   = Salt;
            SymmetricKey masterKeyEncryptingKey = keyEncryptingKey;

            if (fileVersionMajor <= 1)
            {
                // Due to a bug in 1.1 and earlier we only used a truncated part of the key and salt :-(
                // Compensate for this here. Users should be warned if FileVersionMajor <= 1 .
                byte[] badKey = new byte[masterKeyEncryptingKey.Size / 8];
                Array.Copy(keyEncryptingKey.GetBytes(), 0, badKey, 0, 4);
                masterKeyEncryptingKey = new SymmetricKey(badKey);

                byte[] badSalt = new byte[salt.Length];
                Array.Copy(salt.GetBytes(), 0, badSalt, 0, 4);
                salt = new Salt(badSalt);
            }

            KeyWrap keyWrap = new KeyWrap(salt, KeyWrapIterations, KeyWrapMode.AxCrypt);

            byte[] unwrappedKeyData = keyWrap.Unwrap(Resolve.CryptoFactory.Legacy.CreateCrypto(masterKeyEncryptingKey, null, 0), wrappedKeyData);
            return(unwrappedKeyData);
        }
コード例 #4
0
ファイル: Encryptor.cs プロジェクト: aschoerk/cryptDotNetJava
        /// <summary>
        /// Encrypts the specified data.
        /// </summary>
        /// <param name="data">The data to encrypt</param>
        /// <param name="key">The key to encrypt data.</param>
        /// <returns>
        /// The data encrypted.
        /// </returns>
        private byte[] EncryptSymmetric(byte[] data, SymmetricKey key)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data");
            }

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


            using (AesCryptoServiceProvider providerInLine = new AesCryptoServiceProvider())
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (ICryptoTransform cryptoEncryptor = providerInLine.CreateEncryptor(key.Key, key.IV))
                    {
                        using (CryptoStream writerStream = new CryptoStream(stream, cryptoEncryptor, CryptoStreamMode.Write))
                        {
                            writerStream.Write(data, 0, data.Length);
                            writerStream.FlushFinalBlock();
                            byte[] res = stream.ToArray();
                            return(res);
                        }
                    }
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Creates a secret in Azure Key Vault and returns its ID.
        /// </summary>
        /// <param name="secretName">The name of the secret to create.</param>
        /// <returns>The ID of the secret created.</returns>
        public static string SetUpKeyVaultSecret(string secretName)
        {
            KeyVaultClient cloudVault = new KeyVaultClient(GetAccessToken);
            string         vaultUri   = CloudConfigurationManager.GetSetting("VaultUri");

            /* try
             * {
             *   // Delete the secret if it exists.
             *   cloudVault.DeleteSecretAsync(vaultUri, secretName).GetAwaiter().GetResult();
             * }
             * catch (KeyVaultClientException ex)
             * {
             *   if (ex.Status != System.Net.HttpStatusCode.NotFound)
             *   {
             *       Console.WriteLine("Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
             *       Console.WriteLine("Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
             *       Console.WriteLine("Press any key to exit");
             *       Console.ReadLine();
             *       throw;
             *   }
             * }*/

            // Create a 256bit symmetric key and convert it to Base64.
            SymmetricKey symmetricKey   = new SymmetricKey(secretName, SymmetricKey.KeySize256);
            string       symmetricBytes = Convert.ToBase64String(symmetricKey.Key);

            // Store the Base64 of the key in the key vault. Note that the content-type of the secret must
            // be application/octet-stream or the KeyVaultKeyResolver will not load it as a key.
            Secret cloudSecret = cloudVault.SetSecretAsync(vaultUri, secretName, symmetricBytes, null, "application/octet-stream").GetAwaiter().GetResult();

            // Return the base identifier of the secret. This will be resolved to the current version of the secret.
            return(cloudSecret.SecretIdentifier.BaseIdentifier);
        }
コード例 #6
0
ファイル: Encryptor.cs プロジェクト: aschoerk/cryptDotNetJava
        public byte[] DecryptTestwise(byte[] data, SymmetricKey key)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data");
            }

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


            using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
            {
                using (MemoryStream outputStream = new MemoryStream())
                {
                    using (MemoryStream memStreamEncryptData = new MemoryStream(data))
                    {
                        using (ICryptoTransform cryptoDecryptor = provider.CreateDecryptor(key.Key, key.IV))
                        {
                            using (CryptoStream stream = new CryptoStream(memStreamEncryptData, cryptoDecryptor, CryptoStreamMode.Read))
                            {
                                byte[] resultBuffer = new byte[data.Length];
                                int    len          = stream.Read(resultBuffer, 0, resultBuffer.Length);
                                outputStream.Write(resultBuffer, 0, len);
                                outputStream.Flush();
                                return(outputStream.ToArray());
                            }
                        }
                    }
                }
            }
        }
コード例 #7
0
ファイル: Encryptor.cs プロジェクト: aschoerk/cryptDotNetJava
        public byte[] DecryptTestWise(byte[] toDecrypt, string xmlPrivate)
        {
            //Encode with public key
            RSACryptoServiceProvider rsaPrivate = new RSACryptoServiceProvider();

            rsaPrivate.FromXmlString(xmlPrivate);

            int len = toDecrypt[0] + toDecrypt[1] * 256;

            byte[] encryptedSymmetricKey = new byte[len];
            for (int i = 0; i < len; i++)
            {
                encryptedSymmetricKey[i] = toDecrypt[i + 2];
            }

            byte[] encryptedData = new byte[toDecrypt.Length - 2 - len];
            for (int i = 0; i < encryptedData.Length; i++)
            {
                encryptedData[i] = toDecrypt[i + 2 + len];
            }

            byte[] decryptedKey = rsaPrivate.Decrypt(encryptedSymmetricKey, false);


            SymmetricKey s = new SymmetricKey();

            s.fromByteArray(decryptedKey);

            return(DecryptTestwise(encryptedData, s));
        }
コード例 #8
0
ファイル: Encryptor.cs プロジェクト: aschoerk/cryptDotNetJava
        public byte[] EncryptAssymetricByPublic(byte[] toEncrypt, String xmlPublic)
        {
            //Encode with public key
            RSACryptoServiceProvider rsaPublic = new RSACryptoServiceProvider();

            rsaPublic.FromXmlString(xmlPublic);


            SymmetricKey symmetricKey = GenerateSymmetricKey();

            byte[] encryptedKey = rsaPublic.Encrypt(symmetricKey.toByteArray(), false);

            byte[] encrypted = EncryptSymmetric(toEncrypt, symmetricKey);

            byte[] combined = new byte[2 + encryptedKey.Length + encrypted.Length];

            combined[0] = (byte)(encryptedKey.Length & 0x00FF);
            combined[1] = (byte)(encryptedKey.Length >> 8);


            for (int i = 0; i < encryptedKey.Length; i++)
            {
                combined[2 + i] = encryptedKey[i];
            }
            for (int i = 0; i < encrypted.Length; i++)
            {
                combined[2 + i + encryptedKey.Length] = encrypted[i];
            }
            return(combined);
        }
コード例 #9
0
        public static void TestInvalidArguments()
        {
            SymmetricKey key = null;

            Assert.DoesNotThrow(() =>
            {
                key = new SymmetricKey(new byte[16]);
            });
            Assert.DoesNotThrow(() =>
            {
                key = new SymmetricKey(new byte[24]);
            });
            Assert.DoesNotThrow(() =>
            {
                key = new SymmetricKey(new byte[32]);
            });

            Assert.Throws <ArgumentNullException>(() =>
            {
                key = new SymmetricKey((byte[])null);
            });

            // Use the instance to avoid FxCop errors.
            Object.Equals(key, null);
        }
コード例 #10
0
        public bool Open(String path, SymmetricKey encryptionKey = null)
        {
            if (IsOpen)
            {
                return(true);
            }

            Path    = path;
            Factory = new TaskFactory(new SingleThreadScheduler());

            try {
                shouldCommit = false;
                const int writer_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
                OpenSqliteConnection(writer_flags, encryptionKey, out _writeConnection);

                const int reader_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX;
                OpenSqliteConnection(reader_flags, encryptionKey, out _readConnection);

                if (!Decrypt(encryptionKey))
                {
                    throw new CouchbaseLiteException(StatusCode.Unauthorized);
                }
            } catch (CouchbaseLiteException) {
                Log.W(TAG, "Error opening SQLite storage engine");
                throw;
            } catch (Exception ex) {
                throw new CouchbaseLiteException("Failed to open SQLite storage engine", ex)
                      {
                          Code = StatusCode.Exception
                      };
            }

            return(true);
        }
コード例 #11
0
        public void TestUnencryptedDB()
        {
            // Create unencrypted DB:
            var options = new DatabaseOptions();

            options.Create = true;
            var seekrit = manager.OpenDatabase("seekrit", options);

            Assert.IsNotNull(seekrit, "Failed to create db");
            CreateDocumentWithProperties(seekrit, new Dictionary <string, object> {
                { "answer", 42 }
            });

            Assert.DoesNotThrow(() => seekrit.Close().Wait(15000));

            var key = new SymmetricKey(_wrong.KeyData);

            options.EncryptionKey = key;
            var e = Assert.Throws <CouchbaseLiteException>(() => seekrit = manager.OpenDatabase("seekrit", options),
                                                           "Shouldn't have been able to reopen encrypted db with wrong password");

            Assert.AreEqual(StatusCode.Unauthorized, e.Code);

            seekrit.ChangeEncryptionKey(null);
            options.EncryptionKey = null;
            seekrit = manager.OpenDatabase("seekrit", options);
            Assert.IsNotNull(seekrit, "Failed to reopen db");
            Assert.AreEqual(1, seekrit.GetDocumentCount());
        }
コード例 #12
0
        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)
                {
                }
            });
        }
コード例 #13
0
 public CommandConsumer(Type type, SymmetricKey encryptionKey)
 {
     this.Type          = type;
     this.topic         = type.GetNiceName();
     this.clientID      = Guid.NewGuid().ToString();
     this.encryptionKey = encryptionKey;
 }
コード例 #14
0
        /// <summary>
        ///     Determines which (if any) key is valid from a set of potential keys.
        /// </summary>
        /// <remarks>
        ///     Where appropriate, computes confirmations in parallel.
        /// </remarks>
        /// <param name="keyConfirmation">Key confirmation configuration.</param>
        /// <param name="verifiedOutput">Known/verified output of the function if correct key is input.</param>
        /// <param name="potentialKeys">Set of potential keys used by the sender.</param>
        /// <exception cref="ArgumentNullException">Key confirmation configuration, verified output, or potential keys is null.</exception>
        /// <exception cref="ConfigurationInvalidException">
        ///     Some aspect of configuration invalid - detailed inside exception message.
        /// </exception>
        /// <returns>Valid key, or null if none are validated as being correct.</returns>
        public static SymmetricKey ConfirmKeyFromCanary(AuthenticationConfiguration keyConfirmation,
                                                        byte[] verifiedOutput, IEnumerable <SymmetricKey> potentialKeys)
        {
            if (keyConfirmation == null)
            {
                throw new ArgumentNullException("keyConfirmation", "No configuration supplied.");
            }
            if (potentialKeys == null)
            {
                throw new ArgumentNullException("potentialKeys", "No potential keys supplied.");
            }

            Func <byte[], byte[]> validator = GetValidator(keyConfirmation, TagConstantBytes,
                                                           keyConfirmation.SerialiseDto(), verifiedOutput.Length);

            SymmetricKey preKey = null;

            Parallel.ForEach(potentialKeys, (key, state) =>
            {
                byte[] validationOut = validator(key.ConfirmationCanary);
                if (validationOut.SequenceEqual_ConstantTime(verifiedOutput))
                {
                    preKey = key;
                    // Terminate all other validation function instances - we have found the key
                    state.Stop();
                }
            });

            return(preKey);
        }
コード例 #15
0
        public bool Open(String path, bool readOnly, string schema, SymmetricKey encryptionKey)
        {
            if (IsOpen)
            {
                return(true);
            }

            Path           = path;
            _readOnly      = readOnly;
            _encryptionKey = encryptionKey;
            Factory        = new TaskFactory(new SingleThreadScheduler());

            try {
                OpenRWConnection(_readOnly);
                if (schema != null && GetVersion() == 0)
                {
                    foreach (var statement in schema.Split(';'))
                    {
                        ExecSQL(statement);
                    }
                }

                _readerConnections = new ConnectionPool(3, OpenROConnection, Close);
            } catch (CouchbaseLiteException) {
                Log.To.Database.W(TAG, "Error opening SQLite storage engine, rethrowing...");
                throw;
            } catch (Exception ex) {
                throw Misc.CreateExceptionAndLog(Log.To.Database, ex, TAG, "Failed to open SQLite storage engine");
            }

            return(true);
        }
コード例 #16
0
        public void Crypto_SymmetricKey()
        {
            SymmetricKey key = Crypto.GenerateSymmetricKey(CryptoAlgorithm.AES, 256);
            SymmetricKey copy;
            string       inputString;

            byte[] inputBytes;

            copy = new SymmetricKey(key.ToString());
            Assert.AreEqual(key.Algorithm, copy.Algorithm);
            CollectionAssert.AreEqual(key.Key, copy.Key);
            CollectionAssert.AreEqual(key.IV, copy.IV);

            inputString = "Hello World!";
            Assert.AreEqual(inputString, Crypto.DecryptString(Crypto.EncryptString(inputString, key), key));
            Assert.AreEqual(inputString, Crypto.DecryptStringWithSalt4(Crypto.EncryptStringWithSalt4(inputString, key), key));
            Assert.AreEqual(inputString, Crypto.DecryptStringWithSalt8(Crypto.EncryptStringWithSalt8(inputString, key), key));

            inputBytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            CollectionAssert.AreEqual(inputBytes, Crypto.Decrypt(Crypto.Encrypt(inputBytes, key), key));
            CollectionAssert.AreEqual(inputBytes, Crypto.DecryptWithSalt4(Crypto.EncryptWithSalt4(inputBytes, key), key));
            CollectionAssert.AreEqual(inputBytes, Crypto.DecryptWithSalt8(Crypto.EncryptWithSalt8(inputBytes, key), key));

            key = new SymmetricKey("plaintext");
            Assert.AreEqual(CryptoAlgorithm.PlainText, key.Algorithm);
            CollectionAssert.AreEqual(new byte[0], key.Key);
            CollectionAssert.AreEqual(new byte[0], key.IV);
            Assert.AreEqual("PLAINTEXT", key.ToString());
        }
コード例 #17
0
ファイル: RabbitMQServer.cs プロジェクト: szawaski/Zerra
 public RabbitMQServer(string host, SymmetricKey encryptionKey)
 {
     this.host             = host;
     this.encryptionKey    = encryptionKey;
     this.commandExchanges = new List <CommandReceiverExchange>();
     this.eventExchanges   = new List <EventReceiverExchange>();
 }
コード例 #18
0
        public override SymmetricKeyPair Exchange(System.IO.Stream stream)
        {
            //Construct a binary stream around the underlying stream.
            BinaryWriter binaryWriter = new BinaryWriter(stream);
            BinaryReader binaryReader = new BinaryReader(stream);

            //Generate an elliptic-curve Diffie-Hellman key for private use.
            ECDiffieHellmanCng local = new ECDiffieHellmanCng(keySize);

            local.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            local.HashAlgorithm         = symmetricKeyHashAlgorithm;

            //Send our ECDH public key to the other party.
            Packet.WriteBytes(binaryWriter, local.PublicKey.ToByteArray());
            binaryWriter.Flush();

            //Recieve the ECDH public key from the other party.
            ECDiffieHellmanCng remote = new ECDiffieHellmanCng(
                CngKey.Import(
                    Packet.ReadBytes(binaryReader),
                    CngKeyBlobFormat.EccPublicBlob
                    )
                );

            //Compute the shared secret using the ECDH keys transmitted.
            byte[]       sharedSecret = local.DeriveKeyMaterial(remote.PublicKey);
            SymmetricKey sharedKey    = factory.CreateKey(factory.CreateIV(sharedSecret), sharedSecret);

            //Return a keypair to the upper level, using the shared key for both directions.
            return(new SymmetricKeyPair(sharedKey, sharedKey));
        }
コード例 #19
0
        public async Task TestGetModulesIdentity_EdgeHubTest()
        {
            const string Name = "filter";

            var symmetricKey = new SymmetricKey();

            symmetricKey.PrimaryKey   = Convert.ToBase64String(Encoding.UTF8.GetBytes("primarySymmetricKey"));
            symmetricKey.SecondaryKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("secondarySymmetricKey"));

            var serviceModuleFilterIdentity = new Module("device1", Name)
            {
                Authentication = new AuthenticationMechanism
                {
                    SymmetricKey = symmetricKey
                }
            };

            var serviceModuleEdgeHubIdentity = new Module("device1", Constants.EdgeHubModuleIdentityName)
            {
                Authentication = new AuthenticationMechanism
                {
                    SymmetricKey = symmetricKey
                }
            };

            var    serviceClient   = new Mock <IServiceClient>();
            string hostname        = "hostname";
            string deviceId        = "deviceId";
            string gatewayHostName = "localhost";

            Module[] serviceIdentities = { serviceModuleFilterIdentity, serviceModuleEdgeHubIdentity };
            serviceClient.Setup(sc => sc.GetModules()).Returns(Task.FromResult(serviceIdentities.AsEnumerable()));
            serviceClient.Setup(sc => sc.CreateModules(It.Is <IEnumerable <string> >(m => !m.Any()))).Returns(Task.FromResult(new Module[0]));
            serviceClient.Setup(sc => sc.UpdateModules(It.Is <IEnumerable <Module> >(m => !m.Any()))).Returns(Task.FromResult(new Module[0]));

            var testMod    = new TestModule(Name, "v1", "test", ModuleStatus.Running, new TestConfig("image"), RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars);
            var edgeHubMod = new TestModule(Constants.EdgeHubModuleName, "v1", "test", ModuleStatus.Running, new TestConfig("image"), RestartPolicy.Always, DefaultConfigurationInfo, EnvVars);

            IImmutableDictionary <string, IModuleIdentity> modulesIdentities = await new ModuleIdentityLifecycleManager(serviceClient.Object, hostname, deviceId, gatewayHostName)
                                                                               .GetModuleIdentitiesAsync(ModuleSet.Create(testMod, edgeHubMod), ModuleSet.Empty);

            serviceClient.Verify(sc => sc.CreateModules(It.Is <IEnumerable <string> >(m => !m.Any())), Times.Once);
            serviceClient.Verify(sc => sc.UpdateModules(It.Is <IEnumerable <Module> >(m => !m.Any())), Times.Once);
            Assert.True(modulesIdentities.Count == 2);
            IModuleIdentity edgeHubModuleIdentity = modulesIdentities[Constants.EdgeHubModuleName];

            Assert.NotNull(edgeHubModuleIdentity);
            var edgeHubCreds = edgeHubModuleIdentity.Credentials as ConnectionStringCredentials;

            Assert.NotNull(edgeHubCreds);
            Assert.Equal("HostName=hostname;DeviceId=deviceId;ModuleId=$edgeHub;SharedAccessKey=cHJpbWFyeVN5bW1ldHJpY0tleQ==", edgeHubCreds.ConnectionString);

            IModuleIdentity testModuleIdentity = modulesIdentities[Name];

            Assert.NotNull(testModuleIdentity);
            var testModCreds = testModuleIdentity.Credentials as ConnectionStringCredentials;

            Assert.NotNull(testModCreds);
            Assert.Equal("HostName=hostname;DeviceId=deviceId;ModuleId=filter;SharedAccessKey=cHJpbWFyeVN5bW1ldHJpY0tleQ==;GatewayHostName=localhost", testModCreds.ConnectionString);
        }
コード例 #20
0
 public TcpRawCQRSServer(NetworkType networkType, ContentType?contentType, string serverUrl, SymmetricKey encryptionKey)
     : base(serverUrl)
 {
     this.networkType   = networkType;
     this.contentType   = contentType;
     this.encryptionKey = encryptionKey;
 }
コード例 #21
0
        /// <summary>
        /// Encrypts the committed file using the specified symmetric encryption key.
        /// </summary>
        /// <param name="key">The symmetric encryption key.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="key" /> is <c>null</c>.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the file has not been committed to the cache.</exception>
        /// <exception cref="IOException">Thrown if there's a problem reading or writing file data.</exception>
        /// <exception cref="CryptographicException">Thrown if there's any encryption failure.</exception>
        /// <remarks>
        /// <note>
        /// This method may be called only on files that have been already been committed to the cache.
        /// </note>
        /// </remarks>
        public void Encrypt(SymmetricKey key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (IsUploading)
            {
                throw new ArgumentNullException(string.Format("Cannot encrypt file [{0}] until it has been committed to the cache.", ID));
            }

            if (!File.Exists(this.Path))
            {
                throw new InvalidOperationException(string.Format("Cannot encrypt web transfer file with ID [{0}] because it does not exist.", ID));
            }

            var encryptedTempPath = this.Path + ".encrypting";

            using (var encryptor = new StreamEncryptor(key))
            {
                encryptor.Encrypt(this.Path, encryptedTempPath);
            }

            File.Delete(this.Path);
            File.Move(encryptedTempPath, this.Path);
        }
コード例 #22
0
ファイル: Manager.cs プロジェクト: z000z/couchbase-lite-net
        public bool RegisterEncryptionKey(object keyDataOrPassword, string dbName)
        {
            var realKey = default(SymmetricKey);

            if (keyDataOrPassword != null)
            {
                var password = keyDataOrPassword as string;
                if (password != null)
                {
                    realKey = new SymmetricKey(password);
                }
                else
                {
                    var keyData = keyDataOrPassword as IEnumerable <byte>;
                    Debug.Assert(keyData != null);
                    try {
                        realKey = new SymmetricKey(keyData.ToArray());
                    } catch (ArgumentOutOfRangeException) {
                        return(false);
                    }
                }
            }

            Shared.SetValue("encryptionKey", "", dbName, realKey);
            return(true);
        }
コード例 #23
0
        public static async Task <IKey> GetCustomKey(bool createKey)
        {
            RandomNumberGenerator randomNumberGenerator;

            byte[] keyRnd = new byte[64]; //512 bits


            if (createKey)
            {
                //Génére la clé
                randomNumberGenerator = RandomNumberGenerator.Create();
                randomNumberGenerator.GetBytes(keyRnd);

                var protectData = ProtectedData.Protect(keyRnd, null, DataProtectionScope.CurrentUser);
                File.WriteAllBytes("dtkey.bin", protectData);
            }
            else
            {
                var protectData = File.ReadAllBytes("dtkey.bin");
                keyRnd = ProtectedData.Unprotect(protectData, null, DataProtectionScope.CurrentUser);
            }
            SymmetricKey symKey = new SymmetricKey("private:key1", keyRnd);

            return(symKey);
        }
コード例 #24
0
        public void SecureTicket_ClientClock()
        {
            DateTime     now = DateTime.UtcNow;
            SymmetricKey key = new SymmetricKey("aes:Cz1uS3EYB5aLDgXdKKmzGPnMU3/QwK1i+8nY3KuUaCw=:Toel2ZQR6TBtOvq+zatyoA==");
            SecureTicket ticket;
            string       encrypted;

            ticket = new SecureTicket("my-resource", TimeSpan.FromSeconds(100));
            ticket.Set("arg0", "myarg-0");
            ticket.Set("arg1", "myarg-1");
            ticket["arg2"] = "myarg-2";

            Thread.Sleep(5000);     // Simulate clock skew between the issuer and client

            encrypted = ticket.ToBase64String(key);
            ticket    = SecureTicket.Parse(key, encrypted);

            Assert.AreEqual("my-resource", ticket.Resource);
            Assert.AreEqual(TimeSpan.FromSeconds(100), ticket.Lifespan);
            Assert.IsTrue(Helper.Within(now + TimeSpan.FromSeconds(100), ticket.IssuerExpirationUtc, delta));
            Assert.IsTrue(Helper.Within(now + TimeSpan.FromSeconds(105), ticket.ClientExpirationUtc, delta));
            Assert.AreEqual("myarg-0", ticket["arg0"]);
            Assert.AreEqual("myarg-1", ticket["arg1"]);
            Assert.AreEqual("myarg-2", ticket["arg2"]);
            Assert.AreEqual("myarg-0", ticket.Get("arg0", "hello"));
            Assert.AreEqual("hello", ticket.Get("XXXX", "hello"));
        }
コード例 #25
0
        public BlobStore(string path, SymmetricKey encryptionKey)
        {
            if (path == null)
            {
                Log.To.Database.E(TAG, "path cannot be null in ctor, throwing...");
                throw new ArgumentNullException("path");
            }

            _path         = path;
            EncryptionKey = encryptionKey;
            if (Directory.Exists(path))
            {
                // Existing blob-store.
                VerifyExistingStore();
            }
            else
            {
                // New blob store; create directory:
                Directory.CreateDirectory(path);
                if (!Directory.Exists(path))
                {
                    Log.To.Database.E(TAG, "Unable to create directory for: {0}", path);
                    throw new InvalidOperationException(string.Format("Unable to create directory for: {0}", path));
                }

                if (encryptionKey != null)
                {
                    MarkEncrypted(true);
                }
            }
        }
コード例 #26
0
        public async Task TestGetModulesIdentity_WithUpdatedModules_HasAccessKey_ShouldNotUpdate()
        {
            const string Name = "test-filters";

            var serviceModuleIdentity = new Module("device1", Name);

            serviceModuleIdentity.Authentication = new AuthenticationMechanism();
            var symmetricKey = new SymmetricKey();

            symmetricKey.PrimaryKey   = Convert.ToBase64String(Encoding.UTF8.GetBytes("primarySymmetricKey"));
            symmetricKey.SecondaryKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("secondarySymmetricKey"));

            serviceModuleIdentity.Authentication.SymmetricKey = symmetricKey;

            var    serviceClient   = new Mock <IServiceClient>();
            string hostname        = "hostname";
            string deviceId        = "deviceId";
            string gatewayHostName = "localhost";

            Module[] serviceIdentities = { serviceModuleIdentity };
            serviceClient.Setup(sc => sc.GetModules()).Returns(Task.FromResult(serviceIdentities.AsEnumerable()));
            serviceClient.Setup(sc => sc.CreateModules(It.Is <IEnumerable <string> >(m => !m.Any()))).Returns(Task.FromResult(new Module[0]));
            serviceClient.Setup(sc => sc.UpdateModules(It.Is <IEnumerable <Module> >(m => !m.Any()))).Returns(Task.FromResult(new Module[0]));

            var module = new TestModule(Name, "v1", "test", ModuleStatus.Running, new TestConfig("image"), RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars);

            IImmutableDictionary <string, IModuleIdentity> modulesIdentities = await new ModuleIdentityLifecycleManager(serviceClient.Object, hostname, deviceId, gatewayHostName)
                                                                               .GetModuleIdentitiesAsync(ModuleSet.Create(module), ModuleSet.Empty);

            serviceClient.Verify(sc => sc.CreateModules(It.Is <IEnumerable <string> >(m => !m.Any())), Times.Once);
            serviceClient.Verify(sc => sc.UpdateModules(It.Is <IEnumerable <Module> >(m => !m.Any())), Times.Once);
            Assert.True(modulesIdentities.Count == 1);
        }
コード例 #27
0
        public void CloudQueueMessageValidateEncryption()
        {
            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            CloudQueueClient client = GenerateCloudQueueClient();
            string           name   = GenerateNewQueueName();
            CloudQueue       queue  = client.GetQueueReference(name);

            try
            {
                queue.CreateIfNotExists();

                byte[] messageBytes = new byte[100];
                Random rand         = new Random();
                rand.NextBytes(messageBytes);

                string            inputMessage = Convert.ToBase64String(messageBytes);
                CloudQueueMessage message      = new CloudQueueMessage(inputMessage);
                queue.EncodeMessage = false;

                QueueEncryptionPolicy policy  = new QueueEncryptionPolicy(aesKey, null);
                QueueRequestOptions   options = new QueueRequestOptions()
                {
                    EncryptionPolicy = policy
                };

                // Add message
                queue.AddMessage(message, null, null, options, null);

                // Retrieve message without decrypting
                CloudQueueMessage retrMessage = queue.GetMessage(null, null, null);

                // Decrypt locally
                CloudQueueMessage          decryptedMessage;
                CloudQueueEncryptedMessage encryptedMessage = JsonConvert.DeserializeObject <CloudQueueEncryptedMessage>(retrMessage.AsString);
                EncryptionData             encryptionData   = encryptedMessage.EncryptionData;

                byte[] contentEncryptionKey = aesKey.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, CancellationToken.None).Result;

                using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                {
                    myAes.Key = contentEncryptionKey;
                    myAes.IV  = encryptionData.ContentEncryptionIV;

                    byte[] src = Convert.FromBase64String(encryptedMessage.EncryptedMessageContents);
                    using (ICryptoTransform decryptor = myAes.CreateDecryptor())
                    {
                        decryptedMessage = new CloudQueueMessage(decryptor.TransformFinalBlock(src, 0, src.Length));
                    }
                }

                TestHelper.AssertBuffersAreEqual(message.AsBytes, decryptedMessage.AsBytes);
            }
            finally
            {
                queue.DeleteIfExists();
            }
        }
コード例 #28
0
 public byte[] SymmetricDecrypt(CipherText cipher, SymmetricKey symmetricKey)
 {
     _cipher.Init(
         false,
         new ParametersWithIV(
             new KeyParameter(symmetricKey), Iv));
     return(_cipher.DoFinal(cipher));
 }
コード例 #29
0
 public CipherText SymmetricEncrypt(byte[] bytes, SymmetricKey symmetricKey)
 {
     _cipher.Init(
         true,
         new ParametersWithIV(
             new KeyParameter(symmetricKey), Iv));
     return(new CipherText(_cipher.DoFinal(bytes)));
 }
コード例 #30
0
        public void ByteArray()
        {
            var aes = new SymmetricKey(KeyBytes);
            ImmutableArray <byte> expected = KeyBytes.ToImmutableArray();
            ImmutableArray <byte> actual   = aes.ByteArray;

            Assert.Equal <byte>(expected, actual);
        }
コード例 #31
0
        public bool TryGetKey(string id, out SymmetricKey key)
        {
            TestSymmetricKey symmetricKey;
            bool found = _keys.TryGetValue(id, out symmetricKey);
            if (found)
            {
                key = symmetricKey;
                return true;
            }

            key = null;
            return false;
        }
コード例 #32
0
 public bool TryGetKey(string id, out SymmetricKey key)
 {
     key = _key;
     return true;
 }