Exemple #1
0
        public async Task EncryptLocalDecryptOnKeyVault([EnumValues(nameof(EncryptionAlgorithm.Rsa15), nameof(EncryptionAlgorithm.RsaOaep), nameof(EncryptionAlgorithm.RsaOaep256))] EncryptionAlgorithm algorithm)
        {
            KeyVaultKey key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient remoteClient = GetCryptoClient(key.Id, forceRemote: true);
            CryptographyClient localClient  = GetLocalCryptoClient(key.Key);

            byte[] plaintext = new byte[32];
            Recording.Random.NextBytes(plaintext);

            EncryptResult encrypted = await localClient.EncryptAsync(algorithm, plaintext);

            Assert.AreEqual(algorithm, encrypted.Algorithm);
            Assert.AreEqual(key.Id, encrypted.KeyId);
            Assert.IsNotNull(encrypted.Ciphertext);

            DecryptResult decrypted = await remoteClient.DecryptAsync(algorithm, encrypted.Ciphertext);

            Assert.AreEqual(algorithm, decrypted.Algorithm);
            Assert.AreEqual(key.Id, decrypted.KeyId);
            Assert.IsNotNull(decrypted.Plaintext);

            CollectionAssert.AreEqual(plaintext, decrypted.Plaintext);
        }
        public async Task EncryptDecryptRoundTrip([Fields] EncryptionAlgorithm algorithm)
        {
            Key key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true);

            byte[] data = new byte[32];
            Recording.Random.NextBytes(data);

            EncryptResult encResult = await cryptoClient.EncryptAsync(algorithm, data);

            Assert.AreEqual(algorithm, encResult.Algorithm);
            Assert.AreEqual(key.Id, encResult.KeyId);
            Assert.IsNotNull(encResult.Ciphertext);

            DecryptResult decResult = await cryptoClient.DecryptAsync(algorithm, encResult.Ciphertext);

            Assert.AreEqual(algorithm, decResult.Algorithm);
            Assert.AreEqual(key.Id, decResult.KeyId);
            Assert.IsNotNull(decResult.Plaintext);

            CollectionAssert.AreEqual(data, decResult.Plaintext);
        }
Exemple #3
0
        static void Main(string[] args)
        {
            string keyVaultUrl = "https://demovault2090.vault.azure.net/";
            var    client      = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Getting the Encryption key from the key vault
            KeyVaultKey key = client.GetKey("newkey");

            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential());

            byte[] plaintext = Encoding.UTF8.GetBytes("This is sensitive data");

            // Encrypting data
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep256, plaintext);

            //Decrypting data
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, encryptResult.Ciphertext);

            Console.WriteLine("Plain text");

            string txt = Encoding.UTF8.GetString(decryptResult.Plaintext);

            Console.WriteLine(txt);
            Console.ReadLine();
        }
        public void Test_Attachment_DecryptFailOnBadKey()
        {
            string?cipherFile          = null;
            bool   hitCorrectException = false;

            try
            {
                byte[]        key            = Util.GetSecretBytes(64);
                byte[]        plaintextInput = Encoding.UTF8.GetBytes("Gwen Stacy");
                EncryptResult encryptResult  = EncryptData(plaintextInput, key);
                byte[]        badKey         = new byte[64];

                cipherFile = WriteToFile(encryptResult.ciphertext);

                using FileStream fileStream = File.Open(cipherFile, FileMode.Open);
                AttachmentCipherInputStream.CreateForAttachment(fileStream, plaintextInput.Length, badKey, encryptResult.digest);
            }
            catch (InvalidMessageException)
            {
                hitCorrectException = true;
            }
            finally
            {
                if (cipherFile != null)
                {
                    DeleteFile(cipherFile);
                }
            }

            Assert.IsTrue(hitCorrectException);
        }
