在c#中以加密形式将数据存储到文件中10通用应用程序开发

问题描述:

这里我尝试以加密形式在本地写入一些文本到文件中,但是当我在本地看到文件时数据不是加密形式。 有人可以纠正我。在c#中以加密形式将数据存储到文件中10通用应用程序开发

//Writing to file 
    StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder; 
    // textBlock.Text = folder.Path; 
    StorageFile sampleFile = await folder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting); 
    var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(
       "Text input into sample.txt file", Windows.Security.Cryptography.BinaryStringEncoding.Utf8); 
    await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer); 

    //Reading from file 
    StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; 
    sampleFile = await storageFolder.GetFileAsync("sample.txt"); 
    string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile); 
    // textBlock.Text = text; 
+0

UTF8是不加密和'ConvertStringToBinary'是不执行加密方法。不知道你的样本是否与你的问题有关... –

+0

我是新来的应用程序开发,我试着通过以下的https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh758325。 aspx,残友请一些教程来加密文件中的数据并再次解密。 – djkp

+0

请告诉我们您计划如何保护您的加密密钥第一... –

您可以使用CryptographicEngine class实际执行加密和解密。

但是以@Neil's评论以上 - 你在哪里存储解密密钥?如果密钥存储为应用程序的一部分,它并不能真正保护任何内容。如果它来自用户输入(例如,他们每次输入的密码+可选的盐),那就更好了。

+0

使用Windows.Security.Credentials有什么问题吗?还是将用户凭证存储在凭证柜更坏的做法中? – visc

+0

在储物柜中储存凭证非常棒。问题是“他们来自哪里” –

如果您想在代码中保留秘密,可以使用混淆。然而,这也可能会被打破,但至少它会使安全性变得更难以破解,因此尝试破解安全性的动机也就越小。最终,所需的保护量取决于您想要隐藏的数据的重要性。

加密或解密storagefile UWP

public static async Task<StorageFile> EncryptStorageFileLocalUserAsync(this StorageFile FileForEncryption) 
    { 
     //"LOCAL = user" 
     IBuffer data = await FileIO.ReadBufferAsync(FileForEncryption); 
     IBuffer SecuredData = await DataProtectionStream("LOCAL = user", data); 
     var EncryptedFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(
      "EncryptedFile" + FileForEncryption.FileType, CreationCollisionOption.ReplaceExisting); 
     await FileIO.WriteBufferAsync(EncryptedFile, SecuredData); 
     return EncryptedFile; 
     // Reporting.DisplayMessage("File encryption successfull. File stored at " + EncryptedFile.Path + "\n\n"); 

    } 
    public static async Task<StorageFile> DecryptStorageFileLocalUserAsync(this StorageFile EncryptedFile) 
    { 

     IBuffer data = await FileIO.ReadBufferAsync(EncryptedFile); 
     IBuffer UnSecuredData = await DataUnprotectStream(data); 

     var DecryptedFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(
      "DecryptedFile" + EncryptedFile.FileType, CreationCollisionOption.ReplaceExisting); 
     await FileIO.WriteBufferAsync(DecryptedFile, UnSecuredData); 
     // Reporting.DisplayMessage("File decryption successfull. File stored at " + DecryptedFile.Path + "\n\n"); 
     return DecryptedFile; 

    }