Example #1
0
        public static async Task <bool> EncryptFilename(string uploadfilename, string enckey, string checkpoint, CancellationToken ct = default(CancellationToken))
        {
            int retry = 30;

            while (--retry > 0)
            {
                var child = (await GetChanges(checkpoint, ct).ConfigureAwait(false)).Where(x => x.name.Contains(uploadfilename)).LastOrDefault();
                if (child?.status == "AVAILABLE")
                {
                    Config.Log.LogOut("EncryptFilename");
                    using (var ms = new MemoryStream())
                    {
                        byte[] plain = Encoding.UTF8.GetBytes(enckey);
                        ms.Write(plain, 0, plain.Length);
                        ms.Position = 0;
                        using (var enc = new CryptCTR.AES256CTR_CryptStream(ms, child.id))
                        {
                            byte[] buf = new byte[ms.Length];
                            enc.Read(buf, 0, buf.Length);
                            string cryptname = "";
                            foreach (var c in buf)
                            {
                                cryptname += (char)('\u2800' + c);
                            }
                            int retry2 = 30;
                            FileMetadata_Info reItem = null;
                            while (--retry2 > 0)
                            {
                                try
                                {
                                    if (reItem == null)
                                    {
                                        reItem = await Drive.renameItem(id : child.id, newname : cryptname, ct : ct).ConfigureAwait(false);
                                    }
                                }
                                catch { }
                                var child2 = (await GetChanges(checkpoint: ChangeCheckpoint, ct: ct).ConfigureAwait(false)).Where(x => x.name.Contains(cryptname)).LastOrDefault();
                                if (reItem != null && child2?.status == "AVAILABLE")
                                {
                                    AmazonDriveTree[reItem.id].IsEncrypted = CryptMethods.Method1_CTR;
                                    AmazonDriveTree[reItem.id].ReloadCryptedMethod1();
                                    break;
                                }
                                await Task.Delay(2000).ConfigureAwait(false);
                            }
                            return(true);
                        }
                    }
                }
                await Task.Delay(2000).ConfigureAwait(false);
            }
            return(false);
        }
Example #2
0
        private async Task DecodeFile(IEnumerable <string> encfiles)
        {
            foreach (var file in encfiles)
            {
                if (!File.Exists(file))
                {
                    Log("file not found : {0}", file);
                    continue;
                }
                var decfilepath = Path.GetDirectoryName(file);

                var encfilename = Path.GetFileName(file);
                var enckey      = Path.GetFileNameWithoutExtension(encfilename);
                if (!Regex.IsMatch(encfilename, ".*?\\.[a-z0-9]{8}\\.enc$"))
                {
                    Log("filename decode error : {0}", file);
                    continue;
                }
                var decfilename = Path.GetFileNameWithoutExtension(enckey);

                var decfile = Path.Combine(decfilepath, decfilename);
                if (File.Exists(decfile))
                {
                    Log("Exists : {0}", decfile);
                    continue;
                }

                using (var efile = File.OpenRead(file))
                    using (var dfile = File.OpenWrite(decfile))
                        using (var cfile = new CryptCTR.AES256CTR_CryptStream(efile, enckey))
                        {
                            try
                            {
                                await cfile.CopyToAsync(dfile, 81920, cts.Token);
                            }
                            catch (Exception ex)
                            {
                                Log("Decode Error : {0}->{1} {2}", file, decfile, ex.Message);
                                continue;
                            }
                        }
                Log("OK : {0}->{1}", file, decfile);
            }
        }
Example #3
0
 public static string DecryptFilename(FileMetadata_Info downloaditem)
 {
     using (var ms = new MemoryStream())
     {
         string cryptname = downloaditem?.name;
         if (string.IsNullOrEmpty(cryptname))
         {
             return(null);
         }
         byte[] buf = new byte[cryptname.Length];
         int    i   = 0;
         foreach (var c in cryptname)
         {
             if (c < '\u2800' || c > '\u28ff')
             {
                 return(null);
             }
             buf[i++] = (byte)(c - '\u2800');
         }
         ms.Write(buf, 0, i);
         ms.Position = 0;
         using (var dec = new CryptCTR.AES256CTR_CryptStream(ms, downloaditem.id))
         {
             byte[] plain = new byte[i];
             dec.Read(plain, 0, plain.Length);
             var plainname = Encoding.UTF8.GetString(plain);
             if (plainname.IndexOfAny(Path.GetInvalidFileNameChars()) < 0)
             {
                 if (Regex.IsMatch(plainname ?? "", ".*?\\.[a-z0-9]{8}$"))
                 {
                     return(plainname);
                 }
                 else
                 {
                     return(null);
                 }
             }
             else
             {
                 return(null);
             }
         }
     }
 }
Example #4
0
        private async Task EncodeFile(IEnumerable <string> plainfiles)
        {
            foreach (var file in plainfiles)
            {
                if (!File.Exists(file))
                {
                    Log("file not found : {0}", file);
                    continue;
                }
                var encfilepath = Path.GetDirectoryName(file);

                var plainfilename = Path.GetFileName(file);
                var enckey        = plainfilename + "." + Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                var encfilename   = enckey + ".enc";

                var encfile = Path.Combine(encfilepath, encfilename);
                if (File.Exists(encfile))
                {
                    Log("Exists : {0}", encfile);
                    continue;
                }

                using (var pfile = File.OpenRead(file))
                    using (var efile = File.OpenWrite(encfile))
                        using (var cfile = new CryptCTR.AES256CTR_CryptStream(pfile, enckey))
                        {
                            try
                            {
                                await cfile.CopyToAsync(efile, 81920, cts.Token);
                            }
                            catch (Exception ex)
                            {
                                Log("Encode Error : {0}->{1} {2}", file, encfile, ex.Message);
                                continue;
                            }
                        }
                Log("OK : {0}->{1}", file, encfile);
            }
        }