Exemple #5
0
    static void Main(string[] args)
    {
        string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
        string inputValue        = "MyTest";
        string keyValue          = valid128BitString;

        //Turns our text in to binary data
        byte[] byteValForString = Encoding.UTF8.GetBytes(inputValue);

        EncryptResult result        = Aes128Utility.EncryptData(byteValForString, keyValue);
        EncryptResult encyptedValue = new EncryptResult();

        //(Snip)

        encyptedValue.IV           = resultingIV;
        encyptedValue.EncryptedMsg = result.EncryptedMsg;

        string finalResult = Encoding.UTF8.GetString(Aes128Utility.DecryptData(encyptedValue, keyValue));

        Console.WriteLine(finalResult);

        if (String.Equals(inputValue, finalResult))
        {
            Console.WriteLine("Match");
        }
        else
        {
            Console.WriteLine("Differ");
        }

        Console.ReadLine();
    }
Exemple #6
0
        public void InitializesIv(EncryptionAlgorithm algorithm)
        {
            // Use a 256-bit key which will be truncated based on the selected algorithm.
            byte[] k = new byte[] { 0xe2, 0x7e, 0xd0, 0xc8, 0x45, 0x12, 0xbb, 0xd5, 0x5b, 0x6a, 0xf4, 0x34, 0xd2, 0x37, 0xc1, 0x1f, 0xeb, 0xa3, 0x11, 0x87, 0x0f, 0x80, 0xf2, 0xc2, 0xe3, 0x36, 0x42, 0x60, 0xf3, 0x1c, 0x82, 0xc8 };

            JsonWebKey key = new JsonWebKey(new[] { KeyOperation.Encrypt, KeyOperation.Decrypt })
            {
                K = k,
            };

            AesCryptographyProvider provider = new AesCryptographyProvider(key, null);

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

            EncryptOptions encryptOptions = new EncryptOptions(algorithm, plaintext, null, null);
            EncryptResult  encrypted      = provider.Encrypt(encryptOptions, default);

            Assert.IsNotNull(encryptOptions.Iv);
            CollectionAssert.AreEqual(encryptOptions.Iv, encrypted.Iv);

            DecryptOptions decryptOptions = new DecryptOptions(algorithm, encrypted.Ciphertext, encrypted.Iv);
            DecryptResult  decrypted      = provider.Decrypt(decryptOptions, default);

            Assert.IsNotNull(decrypted);

            // AES-CBC will be zero-padded.
            StringAssert.StartsWith("plaintext", Encoding.UTF8.GetString(decrypted.Plaintext));
        }
        //public string GatewayName = "Premium Payment Gateway";


        public async Task <string> EncryptStringAsync(CryptographyClient cryptoClient, string input)
        {
            byte[] inputAsByteArray = Encoding.UTF8.GetBytes(input);

            EncryptResult encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, inputAsByteArray).ConfigureAwait(false);

            return(Convert.ToBase64String(encryptResult.Ciphertext));
        }
Exemple #8
0
 /// <summary>
 /// Encrypt an image message.
 /// </summary>
 /// <param name="encryptResult">result of the image encryption</param>
 /// <param name="uploadResult">result of the upload</param>
 /// <param name="senderPrivateKey">the private key of the sending ID</param>
 /// <param name="recipientPublicKey">the public key of the receiving ID</param>
 /// <returns>encrypted result</returns>
 public static EncryptResult EncryptImageMessage(EncryptResult encryptResult, UploadResult uploadResult, byte[] senderPrivateKey, byte[] recipientPublicKey)
 {
     return(EncryptMessage(
                new ImageMessage(uploadResult.BlobId,
                                 encryptResult.Size,
                                 encryptResult.Nonce),
                senderPrivateKey,
                recipientPublicKey));
 }
