Пример #1
0
        //String strMsg = "1234567812345678";     // Data to encrypt.
        //String strAlgName = SymmetricAlgorithmNames.AesCbc;
        //UInt32 keyLength = 32;                  // Length of the key, in bytes
        //BinaryStringEncoding encoding;          // Binary encoding value
        //IBuffer iv;                             // Initialization vector
        //CryptographicKey key;

        public async Task EncryptFileAes(FileItemViewModel fileToEncrypt)
        {
            if (!fileToEncrypt.IsEncrypted)
            {
                var fileBuffer = await FileIO.ReadBufferAsync(fileToEncrypt.File);

                CreateNonce(fileToEncrypt);
                EncryptedAndAuthenticatedData encryptedData = CryptographicEngine.EncryptAndAuthenticate(aesKey, fileBuffer, fileToEncrypt.Nonce,
                                                                                                         null);

                var serialData = new SerialisableAuthData(encryptedData.AuthenticationTag, encryptedData.EncryptedData);

                XmlSerializer serializer = new XmlSerializer(typeof(SerialisableAuthData));
                using (Stream stream = await fileToEncrypt.File.OpenStreamForWriteAsync())
                {
                    TextWriter output = new StreamWriter(stream);
                    serializer.Serialize(output, serialData);
                    await stream.FlushAsync();

                    output.Dispose();
                    stream.Dispose();
                }
                fileToEncrypt.IsEncrypted = true;
            }
            else
            {
                throw new Exception("Tried to encrypt file with encrypted flag already set to true");
            }
        }
Пример #2
0
        // Encryption and authentication method for recipient
        private void AuthenticatedEncryptionRecipient(
            String strMsg,
            String strAlgName,
            UInt32 keyLength)
        {
            // Open a SymmetricKeyAlgorithmProvider object for the specified algorithm.
            SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Create a buffer that contains the data to be encrypted.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Generate a symmetric key.
            keyMaterialRecipient       = CryptographicBuffer.GenerateRandom(keyLength);
            keyMaterialStringRecipient = CryptographicBuffer.EncodeToBase64String(keyMaterialRecipient);
            keyRecipient = objAlgProv.CreateSymmetricKey(keyMaterialRecipient);

            // Generate a new nonce value.
            buffNonceRecipient = GetNonce();

            // Encrypt and authenticate the message.
            EncryptedAndAuthenticatedData objEncrypted = CryptographicEngine.EncryptAndAuthenticate(
                keyRecipient,
                buffMsg,
                buffNonceRecipient,
                null);

            encryptedMessageDataRecipient       = objEncrypted.EncryptedData;
            authenticationTagRecipient          = objEncrypted.AuthenticationTag;
            encryptedMessageDataStringRecipient = CryptographicBuffer.EncodeToBase64String(encryptedMessageDataRecipient);
            authenticationTagStringRecipient    = CryptographicBuffer.EncodeToBase64String(authenticationTagRecipient);
            nonceStringRecipient = CryptographicBuffer.EncodeToBase64String(buffNonceRecipient);
        }
