Beispiel #1
0
 public async Task DecryptFileAes(FileItemViewModel fileToDecrypt)
 {
     if (fileToDecrypt.IsEncrypted)
     {
         XmlSerializer        serializer = new XmlSerializer(typeof(SerialisableAuthData));
         SerialisableAuthData tagData    = null;
         using (Stream stream = await fileToDecrypt.File.OpenStreamForReadAsync())
         {
             tagData = serializer.Deserialize(stream) as SerialisableAuthData;
             stream.Dispose();
         }
         if (tagData != null)
         {
             IBuffer data          = tagData.GetData();
             IBuffer 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");
     }
 }
Beispiel #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);
                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");
            }
        }