Exemple #9
0
        /// <summary>
        /// Upload a file.
        /// </summary>
        /// <param name="fileEncryptionResult">The result of the file encryption (i.e. encrypted file data)</param>
        /// <returns>the result of the upload</returns>
        public UploadResult UploadFile(EncryptResult fileEncryptionResult)
        {
            string attachmentName     = "blob";
            string attachmentFileName = "blob.file";
            string crlf       = "\r\n";
            string twoHyphens = "--";

            char[] chars    = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
            string boundary = string.Empty;
            Random rand     = new Random();
            int    count    = rand.Next(11) + 30;

            for (int i = 0; i < count; i++)
            {
                boundary += chars[rand.Next(chars.Length)];
            }

            byte[] header = Encoding.UTF8.GetBytes(twoHyphens + boundary + crlf +
                                                   "Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf + crlf
                                                   );
            byte[] footer   = Encoding.UTF8.GetBytes(crlf + twoHyphens + boundary + twoHyphens + crlf);
            byte[] postData = new byte[header.Length + fileEncryptionResult.Result.Length + footer.Length];

            header.CopyTo(postData, 0);
            fileEncryptionResult.Result.CopyTo(postData, header.Length);
            footer.CopyTo(postData, header.Length + fileEncryptionResult.Result.Length);

            string queryString = MakeUrlEncoded(MakeRequestParams());
            Uri    url         = new Uri(this.apiUrl + "upload_blob?" + queryString);

            WebRequest request = WebRequest.CreateHttp(url);

            request.Method = "POST";

            if (!WebHeaderCollection.IsRestricted("Connection"))
            {
                request.Headers.Set(HttpRequestHeader.Connection, "Keep-Alive");
            }
            if (!WebHeaderCollection.IsRestricted("CacheControl"))
            {
                request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
            }

            request.ContentType   = "multipart/form-data;boundary=" + boundary;
            request.ContentLength = postData.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(postData, 0, postData.Length);
                stream.Close();
            }

            string         responseData;
            HttpStatusCode responseCode = GetResponse(request, out responseData);

            return(new UploadResult((int)responseCode, responseData != null ? DataUtils.HexStringToByteArray(responseData) : null));
        }
        public async Task DecryptRequiresPrivateKey()
        {
            JsonWebKey jwk = CreateKey(KeyType.Rsa, keyOps: new[] { KeyOperation.Encrypt, KeyOperation.Decrypt });
            LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk);

            EncryptResult encrypted = await client.EncryptAsync(EncryptionAlgorithm.RsaOaep, TestData);

            Assert.ThrowsAsync(new InstanceOfTypeConstraint(typeof(CryptographicException)), async() => await client.DecryptAsync(EncryptionAlgorithm.RsaOaep, encrypted.Ciphertext));
        }
Exemple #11
0
        public void EncryptDecryptSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a RSA key which will be used to encrypt and decrypt
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");

            // Let's create the CryptographyClient which can perform cryptographic operations with the key we just created.
            // Again we are using the default Azure credential as above.
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());

            // Next we'll encrypt some arbitrary plain text with the key using the CryptographyClient. Note that RSA encryption
            // algorithms have no chaining so they can only encrypt a single block of plaintext securely. For RSAOAEP this can be
            // calculated as (keysize / 8) - 42, or in our case (2048 / 8) - 42 = 214 bytes.
            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // First encrypt the data using RSAOAEP with the created key.
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

            Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}");

            // Now decrypt the encrypted data. Note that the same algorithm must always be used for both encrypt and decrypt
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

            Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}");

            // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

            // To ensure the key is deleted on server before we try to purge it.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
        public void Test_Sticker_EncryptDecryptEmpty()
        {
            byte[]        packKey        = Util.GetSecretBytes(32);
            byte[]        plaintextInput = Encoding.UTF8.GetBytes(string.Empty);
            EncryptResult encryptResult  = EncryptData(plaintextInput, ExpandPackKey(packKey));

            using Stream inputStream = AttachmentCipherInputStream.CreateForStickerData(encryptResult.ciphertext, packKey);
            byte[] plaintextOutput = ReadInputStreamFully(inputStream);

            CollectionAssert.AreEqual(plaintextInput, plaintextOutput);
        }
        public void EncryptDecrypt()
        {
            #region Snippet:EncryptDecrypt
            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // encrypt the data using the algorithm RSAOAEP
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

            // decrypt the encrypted data.
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);
            #endregion
        }
        public IActionResult Get()
        {
            BlowFish      blowFish      = new BlowFish("@dm1n1z7r@t0r!!!");
            EncryptResult encryptResult = new EncryptResult();

            encryptResult.serverName = blowFish.Encrypt_CBC("localhost");
            encryptResult.dbName     = blowFish.Encrypt_CBC("DatingApp");
            encryptResult.userName   = blowFish.Encrypt_CBC("sa");
            encryptResult.password   = blowFish.Encrypt_CBC("password1");

            return(Ok(encryptResult));
        }