Пример #3
0
        /// <summary>
        /// This is the click handler for the 'RunSample' button.  It is responsible for executing the sample code.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RunSample_Click(object sender, RoutedEventArgs e)
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();
            UInt32 keySize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString());

            Scenario6Text.Text = "";

            IBuffer Decrypted;
            IBuffer Data;
            IBuffer Nonce;
            String  Cookie = "Some Cookie to Encrypt";

            // Data to encrypt.
            Data = CryptographicBuffer.ConvertStringToBinary(Cookie, BinaryStringEncoding.Utf16LE);

            // Created a SymmetricKeyAlgorithmProvider object for the algorithm specified on input.
            SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algName);

            Scenario6Text.Text += "*** Sample Authenticated Encryption\n";
            Scenario6Text.Text += "    Algorithm Name: " + Algorithm.AlgorithmName + "\n";
            Scenario6Text.Text += "    Key Size: " + keySize + "\n";
            Scenario6Text.Text += "    Block length: " + Algorithm.BlockLength + "\n";

            // Generate a random key.
            IBuffer          keymaterial = CryptographicBuffer.GenerateRandom((keySize + 7) / 8);
            CryptographicKey key         = Algorithm.CreateSymmetricKey(keymaterial);


            // Microsoft GCM implementation requires a 12 byte Nonce.
            // Microsoft CCM implementation requires a 7-13 byte Nonce.
            Nonce = GetNonce();

            // Encrypt and create an authenticated tag on the encrypted data.
            EncryptedAndAuthenticatedData Encrypted = CryptographicEngine.EncryptAndAuthenticate(key, Data, Nonce, null);

            Scenario6Text.Text += "    Plain text: " + Data.Length + " bytes\n";
            Scenario6Text.Text += "    Encrypted: " + Encrypted.EncryptedData.Length + " bytes\n";
            Scenario6Text.Text += "    AuthTag: " + Encrypted.AuthenticationTag.Length + " bytes\n";

            // Create another instance of the key from the same material.
            CryptographicKey key2 = Algorithm.CreateSymmetricKey(keymaterial);

            if (key.KeySize != key2.KeySize)
            {
                Scenario6Text.Text += "CreateSymmetricKey failed!  The imported key's size did not match the original's!";
                return;
            }

            // Decrypt and verify the authenticated tag.
            Decrypted = CryptographicEngine.DecryptAndAuthenticate(key2, Encrypted.EncryptedData, Nonce, Encrypted.AuthenticationTag, null);

            if (!CryptographicBuffer.Compare(Decrypted, Data))
            {
                Scenario6Text.Text += "Decrypted does not match original!";
                return;
            }
        }
        public Part[] Encrypt([ReadOnlyArray] byte[] aad, [ReadOnlyArray] byte[] plainText, [ReadOnlyArray] byte[] cek)
        {
            Ensure.BitSize(cek, keySizeBits, string.Format("AesGcmEncryptor expected key of size {0} bits, but was given {1} bits", keySizeBits, cek.Length * 8));

            IBuffer iv = CryptographicBuffer.GenerateRandom(12);

            SymmetricKeyAlgorithmProvider alg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesGcm);

            CryptographicKey key = alg.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(cek));

            EncryptedAndAuthenticatedData eaad = CryptographicEngine.EncryptAndAuthenticate(key,
                                                                                            CryptographicBuffer.CreateFromByteArray(plainText), iv, CryptographicBuffer.CreateFromByteArray(aad));

            return(new[] { new Part(Buffer.ToBytes(iv)), new Part(Buffer.ToBytes(eaad.EncryptedData)), new Part(Buffer.ToBytes(eaad.AuthenticationTag)) });
        }
Пример #5
0
 public void EncryptString(StringItemViewModel stringToEncrypt)
 {
     if (stringToEncrypt.IsEncrypted)
     {
         IBuffer stringBuffer    = CryptographicBuffer.ConvertStringToBinary(stringToEncrypt.Content, BinaryStringEncoding.Utf8);
         var     encryptedString = CryptographicEngine.EncryptAndAuthenticate(aesKey, stringBuffer, stringToEncrypt.Nonce,
                                                                              null);
         stringToEncrypt.AuthenticationTag = encryptedString.AuthenticationTag;
         stringToEncrypt.Content           = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, encryptedString.EncryptedData);
         stringToEncrypt.IsEncrypted       = true;
     }
     else
     {
         throw new Exception("Tried to encrypt string with encrypted flag set to true");
     }
 }