Example #5
0
        public async Task <FileMetadata_Info> uploadFile(string filename, string parent_id = null, string uploadname = null, string uploadkey = null, PoschangeEventHandler process = null, CancellationToken ct = default(CancellationToken))
        {
            int transbufsize = Config.UploadBufferSize;

            if (Config.UploadLimit < transbufsize)
            {
                transbufsize = (int)Config.UploadLimit;
            }
            if (transbufsize < 1 * 1024)
            {
                transbufsize = 1 * 1024;
            }
            if (Config.UploadTrick1)
            {
                transbufsize = 256 * 1024;
            }


            Config.Log.LogOut("\t[uploadFile] " + filename);
            string error_str;
            string HashStr = "";

            using (var client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromDays(1);
                try
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Authkey.access_token);
                    var content = new MultipartFormDataContent();

                    DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(ItemUpload_Info));

                    // Serializerを使ってオブジェクトをMemoryStream に書き込み
                    MemoryStream ms             = new MemoryStream();
                    var          short_filename = Path.GetFileName(filename);

                    if (uploadname == null)
                    {
                        uploadname = (Config.UseEncryption) ? short_filename + ".enc" : short_filename;
                        if (uploadkey == null)
                        {
                            uploadkey = short_filename;
                        }
                    }
                    else
                    {
                        if (uploadkey == null)
                        {
                            uploadkey = Path.GetFileNameWithoutExtension(uploadname);
                        }
                    }
                    jsonSer.WriteObject(ms, new ItemUpload_Info
                    {
                        name    = uploadname,
                        kind    = "FILE",
                        parents = string.IsNullOrEmpty(parent_id) ? null : new string[] { parent_id }
                    });
                    ms.Position = 0;

                    // StreamReader で StringContent (Json) をコンストラクトします。
                    StreamReader sr = new StreamReader(ms);
                    content.Add(new StringContent(sr.ReadToEnd(), System.Text.Encoding.UTF8, "application/json"), "metadata");

                    using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 256 * 1024))
                    {
                        HashStream    contStream  = null;
                        Stream        cryptStream = null;
                        StreamContent fileContent = null;
                        IHashStream   hasher      = null;
                        if (Config.UseEncryption)
                        {
                            if (Config.CryptMethod == CryptMethods.Method1_CTR)
                            {
                                cryptStream = new CryptCTR.AES256CTR_CryptStream(file, uploadkey);
                                contStream  = new HashStream(cryptStream, new MD5CryptoServiceProvider());
                                hasher      = contStream;
                            }
                            if (Config.CryptMethod == CryptMethods.Method2_CBC_CarotDAV)
                            {
                                cryptStream = new CryptCarotDAV.CryptCarotDAV_CryptStream(file);
                                contStream  = new HashStream(cryptStream, new MD5CryptoServiceProvider());
                                hasher      = contStream;
                            }
                        }
                        else
                        {
                            contStream = new HashStream(file, new MD5CryptoServiceProvider());
                            hasher     = contStream;
                        }

                        using (cryptStream)
                            using (contStream)
                                using (var thstream = new ThrottleUploadStream(contStream, ct))
                                    using (var f = new PositionStream(thstream))
                                    {
                                        if (process != null)
                                        {
                                            f.PosChangeEvent += process;
                                        }

                                        fileContent = new StreamContent(f, transbufsize);
                                        fileContent.Headers.ContentLength = f.Length;
                                        fileContent.Headers.ContentType   = new MediaTypeHeaderValue("application/octet-stream");
                                        content.Add(fileContent, "content", Path.GetFileName(filename));

                                        using (fileContent)
                                        {
                                            if (Config.UploadTrick1)
                                            {
                                                if (DelayUploadReset != null)
                                                {
                                                    if (Interlocked.CompareExchange(ref Config.UploadLimitTemp, Config.UploadLimit, 10 * 1024) == 10 * 1024)
                                                    {
                                                        DelayUploadReset = Task.Delay(TimeSpan.FromSeconds(10)).ContinueWith((task) =>
                                                        {
                                                            Interlocked.Exchange(ref Config.UploadLimit, Config.UploadLimitTemp);
                                                            DelayUploadReset = null;
                                                        });
                                                    }
                                                }
                                            }
                                            var response = await client.PostAsync(
                                                Config.contentUrl + "nodes?suppress=deduplication",
                                                content,
                                                ct).ConfigureAwait(false);

                                            HashStr = hasher.Hash.ToLower();
                                            response.EnsureSuccessStatusCode();
                                            string responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                                            // Above three lines can be replaced with new helper method in following line
                                            // string body = await client.GetStringAsync(uri);
                                            var ret = ParseResponse <FileMetadata_Info>(responseBody);
                                            if (ret.contentProperties?.md5 != HashStr)
                                            {
                                                throw new AmazonDriveUploadException(HashStr);
                                            }
                                            return(ret);
                                        }
                                    }
                    }
                }
                catch (AmazonDriveUploadException)
                {
                    throw;
                }
                catch (HttpRequestException ex)
                {
                    error_str = ex.Message;
                    Config.Log.LogOut("\t[uploadFile] " + error_str);
                    throw new AmazonDriveUploadException(HashStr, ex);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    error_str = ex.ToString();
                    Config.Log.LogOut("\t[uploadFile] " + error_str);
                    throw;
                }
            }
        }