Exemple #15
0
        public string Encode(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(value));
            }

            byte[]        valueByteArray = Encoding.UTF8.GetBytes(value);
            EncryptResult encryptResult  = _cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, valueByteArray);

            return(Convert.ToBase64String(encryptResult.Ciphertext));
        }
        public void OctEncryptDecryptSync()
        {
            TestEnvironment.AssertManagedHsm();

            string managedHsmUrl = TestEnvironment.ManagedHsmUrl;

            #region Snippet:OctKeysSample4CreateKey
            var managedHsmClient = new KeyClient(new Uri(managedHsmUrl), new DefaultAzureCredential());

            var octKeyOptions = new CreateOctKeyOptions($"CloudOctKey-{Guid.NewGuid()}")
            {
                KeySize = 256,
            };

            KeyVaultKey cloudOctKey = managedHsmClient.CreateOctKey(octKeyOptions);
            #endregion

            #region Snippet:OctKeySample4Encrypt
            var cryptoClient = new CryptographyClient(cloudOctKey.Id, new DefaultAzureCredential());

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");
            byte[] aad       = Encoding.UTF8.GetBytes("additional authenticated data");

            EncryptParameters encryptParams = EncryptParameters.A256GcmParameters(plaintext, aad);
            EncryptResult     encryptResult = cryptoClient.Encrypt(encryptParams);
            #endregion

            #region Snippet:OctKeySample4Decrypt
            DecryptParameters decryptParams = DecryptParameters.A256GcmParameters(
                encryptResult.Ciphertext,
                encryptResult.Iv,
                encryptResult.AuthenticationTag,
                encryptResult.AdditionalAuthenticatedData);

            DecryptResult decryptResult = cryptoClient.Decrypt(decryptParams);
            #endregion

            Assert.AreEqual(plaintext, decryptResult.Plaintext);

            // Delete and purge the key.
            DeleteKeyOperation operation = managedHsmClient.StartDeleteKey(octKeyOptions.Name);

            // You only need to wait for completion if you want to purge or recover the key.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }

            managedHsmClient.PurgeDeletedKey(operation.Value.Name);
        }
Exemple #17
0
        /// <summary>
        /// Encrypt a text message and send it to the given recipient.
        /// </summary>
        /// <param name="threemaId">target Threema ID</param>
        /// <param name="text">the text to send</param>
        /// <returns>generated message ID</returns>
        public string SendTextMessage(string threemaId, string text)
        {
            //fetch public key
            byte[] publicKey = this.apiConnector.LookupKey(threemaId);

            if (publicKey == null)
            {
                throw new InvalidKeyException("invalid threema id");
            }
            EncryptResult res = CryptTool.EncryptTextMessage(text, this.privateKey, publicKey);

            return(this.apiConnector.SendE2EMessage(threemaId, res.Nonce, res.Result));
        }
        public async Task EncryptDecryptRoundtrip([EnumValues(nameof(EncryptionAlgorithm.Rsa15), nameof(EncryptionAlgorithm.RsaOaep))] EncryptionAlgorithm algorithm)
        {
            JsonWebKey jwk = CreateKey(KeyType.Rsa, includePrivateParameters: true);
            LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk);

            EncryptResult encrypted = await client.EncryptAsync(algorithm, TestData);

            DecryptResult decrypted = await client.DecryptAsync(algorithm, encrypted.Ciphertext);

            string actual = Encoding.UTF8.GetString(decrypted.Plaintext);

            Assert.AreEqual("test", actual);
        }
Exemple #19
0
        public override async Task SetupAsync()
        {
            await base.SetupAsync();

            // Generate new plaintext with each iteration to avoid potential caching of results.
            _plaintext = new byte[32];
            Random.NextBytes(_plaintext);

            // CryptographyClient caches the public key so encrypting now removes the initial request from metrics.
            EncryptResult result = await CryptographyClient.EncryptAsync(s_algorithm, _plaintext);

            _ciphertext = result.Ciphertext;
        }
