Example #1
0
 public async Task DecryptFileAes(FileItemViewModel fileToDecrypt)
 {
     if (fileToDecrypt.IsEncrypted)
     {
         var serializer = new XmlSerializer(typeof(SerialisableAuthData));
         SerialisableAuthData tagData = null;
         using (var stream = await fileToDecrypt.File.OpenStreamForReadAsync())
         {
             tagData = serializer.Deserialize(stream) as SerialisableAuthData;
             stream.Dispose();
         }
         if (tagData != null)
         {
             var data          = tagData.GetData();
             var tag           = tagData.GetTag();
             var decryptedData = CryptographicEngine.DecryptAndAuthenticate(aesKey, data,
                                                                            fileToDecrypt.Nonce, tag, null);
             await FileIO.WriteBufferAsync(fileToDecrypt.File, decryptedData);
         }
         fileToDecrypt.IsEncrypted = false;
     }
     else
     {
         throw new Exception("Tried to dencrypt file with encrypted flag already set to false");
     }
 }
Example #2
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);
                var encryptedData = CryptographicEngine.EncryptAndAuthenticate(aesKey, fileBuffer, fileToEncrypt.Nonce,
                                                                               null);

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

                var serializer = new XmlSerializer(typeof(SerialisableAuthData));
                using (var 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");
            }
        }