Пример #6
0
        /// <summary>
        /// The encrypt symmetric.
        /// </summary>
        /// <param name="keyBuffer">
        /// The key.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string EncryptSymmetric(IBuffer keyBuffer, IBuffer message)
        {
            IBuffer initializationBuffer = null;

            var algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(this.AlgorithmName);

            if (!this.IsPkcs7)
            {
                var pad = message.Length % algorithm.BlockLength;
                if (pad > 0)
                {
                    var desiredLength = message.Length + algorithm.BlockLength - pad;
                    message = EnsureLength(message, (int)desiredLength, false);
                }
            }

            CryptographicKey keyMaterial = algorithm.CreateSymmetricKey(EnsureLength(keyBuffer, 32, true));

            if (this.ModeOfOperation.Equals(ModeOfOperation.CBC))
            {
                var initialationVector = CryptographicBuffer.ConvertStringToBinary(Iv, Encoding);
                initializationBuffer = EnsureLength(initialationVector, (int)algorithm.BlockLength, true);
            }

            if (this.HasAuthentication)
            {
                var authenticationData = CryptographicBuffer.ConvertStringToBinary(AuthenticationData, Encoding);
                EncryptedAndAuthenticatedData encryptedData = CryptographicEngine.EncryptAndAuthenticate(
                    keyMaterial, message, GetNonce(), authenticationData);
                return(string.Format(
                           "{0}|{1}",
                           CryptographicBuffer.EncodeToBase64String(encryptedData.AuthenticationTag),
                           CryptographicBuffer.EncodeToBase64String(encryptedData.EncryptedData)));
            }

            var encryptedBuffer = CryptographicEngine.Encrypt(keyMaterial, message, initializationBuffer);

            return(CryptographicBuffer.EncodeToBase64String(encryptedBuffer));
        }
        /// <summary>
        /// This is the click handler for the 'RunSample' button.  It is responsible for executing the sample code.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RunEncryption_Click(object sender, RoutedEventArgs e)
        {
            EncryptDecryptText.Text = "";

            IBuffer encrypted;
            IBuffer decrypted;
            IBuffer iv = null;
            IBuffer data;
            IBuffer nonce;
            String  algName = AlgorithmNames.SelectionBoxItem.ToString();

            CryptographicKey key = null;

            if (bSymAlgs.IsChecked.Value || bAuthEncrypt.IsChecked.Value)
            {
                key = GenerateSymmetricKey();
            }
            else
            {
                key = GenerateAsymmetricKey();
            }

            data = GenearetData();

            if ((bool)bAuthEncrypt.IsChecked)
            {
                nonce = GetNonce();

                EncryptedAndAuthenticatedData encryptedData = CryptographicEngine.EncryptAndAuthenticate(key, data, nonce, null);

                EncryptDecryptText.Text += "    Plain text: " + data.Length + " bytes\n";
                EncryptDecryptText.Text += "    Encrypted: " + encryptedData.EncryptedData.Length + " bytes\n";
                EncryptDecryptText.Text += "    AuthTag: " + encryptedData.AuthenticationTag.Length + " bytes\n";

                decrypted = CryptographicEngine.DecryptAndAuthenticate(key, encryptedData.EncryptedData, nonce, encryptedData.AuthenticationTag, null);

                if (!CryptographicBuffer.Compare(decrypted, data))
                {
                    EncryptDecryptText.Text += "Decrypted does not match original!";
                    return;
                }
            }
            else
            {
                // CBC mode needs Initialization vector, here just random data.
                // IV property will be set on "Encrypted".
                if (algName.Contains("CBC"))
                {
                    SymmetricKeyAlgorithmProvider algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algName);
                    iv = CryptographicBuffer.GenerateRandom(algorithm.BlockLength);
                }

                // Encrypt the data.
                try
                {
                    encrypted = CryptographicEngine.Encrypt(key, data, iv);
                }
                catch (ArgumentException ex)
                {
                    EncryptDecryptText.Text += ex.Message + "\n";
                    EncryptDecryptText.Text += "An invalid key size was selected for the given algorithm.\n";
                    return;
                }

                EncryptDecryptText.Text += "    Plain text: " + data.Length + " bytes\n";
                EncryptDecryptText.Text += "    Encrypted: " + encrypted.Length + " bytes\n";

                // Decrypt the data.
                decrypted = CryptographicEngine.Decrypt(key, encrypted, iv);

                if (!CryptographicBuffer.Compare(decrypted, data))
                {
                    EncryptDecryptText.Text += "Decrypted data does not match original!";
                    return;
                }
            }
        }