Exemple #20
0
        public void EncryptDecryptSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            #region Snippet:KeysSample4KeyClient
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample4CreateKey
            // Let's create a RSA key which will be used to encrypt and decrypt
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey);
            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");
            #endregion

            #region Snippet:KeysSample4CryptographyClient
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample4EncryptKey
            byte[]        plaintext     = Encoding.UTF8.GetBytes("A single block of plaintext");
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);
            Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}");
            #endregion

            #region Snippet:KeysSample4DecryptKey
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);
            Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}");
            #endregion

            #region Snippet:KeysSample4DeleteKey
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }
            #endregion

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
        public void Test_Attachment_EncryptDecryptEmpty()
        {
            byte[]        key            = Util.GetSecretBytes(64);
            byte[]        plaintextInput = Encoding.UTF8.GetBytes(string.Empty);
            EncryptResult encryptResult  = EncryptData(plaintextInput, key);
            string        cipherFile     = WriteToFile(encryptResult.ciphertext);

            using Stream inputStream = AttachmentCipherInputStream.CreateForAttachment(File.Open(cipherFile, FileMode.Open), plaintextInput.Length, key, encryptResult.digest);
            byte[] plaintextOutput = ReadInputStreamFully(inputStream);

            CollectionAssert.AreEqual(plaintextInput, plaintextOutput);

            DeleteFile(cipherFile);
        }
        protected override void Execute()
        {
            byte[] privateKey = this.privateKeyField.GetValue();
            byte[] publicKey  = this.publicKeyField.GetValue();

            /* read text from stdin */
            //string text = ReadStream(System.Console.In).Trim();
            string text = DataUtils.Utf8Endcode(System.Console.ReadLine().Trim());

            EncryptResult res = CryptTool.EncryptTextMessage(text, privateKey, publicKey);

            System.Console.WriteLine(DataUtils.ByteArrayToHexString(res.Nonce));
            System.Console.WriteLine(DataUtils.ByteArrayToHexString(res.Result));
        }
Exemple #23
0
        public void TestEncrypt()
        {
            string text = "Dies ist eine Testnachricht. äöü";

            Key privateKey = Key.DecodeKey(Common.myPrivateKey);
            Key publicKey  = Key.DecodeKey(Common.otherPublicKey);

            EncryptResult res = CryptTool.EncryptTextMessage(text, privateKey.key, publicKey.key);

            Assert.IsNotNull(res);
            Assert.IsNotNull(res.Nonce);
            Assert.IsNotNull(res.Result);
            Assert.IsFalse(res.Nonce.SequenceEqual(new byte[res.Nonce.Length]));
            Assert.IsFalse(res.Result.SequenceEqual(new byte[res.Result.Length]));
        }
Exemple #24
0
        /// <summary>
        /// Wrapper to encrypt text <see cref="Threema.MsgApi.CryptTool.EncryptTextMessage"/>
        /// </summary>
        /// <param name="text">Text to encrypt</param>
        /// <param name="senderPrivateKey">Sender private key as hex-string</param>
        /// <param name="recipientPublicKey">Recipient public key as hex-string</param>
        /// <returns>Array with encrypted text, nonce and size</returns>
        public ArrayList EncryptTextMessage(string text, string senderPrivateKey, string recipientPublicKey)
        {
            byte[] privateKey = GetKey(senderPrivateKey, Key.KeyType.PRIVATE);
            byte[] publicKey  = GetKey(recipientPublicKey, Key.KeyType.PUBLIC);

            string textEncoded = DataUtils.Utf8Endcode(text);

            EncryptResult encryptResult = CryptTool.EncryptTextMessage(textEncoded, privateKey, publicKey);

            var result = new ArrayList();

            result.Add(DataUtils.ByteArrayToHexString(encryptResult.Result));
            result.Add(DataUtils.ByteArrayToHexString(encryptResult.Nonce));
            result.Add(encryptResult.Size.ToString());
            return(result);
        }
