コード例 #1
0
            public CryptCarotDAV_CryptStream(Stream baseStream) : base()
            {
                innerStream = new HashStream(baseStream, new SHA256CryptoServiceProvider());

                Array.Copy(_salt, header, 24);

                aes           = new AesCryptoServiceProvider();
                aes.BlockSize = BlockSize;
                aes.KeySize   = KeySize;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.Zeros;

                aes.Key   = Key;
                aes.IV    = IV;
                encryptor = aes.CreateEncryptor();

                cryptStream = new CryptoStream(innerStream, encryptor, CryptoStreamMode.Read);
                if (innerStream.Length > 0)
                {
                    patlen = (int)((innerStream.Length - 1) % BlockSizeByte + 1);
                }
                else
                {
                    patlen = BlockSizeByte;
                }
                cryptlen = innerStream.Length + BlockSizeByte - patlen;
            }
コード例 #2
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;
                }
            }
        }