public void WriteFile(string filePath, Stream stream) { filePath = SanitizePath(filePath); DeleteFile(filePath); this.files.Add(new InMemoryVirtualFile(this, GetDirectory(GetDirPath(filePath))) { FilePath = filePath, ByteContents = stream.ReadFully(), }); }
public void WriteFile(string filePath, Stream stream) { filePath = SanitizePath(filePath); DeleteFile(filePath); this.files.Add(new InMemoryVirtualFile(this, CreateDirectory(GetDirPath(filePath))) { FilePath = filePath, ByteContents = stream.ReadFully(), FileLastModified = DateTime.UtcNow, }); }
public virtual Task <TResponse> PostFileAsync <TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType = null) { var content = new MultipartFormDataContent(); var fileBytes = fileToUpload.ReadFully(); var fileContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType ?? MimeTypes.GetMimeType(fileName)); content.Add(fileContent, "file", fileName); return(SendAsync <TResponse>(HttpMethods.Post, ResolveUrl(HttpMethods.Post, relativeOrAbsoluteUrl), content) .ContinueWith(t => { content.Dispose(); fileContent.Dispose(); return t.Result; }, TaskContinuationOptions.ExecuteSynchronously)); }
public async static Task <string> FileToBase64(this string path) { var file = await FileSystem.Current.GetFileFromPathAsync(path); if (file == null) { return(string.Empty); } using (Stream stream = await file.OpenAsync(FileAccess.Read)) { if (stream == null) { return(string.Empty); } return(Convert.ToBase64String(stream.ReadFully())); } }
public int ReadFromFile(Stream file, int offset, int size) { var buf = new byte[size]; if (offset >= 0) { file.Seek(offset); } file.ReadFully(buf); var result = 0; for (var i = 0; i < size; i++) { result |= (buf[i] & 0xFF) << (i * 8); } return(result); }
public static bool IsGZipFile(Stream stream) { // read the header on the first read byte[] header = new byte[10]; // workitem 8501: handle edge case (decompress empty stream) if (!stream.ReadFully(header)) { return(false); } if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) { return(false); } return(true); }
public flash.utils.ByteArray ReadByteArray() { int num = ReadInteger(); if ((num & 1) == 0) { return((flash.utils.ByteArray)GetTableEntry(objectTable, num >> 1)); } num >>= 1; // read all data into byte array byte[] data = new byte[num]; stream.ReadFully(data, 0, num); var array = flash.utils.ByteArray.fromArray(data); objectTable.Add(array); return(array); }
private static Sprite LoadSpriteFromResources(string path, float pixelsPerUnit = 100F) { path = "CrewOfSalem.Resources." + path; try { Texture2D texture2D = GUIExtensions.CreateEmptyTexture(); var assembly = Assembly.GetExecutingAssembly(); Stream stream = assembly.GetManifestResourceStream(path); byte[] byteTexture = stream.ReadFully(); ImageConversion.LoadImage(texture2D, byteTexture, false); return(Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5F, 0.5F), pixelsPerUnit).DontDestroy()); } catch { ConsoleTools.Error("Failed loading sprites from path: " + path); } return(null); }
private void WriteImage(Stream ms) { ms.Position = 0; var hash = GetMd5Hash(ms.ReadFully()); ms.Position = 0; var fileName = hash + ".png"; using (var img = Image.FromStream(ms)) { img.Save(UploadsDir.CombineWith(fileName)); var stream = Resize(img, ThumbnailSize, ThumbnailSize); File.WriteAllBytes(ThumbnailsDir.CombineWith(fileName), stream.ReadFully()); ImageSizes.ForEach(x => File.WriteAllBytes( AssertDir(UploadsDir.CombineWith(x)).CombineWith(hash + ".png"), Get(new Resize { Id = hash, Size = x }).ReadFully())); } }
private static MultipartFormDataContent CreateMultipartContent( Stream contentToUpload, string uploadedFilename, string contentFieldName, Action <MultipartFormDataContent, byte[]> contentSizeAction = null) { var content = new MultipartFormDataContent(); var fileBytes = contentToUpload.ReadFully(); contentSizeAction?.Invoke(content, fileBytes); var fileContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length); AddFormDataContent(content, fileContent, contentFieldName); fileContent.Headers.ContentDisposition.FileName = uploadedFilename; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MimeTypes.GetMimeType(uploadedFilename)); return(content); }
public static byte[] SendBytesToUrl(this string url, string method = null, byte[] requestBody = null, string contentType = null, string acceptContentType = "*/*", Action <HttpWebRequest> requestFilter = null, Action <HttpWebResponse> responseFilter = null) { byte[] buffer; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (method != null) { request.Method = method; } if (contentType != null) { request.ContentType = contentType; } request.Accept = acceptContentType; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; if (requestFilter != null) { requestFilter(request); } if (requestBody != null) { using (Stream stream = request.GetRequestStream()) { stream.Write(requestBody, 0, requestBody.Length); } } using (WebResponse response = request.GetResponse()) { if (responseFilter != null) { responseFilter((HttpWebResponse)response); } using (Stream stream2 = response.GetResponseStream()) { buffer = stream2.ReadFully(); } } return(buffer); }
public static async Task <FileUpload> GetFileUpload(HttpContent content) { if (content == null || content.Headers == null) { return(null); } Func <string, string> getHeaderValue = name => content.Headers.FirstOrDefault(h => h.Key.Equals(name, CommonService.StringComparison)).Value?.FirstOrDefault(); try { FileUpload upload = null; using (Stream chunkStream = await content.ReadAsStreamAsync()) { //Check for not null or empty if (chunkStream == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var filename = content.Headers.ContentDisposition.FileName.Trim('"', ' '); // Read file chunk detail var headerUploadID = getHeaderValue("Upload-UploadID"); var headerChunkID = getHeaderValue("Upload-ChunkID"); var headerTotalSize = getHeaderValue("Upload-TotalSize"); var data = chunkStream.ReadFully(); int chunkID = String.IsNullOrWhiteSpace(headerChunkID) ? -1 : Convert.ToInt32(headerChunkID); long totalSize = String.IsNullOrWhiteSpace(headerTotalSize) ? 0 : Convert.ToInt64(headerTotalSize); upload = new FileUpload(headerUploadID, filename, data, totalSize, chunkID); } return(upload); } catch { return(null); } }
public static byte[] PgpEncrypt( Stream toEncrypt, PgpPublicKey encryptionKey, bool armor = true, bool verify = false, CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip) { var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, verify, new SecureRandom()); var literalizer = new PgpLiteralDataGenerator(); var compressor = new PgpCompressedDataGenerator(compressionAlgorithm); encryptor.AddMethod(encryptionKey); using var stream = new MemoryStream(); using var armoredStream = armor ? new ArmoredOutputStream(stream) : stream as Stream; using var compressedStream = compressor.Open(armoredStream); var rawData = toEncrypt.ReadFully(); var buffer = new byte[1024]; using var literalOut = new MemoryStream(); using var literalStream = literalizer.Open(literalOut, 'b', "STREAM", DateTime.UtcNow, buffer); literalStream.Write(rawData, 0, rawData.Length); literalStream.Close(); var literalData = literalOut.ReadFully(); using var encryptedStream = encryptor.Open(compressedStream, literalData.Length); encryptedStream.Write(literalData, 0, literalData.Length); encryptedStream.Close(); compressedStream.Close(); armoredStream.Close(); stream.Position = 0; Stream outStream = new MemoryStream(); var data = stream.ReadFully(); outStream.Write(data, 0, data.Length); return(data); }
private static void WriteFile(string connectionUrl, string formsAuthenticationCookie, string path) { // // Request connection page // HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(connectionUrl); httpWebRequest.CookieContainer = new CookieContainer(); // // Set Froms Authentication Cookie // httpWebRequest.CookieContainer.Add(new Cookie(FormsAuthentication.FormsCookieName, formsAuthenticationCookie, "/", httpWebRequest.RequestUri.Host)); // Get response HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (Stream s = httpWebResponse.GetResponseStream()) { File.WriteAllBytes(path, s.ReadFully()); } }
protected override void Dispose(bool disposing) { if (_isDisposed) { return; } _isDisposed = true; if (disposing) { long skipBytes = _amountRead % 512; if (skipBytes == 0) { return; } skipBytes = 512 - skipBytes; if (skipBytes == 0) { return; } var buffer = new byte[skipBytes]; Stream.ReadFully(buffer); } }
internal S2k(Stream inStr) { type = inStr.ReadByte(); algorithm = (PgpHashAlgorithm)inStr.ReadByte(); // // if this happens we have a dummy-S2k packet. // if (type != GnuDummyS2K) { if (type != 0) { iv = new byte[8]; if (inStr.ReadFully(iv) < iv.Length) { throw new EndOfStreamException(); } if (type == 3) { itCount = inStr.ReadByte(); } } else { iv = Array.Empty <byte>(); } } else { iv = Array.Empty <byte>(); inStr.ReadByte(); // G inStr.ReadByte(); // N inStr.ReadByte(); // U protectionMode = inStr.ReadByte(); // protection mode } }
public static Story FromStream(Stream stream) { return(new Story(stream.ReadFully())); }
public void AddFile(string filePath, Stream stream) { filePath = StripBeginningDirectorySeparator(filePath); this.files.Add(new InMemoryVirtualFile(VirtualPathProvider, this) { FilePath = filePath, FileName = filePath.Split(DirSeps).Last(), ByteContents = stream.ReadFully(), }); }
public SignatureSubpacket?ReadPacket() { int l = input.ReadByte(); if (l < 0) { return(null); } int bodyLen = 0; bool isLongLength = false; if (l < 192) { bodyLen = l; } else if (l <= 223) { bodyLen = ((l - 192) << 8) + (input.ReadByte()) + 192; } else if (l == 255) { isLongLength = true; bodyLen = (input.ReadByte() << 24) | (input.ReadByte() << 16) | (input.ReadByte() << 8) | input.ReadByte(); } else { throw new IOException("unexpected length header"); } int tag = input.ReadByte(); if (tag < 0) { throw new EndOfStreamException("unexpected EOF reading signature sub packet"); } if (bodyLen <= 0) { throw new EndOfStreamException("out of range data found in signature sub packet"); } byte[] data = new byte[bodyLen - 1]; // // this may seem a bit strange but it turns out some applications miscode the length // in fixed length fields, so we check the length we do get, only throwing an exception if // we really cannot continue // int bytesRead = input.ReadFully(data); bool isCritical = ((tag & 0x80) != 0); SignatureSubpacketTag type = (SignatureSubpacketTag)(tag & 0x7f); if (bytesRead != data.Length) { switch (type) { case SignatureSubpacketTag.SignatureCreationTime: data = CheckData(data, 4, bytesRead, "Signature Creation Time"); break; case SignatureSubpacketTag.IssuerKeyId: data = CheckData(data, 8, bytesRead, "Issuer"); break; case SignatureSubpacketTag.KeyExpirationTime: data = CheckData(data, 4, bytesRead, "Signature Key Expiration Time"); break; case SignatureSubpacketTag.SignatureExpirationTime: data = CheckData(data, 4, bytesRead, "Signature Expiration Time"); break; default: throw new EndOfStreamException("truncated subpacket data."); } } switch (type) { case SignatureSubpacketTag.SignatureCreationTime: return(new SignatureCreationTime(isCritical, isLongLength, data)); case SignatureSubpacketTag.KeyExpirationTime: return(new KeyExpirationTime(isCritical, isLongLength, data)); case SignatureSubpacketTag.SignatureExpirationTime: return(new SignatureExpirationTime(isCritical, isLongLength, data)); case SignatureSubpacketTag.Revocable: return(new Revocable(isCritical, isLongLength, data)); case SignatureSubpacketTag.Exportable: return(new Exportable(isCritical, isLongLength, data)); case SignatureSubpacketTag.IssuerKeyId: return(new IssuerKeyId(isCritical, isLongLength, data)); case SignatureSubpacketTag.TrustSignature: return(new TrustSignature(isCritical, isLongLength, data)); case SignatureSubpacketTag.PreferredCompressionAlgorithms: case SignatureSubpacketTag.PreferredHashAlgorithms: case SignatureSubpacketTag.PreferredSymmetricAlgorithms: return(new PreferredAlgorithms(type, isCritical, isLongLength, data)); case SignatureSubpacketTag.KeyFlags: return(new KeyFlags(isCritical, isLongLength, data)); case SignatureSubpacketTag.PrimaryUserId: return(new PrimaryUserId(isCritical, isLongLength, data)); case SignatureSubpacketTag.SignerUserId: return(new SignerUserId(isCritical, isLongLength, data)); case SignatureSubpacketTag.NotationData: return(new NotationData(isCritical, isLongLength, data)); } return(new SignatureSubpacket(type, isCritical, isLongLength, data)); }
private static ByteArrayContent FileDataContent(byte[] fileData=null, Stream srReader=null) { if (fileData!=null) return new ByteArrayContent(fileData); if (srReader == null) return null; var fd = srReader.ReadFully(); return new ByteArrayContent(fd); }
/// <summary> /// Read a float from a stream. /// </summary> /// <param name="stream">The source stream</param> /// <returns>The float read</returns> public static float ReadFloat(this Stream stream) { return(stream.ReadFully(new byte[4]).ToFloat()); }
/// <summary> /// Read a short from a stream. /// </summary> /// <param name="stream">The source stream</param> /// <returns>The short read</returns> public static short ReadInt16(this Stream stream) { return(stream.ReadFully(new byte[2]).ToInt16()); }
protected Stream CreateDecompressionStream(Stream stream, ZipCompressionMethod method) { switch (method) { case ZipCompressionMethod.None: { return(stream); } case ZipCompressionMethod.Deflate: { return(new DeflateStream(stream, CompressionMode.Decompress)); } case ZipCompressionMethod.BZip2: { return(new BZip2Stream(stream, CompressionMode.Decompress)); } case ZipCompressionMethod.LZMA: { if (FlagUtility.HasFlag(Header.Flags, HeaderFlags.Encrypted)) { throw new NotSupportedException("LZMA with pkware encryption."); } var reader = new BinaryReader(stream); reader.ReadUInt16(); //LZMA version var props = new byte[reader.ReadUInt16()]; reader.Read(props, 0, props.Length); return(new LzmaStream(props, stream, Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1, FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1) ? -1 : (long)Header.UncompressedSize)); } case ZipCompressionMethod.PPMd: { var props = new byte[2]; stream.ReadFully(props); return(new PpmdStream(new PpmdProperties(props), stream, false)); } case ZipCompressionMethod.WinzipAes: { ExtraData data = Header.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault(); if (data == null) { throw new InvalidFormatException("No Winzip AES extra data found."); } if (data.Length != 7) { throw new InvalidFormatException("Winzip data length is not 7."); } ushort compressedMethod = DataConverter.LittleEndian.GetUInt16(data.DataBytes, 0); if (compressedMethod != 0x01 && compressedMethod != 0x02) { throw new InvalidFormatException("Unexpected vendor version number for WinZip AES metadata"); } ushort vendorId = DataConverter.LittleEndian.GetUInt16(data.DataBytes, 2); if (vendorId != 0x4541) { throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata"); } return(CreateDecompressionStream(stream, (ZipCompressionMethod)DataConverter.LittleEndian.GetUInt16(data.DataBytes, 5))); } default: { throw new NotSupportedException("CompressionMethod: " + Header.CompressionMethod); } } }
public void AppendFile(string filePath, Stream stream) { filePath = SanitizePath(filePath); var existingFile = GetFile(filePath); var bytes = existingFile != null ? existingFile.ReadAllBytes().Combine(stream.ReadFully()) : stream.ReadFully(); DeleteFile(filePath); this.files.Add(new InMemoryVirtualFile(this, CreateDirectory(GetDirPath(filePath))) { FilePath = filePath, ByteContents = bytes, FileLastModified = DateTime.UtcNow, }); }
/// <summary> /// Read a long from a stream /// </summary> /// <param name="stream">The source stream</param> /// <returns>The long read</returns> public static long ReadInt64(this Stream stream) { return(stream.ReadFully(new byte[8]).ToInt64()); }
public override T DeserializeFromStream <T>(Stream stream) { var response = stream.ReadFully(); return(response.FromUtf8Bytes().FromJson <T>()); }
/// <summary> /// Read an int from a stream. /// </summary> /// <param name="stream">The source stream</param> /// <returns>The int read</returns> public static int ReadInt32(this Stream stream) { return(stream.ReadFully(new byte[4]).ToInt32()); }
public BlorbFile(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } this.memory = stream.ReadFully(); var reader = new MemoryReader(this.memory, 0); var dwords = reader.NextDWords(3); // First, ensure that this is a valid format if (dwords[0] != id_FORM) { throw new InvalidOperationException(); } if (dwords[2] != id_IFRS) { throw new InvalidOperationException(); } int totalLength = (int)dwords[1] + 8; // Collect all chunks this.chunks = new List <ChunkDescriptor>(); while (reader.Address < totalLength) { var chunk = new ChunkDescriptor(); chunk.Address = (uint)reader.Address; var type = reader.NextDWord(); var len = reader.NextDWord(); chunk.Type = type; if (type == id_FORM) { chunk.DataAddress = chunk.Address; chunk.Length = len + 8; } else { chunk.DataAddress = (uint)reader.Address; chunk.Length = len; } chunks.Add(chunk); reader.Skip((int)len); if ((reader.Address & 1) != 0) { reader.Skip(1); } if (reader.Address > totalLength) { throw new InvalidOperationException(); } } // Loop through chunks and collect resources this.resources = new List <ResourceDecriptor>(); foreach (var chunk in chunks) { if (chunk.Type == id_RIdx) { reader.Address = (int)chunk.DataAddress; var numResources = (int)reader.NextDWord(); if (chunk.Length < (numResources * 12) + 4) { throw new InvalidOperationException(); } for (int i = 0; i < numResources; i++) { var resource = new ResourceDecriptor(); resource.Usage = reader.NextDWord(); resource.Number = reader.NextDWord(); var resourcePos = reader.NextDWord(); var chunkIndex = chunks.FindIndex(c => c.Address == resourcePos); if (chunkIndex < 0) { throw new InvalidOperationException(); } resource.ChunkNumber = chunkIndex; resources.Add(resource); } } else if (chunk.Type == id_RelN) { reader.Address = (int)chunk.DataAddress; if (chunk.Length < 2) { throw new InvalidOperationException(); } releaseNumber = reader.NextWord(); } else if (chunk.Type == id_IFhd) { reader.Address = (int)chunk.DataAddress; if (chunk.Length < 3) { throw new InvalidOperationException(); } var header = new ZHeader(); header.ReleaseNumber = reader.NextWord(); header.SerialNumber = new char[6]; for (int i = 0; i < 6; i++) { header.SerialNumber[i] = (char)reader.NextByte(); } header.Checksum = reader.NextWord(); } else if (chunk.Type == id_Reso) { } else if (chunk.Type == id_Loop) { } else if (chunk.Type == id_Plte) { } } }
/// <summary> /// Reads the value from the stream /// </summary> /// <param name="source"></param> /// <param name="maxLength">Maximal expected length (either 4 or 8)</param> /// <param name="buffer">The buffer for optimization purposes. Must match the maxlength</param> /// <returns></returns> public static VInt Read(Stream source, int maxLength, byte[] buffer) { buffer = buffer ?? new byte[maxLength]; if (source.ReadFully(buffer, 0, 1) == 0) { throw new EndOfStreamException(); } if(buffer[0] == 0) throw new EbmlDataFormatException("Length bigger than 8 are not supported"); // TODO handle EBMLMaxSizeWidth var extraBytes = (buffer[0] & 0xf0) != 0 ? ExtraBytesSize[buffer[0] >> 4] : 4 + ExtraBytesSize[buffer[0]]; if (extraBytes + 1 > maxLength) throw new EbmlDataFormatException(string.Format("Expected VInt with a max length of {0}. Got {1}", maxLength, extraBytes + 1)); if (source.ReadFully(buffer, 1, extraBytes) != extraBytes) { throw new EndOfStreamException(); } ulong encodedValue = buffer[0]; for (var i = 0; i < extraBytes; i++) { encodedValue = encodedValue << 8 | buffer[i + 1]; } return new VInt(encodedValue, extraBytes + 1); }
internal static string ToBase64String(this Stream theStream) { var buffer = theStream.ReadFully(0); return(Convert.ToBase64String(buffer)); }
private static void ReadStreamFully(Stream stream, byte[] buf, int offset, int size, long timeoutMillis) => stream.ReadFully(buf, offset, size, timeoutMillis, ex => ex.ErrorCode == 10060);
/// <summary> /// Read a string from a stream. /// </summary> /// <param name="stream">The source stream</param> /// <returns>The string read</returns> public static string ReadString(this Stream stream) { var len = stream.ReadInt32(); return(Encoding.UTF8.GetString(stream.ReadFully(new byte[len]))); }
private Stream GetDataStream(ReadOnlySpan <byte> sessionData, bool verifyIntegrity) { PgpSymmetricKeyAlgorithm keyAlgorithm = (PgpSymmetricKeyAlgorithm)sessionData[0]; if (keyAlgorithm == PgpSymmetricKeyAlgorithm.Null) { return(inputStream); } var key = sessionData.Slice(1); SymmetricAlgorithm encryptionAlgorithm = PgpUtilities.GetSymmetricAlgorithm(keyAlgorithm); var iv = new byte[(encryptionAlgorithm.BlockSize + 7) / 8]; byte[] keyArray = Array.Empty <byte>(); ICryptoTransform decryptor; var inlineIv = new byte[iv.Length * 2]; // Aligned to block size try { keyArray = key.ToArray(); decryptor = encryptionAlgorithm.CreateDecryptor(keyArray, iv); if (encryptedPacket is SymmetricEncDataPacket) { if (inputStream.ReadFully(inlineIv.AsSpan(0, iv.Length + 2)) < iv.Length + 2) { throw new EndOfStreamException(); } var decryptedInlineIv = decryptor.TransformFinalBlock(inlineIv, 0, inlineIv.Length); if (verifyIntegrity) { VerifyInlineIV(decryptedInlineIv.AsSpan(0, iv.Length), decryptedInlineIv.AsSpan(iv.Length, 2)); } // Perform reset according to the OpenPGP CFB rules decryptor = encryptionAlgorithm.CreateDecryptor(keyArray, inlineIv.AsSpan(2, iv.Length).ToArray()); } } finally { CryptographicOperations.ZeroMemory(keyArray.AsSpan()); } encStream = new CryptoStream( inputStream, new ZeroPaddedCryptoTransform(decryptor), CryptoStreamMode.Read); if (encryptedPacket is SymmetricEncIntegrityPacket) { hashAlgorithm = SHA1.Create(); tailEndCryptoTransform = new TailEndCryptoTransform(hashAlgorithm, hashAlgorithm.HashSize / 8); encStream = new CryptoStream(encStream, tailEndCryptoTransform, CryptoStreamMode.Read); if (encStream.ReadFully(inlineIv.AsSpan(0, iv.Length + 2)) < iv.Length + 2) { throw new EndOfStreamException(); } if (verifyIntegrity) { VerifyInlineIV(inlineIv.AsSpan(0, iv.Length), inlineIv.AsSpan(iv.Length, 2)); } } return(encStream); }
internal SignaturePacket(Stream bcpgIn) { version = bcpgIn.ReadByte(); if (version == 3 || version == 2) { // int l = bcpgIn.ReadByte(); signatureType = (PgpSignatureType)bcpgIn.ReadByte(); creationTime = DateTimeOffset.FromUnixTimeSeconds( ((long)bcpgIn.ReadByte() << 24) | ((long)bcpgIn.ReadByte() << 16) | ((long)bcpgIn.ReadByte() << 8) | (uint)bcpgIn.ReadByte()).UtcDateTime; keyId |= (long)bcpgIn.ReadByte() << 56; keyId |= (long)bcpgIn.ReadByte() << 48; keyId |= (long)bcpgIn.ReadByte() << 40; keyId |= (long)bcpgIn.ReadByte() << 32; keyId |= (long)bcpgIn.ReadByte() << 24; keyId |= (long)bcpgIn.ReadByte() << 16; keyId |= (long)bcpgIn.ReadByte() << 8; keyId |= (uint)bcpgIn.ReadByte(); keyAlgorithm = (PgpPublicKeyAlgorithm)bcpgIn.ReadByte(); hashAlgorithm = (PgpHashAlgorithm)bcpgIn.ReadByte(); hashedData = Array.Empty <SignatureSubpacket>(); unhashedData = Array.Empty <SignatureSubpacket>(); } else if (version == 4) { signatureType = (PgpSignatureType)bcpgIn.ReadByte(); keyAlgorithm = (PgpPublicKeyAlgorithm)bcpgIn.ReadByte(); hashAlgorithm = (PgpHashAlgorithm)bcpgIn.ReadByte(); int hashedLength = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte(); byte[] hashed = new byte[hashedLength]; if (bcpgIn.ReadFully(hashed) < hashed.Length) { throw new EndOfStreamException(); } // // read the signature sub packet data. // SignatureSubpacketParser sIn = new SignatureSubpacketParser(new MemoryStream(hashed, false)); IList <SignatureSubpacket> v = new List <SignatureSubpacket>(); SignatureSubpacket? sub; while ((sub = sIn.ReadPacket()) != null) { v.Add(sub); if (sub is IssuerKeyId issuerKeyId) { keyId = issuerKeyId.KeyId; } else if (sub is SignatureCreationTime signatureCreationTime) { creationTime = signatureCreationTime.Time; } } hashedData = v.ToArray(); int unhashedLength = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte(); byte[] unhashed = new byte[unhashedLength]; if (bcpgIn.ReadFully(unhashed) < unhashed.Length) { throw new EndOfStreamException(); } sIn = new SignatureSubpacketParser(new MemoryStream(unhashed, false)); v.Clear(); while ((sub = sIn.ReadPacket()) != null) { v.Add(sub); if (sub is IssuerKeyId issuerKeyId && keyId == 0) { keyId = issuerKeyId.KeyId; } } unhashedData = v.ToArray(); } else { throw new PgpException("unsupported version: " + version); } fingerprint = new byte[2]; if (bcpgIn.ReadFully(fingerprint) < fingerprint.Length) { throw new EndOfStreamException(); } signature = bcpgIn.ReadAll(); }
private static byte[] ReadFully(this Stream stream, byte[] buf) { return(stream.ReadFully(buf, 0, buf.Length)); }
/// <summary> /// Read a character from a stream. /// </summary> /// <param name="stream">The source stream</param> /// <returns>The character read</returns> public static char ReadChar(this Stream stream) { return(stream.ReadFully(new byte[2]).ToChar()); }
public void WriteFile(string filePath, Stream stream) { var realFilePath = RootDir.RealPath.CombineWith(filePath); EnsureDirectory(Path.GetDirectoryName(realFilePath)); File.WriteAllBytes(realFilePath, stream.ReadFully()); }