Exemple #25
0
        public async Task EncryptDecryptFromKeyClient()
        {
            KeyVaultKey key = await CreateTestKey(EncryptionAlgorithm.RsaOaep);

            RegisterForCleanup(key.Name);

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // Make sure the same (instrumented) pipeline is used from the KeyClient.
            CryptographyClient cryptoClient  = Client.GetCryptographyClient(key.Name, key.Properties.Version);
            EncryptResult      encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, plaintext);

            DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

            Assert.AreEqual(plaintext, decryptResult.Plaintext);
        }
        public async Task <IActionResult> Encrypt(EncryptDto toEncrypt)
        {
            byte[] toEncryptInBytes = Encoding.UTF8.GetBytes(toEncrypt.Payload);

            if (toEncryptInBytes.Length > 245)
            {
                return(BadRequest());
            }

            KeyVaultKey key = await _keyClient.GetKeyAsync("test");

            CryptographyClient crypto = new CryptographyClient(key.Id, new DefaultAzureCredential());

            EncryptResult result = await crypto.EncryptAsync(EncryptionAlgorithm.RsaOaep256, toEncryptInBytes);

            return(new OkObjectResult(Convert.ToBase64String(result.Ciphertext)));
        }
        public void Test_Attachment_EncryptDecryptMultipleTimes()
        {
            // Test that the file passed to AttachmentCipherInputStream can be reused.
            byte[]        key            = Util.GetSecretBytes(64);
            byte[]        plaintextInput = Encoding.UTF8.GetBytes("Peter Parker");
            EncryptResult encryptResult  = EncryptData(plaintextInput, key);
            string        cipherFile     = WriteToFile(encryptResult.ciphertext);

            for (int i = 0; i < 10; i++)
            {
                using Stream inputStream = AttachmentCipherInputStream.CreateForAttachment(File.Open(cipherFile, FileMode.Open), plaintextInput.Length, key, encryptResult.digest);
                byte[] plaintextOutput = ReadInputStreamFully(inputStream);

                CollectionAssert.AreEqual(plaintextInput, plaintextOutput);
            }

            DeleteFile(cipherFile);
        }
Exemple #28
0
        public async Task EncryptWithKeyNameReturnsFullKeyId()
        {
            KeyVaultKey key = await CreateTestKey(EncryptionAlgorithm.RsaOaep);

            RegisterForCleanup(key.Name);

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            Uri keyId = new UriBuilder(Client.VaultUri)
            {
                Path = KeyClient.KeysPath + key.Name,
            }.Uri;

            CryptographyClient client    = GetCryptoClient(keyId, forceRemote: true);
            EncryptResult      encrypted = await client.EncryptAsync(EncryptionAlgorithm.RsaOaep, plaintext);

            Assert.AreEqual(key.Id.ToString(), encrypted.KeyId);
        }
Exemple #29
0
 /// <summary>
 /// Encrypt a file message.
 /// </summary>
 /// <param name="encryptResult">result of the file data encryption</param>
 /// <param name="uploadResult">result of the upload</param>
 /// <param name="mimeType">MIME type of the file</param>
 /// <param name="fileName">File name</param>
 /// <param name="fileSize">Size of the file, in bytes</param>
 /// <param name="uploadResultThumbnail">result of thumbnail upload</param>
 /// <param name="senderPrivateKey">Private key of sender</param>
 /// <param name="recipientPublicKey">Public key of recipient</param>
 /// <returns>Result of the file message encryption (not the same as the file data encryption!)</returns>
 public static EncryptResult EncryptFileMessage(EncryptResult encryptResult,
                                                UploadResult uploadResult,
                                                String mimeType,
                                                String fileName,
                                                int fileSize,
                                                UploadResult uploadResultThumbnail,
                                                byte[] senderPrivateKey, byte[] recipientPublicKey)
 {
     return(EncryptMessage(
                new FileMessage(uploadResult.BlobId,
                                encryptResult.Secret,
                                mimeType,
                                fileName,
                                fileSize,
                                uploadResultThumbnail != null ? uploadResultThumbnail.BlobId : null),
                senderPrivateKey,
                recipientPublicKey));
 }
        public void EncryptDecrypt()
        {
            #region Snippet:EncryptDecrypt
#if SNIPPET
            // Create a new cryptography client using the same Key Vault or Managed HSM endpoint, service version,
            // and options as the KeyClient created earlier.
            var cryptoClient = client.GetCryptographyClient(key.Name, key.Properties.Version);
#endif

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // encrypt the data using the algorithm RSAOAEP
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

            // decrypt the encrypted data.
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);
            #endregion
        }