Ejemplo n.º 1
0
 public async Task <string> UnprotectAsync(ContentFile contentFile, KeyFile keyFile)
 => await Task.FromResult(Unprotect(contentFile : contentFile, keyFile : keyFile));
Ejemplo n.º 2
0
 public async Task <OperationResults> ProtectAsync(string text, ContentFile contentFile, KeyFile keyFile)
 => await Task.FromResult(Protect(text : text, contentFile : contentFile, keyFile : keyFile));
Ejemplo n.º 3
0
        public OperationResults Protect(string text, ContentFile contentFile, KeyFile keyFile)
        {
            _exception = null;
            FileStream stream = null;

            try
            {
                if (string.IsNullOrWhiteSpace(text))
                {
                    throw new Exception("Invalid text to protect");
                }

                if (string.IsNullOrWhiteSpace(contentFile.FileName) || string.IsNullOrWhiteSpace(contentFile.FilePath))
                {
                    throw new Exception("Invalid ContentFile");
                }

                if (string.IsNullOrWhiteSpace(keyFile.FileName) || string.IsNullOrWhiteSpace(keyFile.FilePath))
                {
                    throw new Exception("Invalid KeyFile");
                }

                try
                {
                    stream = File.Create(contentFile.ToString());
                }
                catch (Exception ex)
                {
                    _exception = ex;
                    return(OperationResults.Error);
                }
                var tDesCsp = new TripleDESCryptoServiceProvider();
                var cs      = new CryptoStream(stream, tDesCsp.CreateEncryptor(), CryptoStreamMode.Write);
                var sw      = new StreamWriter(cs);
                sw.WriteLine(text);
                sw.Flush();
                sw.Close();

                stream = null;
                try
                {
                    stream = File.Create(keyFile.ToString());
                }
                catch (Exception ex)
                {
                    _exception = ex;
                    return(OperationResults.Error);
                }
                var bw = new BinaryWriter(stream);
                bw.Write(tDesCsp.Key);
                bw.Write(tDesCsp.IV);
                bw.Flush();
                bw.Close();

                tDesCsp.Clear();

                return(OperationResults.Protected);
            }
            catch (Exception ex)
            {
                _exception = ex;
                return(OperationResults.Error);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }