Producer producing data every one second and Consumer consuming after every minute - c#

I am trying to write a program using BlockingCollection producer/ consumer pattern where producer will keep on producing data every one second and consumer consuming it and displaying some processed data from my Producer data on console window every 60 seconds.
The real life scenario is - I will be getting Open High Low Close stock data in the producer every second which I would like to pass to consumer threads which would create 1 minute OHLC data from 60 seconds data which I will receive from third party. For simulating real life scenario, I am trying to create a producer which would have timer which would keep on putting data in BlockingCollection every second but not sure how to use timer in the producer. Can anyone suggest with code
How would I create Producer which would keep on producing OHLC data every second using timer inside the producer. Lets say my OHLC value would have counter which I will be using for counting second. For example
O=1,H=1,L=1,C=1
O=2,H=2,L=2,C=2
....
O=60,H=60,L=60,C=60
As soon as the counter reaches multiple of 60, my Consumer should kick-in which would take that 60 second data to create one minute OHLC data.
2. Where would CompleteAdding method be written as my Producer is never ending Producer which will only be stopped once I stop entire application
Any help in this regard is greatly appreciated. Thanks in advance

In this example two tasks are created: producer and consumer. In the first, data is generated every second and placed in the collection. In the second, the data is extracted from the collection and processed every minute.
var produced = new BlockingCollection<Price>();
var producer = Task.Run(async () =>
{
try
{
var random = new Random();
while (true)
{
produced.Add(new Price { Low = random.Next(500), High = random.Next(500, 1000) });
await Task.Delay(1000);
}
}
finally
{
produced.CompleteAdding();
}
});
var consumer = Task.Run(async () =>
{
const int interval = 60; // seconds
var values = new List<Price>();
foreach (var value in produced.GetConsumingEnumerable())
{
values.Add(value);
if (DateTime.UtcNow.Second % interval == 0)
{
Console.WriteLine(values.Average(p => p.High)); // do some work
values.Clear();
}
}
});
Task.WaitAll(producer, consumer);

A BlockingCollection is needed when you want the consumer to be blocked while waiting for available data, or the producer to be blocked while waiting for available space in a limited-capacity queue. In your case you want to be blocked by time, not by availability, so a simpler collection like a ConcurrentQueue should be enough (or even a thread-unsafe Queue protected with a locker).
For exiting the loop when the application ends, I suggest that you use cooperative cancellation with a CancellationToken. This way your application will close cleanly.
var queue = new ConcurrentQueue<Price>();
var cts = new CancellationTokenSource();
var producer = Task.Run(async () =>
{
try
{
var random = new Random();
while (true)
{
queue.Enqueue(new Price
{
Low = random.Next(0, 500),
High = random.Next(500, 1000)
});
await Task.Delay(millisecondsDelay: 1000, cts.Token);
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Producer Canceled");
}
});
var consumer = Task.Run(async () =>
{
try
{
var random = new Random();
while (true)
{
await Task.Delay(millisecondsDelay: 60000, cts.Token);
var prices = queue.DequeueAll();
Console.Write($"Minute Report");
Console.Write($", Count: {prices.Count,2}");
Console.Write($", Low Average: {prices.Average(p => p.Low):#,0.0000}");
Console.Write($", High Average: {prices.Average(p => p.High):#,0.0000}");
Console.WriteLine();
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Consumer Canceled");
}
});
Console.WriteLine("Press Escape to finish.");
while (true)
{
var keyInfo = Console.ReadKey(true);
if (keyInfo.Key == ConsoleKey.Escape) break;
}
cts.Cancel();
Task.WaitAll(producer, consumer);
For dequeuing all items from the queue I used the extension method below:
public static List<T> DequeueAll<T>(this ConcurrentQueue<T> source)
{
var list = new List<T>();
while (source.TryDequeue(out var item))
{
list.Add(item);
}
return list;
}
Sample output:
Press Escape to finish.
Minute Report, Count: 60, Low Average: 209.5405, High Average: 782.2432
Minute Report, Count: 59, Low Average: 285.0500, High Average: 714.5500
Minute Report, Count: 60, Low Average: 245.5128, High Average: 718.6667
Minute Report, Count: 60, Low Average: 259.6154, High Average: 703.6667
Minute Report, Count: 59, Low Average: 215.8919, High Average: 735.0811
Minute Report, Count: 59, Low Average: 252.7632, High Average: 727.2368
Minute Report, Count: 60, Low Average: 288.5833, High Average: 730.6389
Producer Canceled
Consumer Canceled

Another approach is to allow the producer to produce values every second and allow the consumer to read the shared buffer only when it contains 60 data elements. This approach removes all direct dependencies between the producer and the consumer. The producer writes to the shared buffer at a rate natural to the producer while the consumer only deals with a batch of 60 data elements.
The following example using Ada illustrates the concept.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar; use Ada.Calendar;
procedure Main is
type Index is mod 60;
type collect is array (Index) of Positive;
protected Buffer is
entry Get (Nums : out collect);
entry Put (Item : in Positive);
private
Buf : collect;
Next : Index := Index'First;
Count : Natural := 0;
end Buffer;
protected body Buffer is
entry Get (Nums : out collect) when Count = Index'Modulus is
begin
Nums := Buf;
Count := 0;
end Get;
entry Put (Item : in Positive) when Count < Index'Modulus is
begin
Buf (Next) := Item;
Next := Next + 1;
Count := Count + 1;
end Put;
end Buffer;
task producer is
entry Done;
end producer;
task body Producer is
Cur_Time : Time;
Pause : constant Duration := 1.0;
Count : Positive := 1;
begin
for Outer in 1 .. 10 loop
for Inner in 1 .. 60 loop
Buffer.Put (Count);
Cur_Time := Clock;
Count := Count + 1;
delay until Cur_Time + Pause;
end loop;
end loop;
accept Done;
end Producer;
task Consumer is
entry Stop;
end Consumer;
task body Consumer is
Batch : collect;
Sum : Integer := 0;
begin
loop
select
accept Stop;
exit;
else
select
Buffer.Get (Batch);
Sum := 0;
for val of Batch loop
Put (val'Image);
Sum := Sum + val;
end loop;
New_Line;
Put_Line ("Average:" & Integer'Image (Sum / Batch'Length));
or
delay 0.01;
end select;
end select;
end loop;
end Consumer;
begin
Producer.Done;
Consumer.Stop;
end Main;
The output of this program is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
Average: 30
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
Average: 90
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
Average: 150
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
Average: 210
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
Average: 270
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
Average: 330
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
Average: 390
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
Average: 450
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
Average: 510
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
Average: 570
[2019-11-08 08:57:07] process terminated successfully, elapsed time: 10:05.48s

Related

External signing PDF with iTextSharp - altered/corrupted document

The goal is to implement a PDF signing process in which the server (.NET Core service) provides the hash to be signed to the client on request (Electron). The client then signs the given hash using a private key obtained from a smart card through a PKCS#11 interface. The signature is then sent back to the server for attaching into the PDF file using iTextSharp.
The process of signing the hash with the smart card token is pretty much straightforward with node-webcrypto-p11 at the moment (with a lot of trial and error needed to get here). The algorithm used is RSASSA-PKCS1-v1_5. I can successfully sign the hash and verify it afterwards.
I recently built on my previous implementation with the help of External signing PDF with iTextsharp (3) where I used getAuthenticatedAttributeBytes for getting the hash to be signed (as suggested by mkl).
On reviewing the signature in Acrobat Reader, I am presented with the dreaded document altered/corrupted, same as the OP pgkdev. As mentioned above the client-side is straightforward with the signing process and I do not suspect any problems arising there (I am open for review of that though).
pgkdev referred to Priyanka's question, where I found out that I am probably having issues regarding the 2-step process of signing the document in which the hash values are no longer the same.
If you check Grazina's question we can see that such an implementation is successful, when you do the process in one step.
mkl further mentions a way to do it successfully in 2 steps, but I am missing some more explanation on how exactly to achieve that.
Note: There is no way for me (that I know of) to do what I want in 1 step, as the signing is initiated by a client in an Electron app.
Clicking on Certificate details shows my full certificate details.
private const string SIG_FIELD_NAME = "sigField1";
private byte[] GetPDFHash(string pdfFilePath, byte[] certificateValue)
{
var preparedSigPdfFilePath = $"{pdfFilePath}.tempsig.pdf";
//Get certificates chain from certificate value
ICollection<X509Certificate> certificatesChain = GetCertificatesChain(certificateValue);
byte[] hash = CreatePDFEmptySignature(pdfFilePath, preparedSigPdfFilePath, certificatesChain);
return hash;
}
private void SignPDFHash(string pdfFilePath, byte[] hash, byte[] signedHash, byte[] certificateValue)
{
var preparedSigPdfFilePath = $"{pdfFilePath}.tempsig.pdf";
var signedPdfFilePath = $"{pdfFilePath}.signed.pdf";
//Get certificates chain from certificate value
ICollection<X509Certificate> certificatesChain = GetCertificatesChain(certificateValue);
CreateFinalSignature(preparedSigPdfFilePath, signedPdfFilePath, hash, signedHash, certificatesChain);
}
private byte[] CreatePDFEmptySignature(string pdfFilePath, string preparedSigPdfFilePath, ICollection<X509Certificate> certificatesChain)
{
byte[] hash;
using (PdfReader reader = new PdfReader(pdfFilePath))
{
using (FileStream baos = System.IO.File.OpenWrite(preparedSigPdfFilePath))
{
PdfStamper pdfStamper = PdfStamper.CreateSignature(reader, baos, '\0', null, true);
PdfSignatureAppearance sap = pdfStamper.SignatureAppearance;
sap.SetVisibleSignature(new Rectangle(36, 720, 160, 780), 1, SIG_FIELD_NAME);
sap.Certificate = certificatesChain.First();
var externalEmptySigContainer = new MyExternalEmptySignatureContainer(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_DETACHED, preparedSigPdfFilePath, certificatesChain);
MakeSignature.SignExternalContainer(sap, externalEmptySigContainer, 8192);
hash = externalEmptySigContainer.PdfHash;
}
}
return hash;
}
private void CreateFinalSignature(string preparedSigPdfFilePath, string signedPdfFilePath,
byte[] hash, byte[] signedHash, ICollection<X509Certificate> certificatesChain)
{
using (PdfReader reader = new PdfReader(preparedSigPdfFilePath))
{
using (FileStream baos = System.IO.File.OpenWrite(signedPdfFilePath))
{
IExternalSignatureContainer externalSigContainer = new MyExternalSignatureContainer(hash, signedHash, certificatesChain);
MakeSignature.SignDeferred(reader, SIG_FIELD_NAME, baos, externalSigContainer);
}
}
}
public class MyExternalEmptySignatureContainer : ExternalBlankSignatureContainer
{
public string PdfTempFilePath { get; set; }
public byte[] PdfHash { get; private set; }
public ICollection<X509Certificate> CertificatesList { get; set; }
public MyExternalEmptySignatureContainer(PdfName filter, PdfName subFilter, string pdfTempFilePath,
ICollection<X509Certificate> certificatesChain) : base(filter, subFilter)
{
PdfTempFilePath = pdfTempFilePath;
CertificatesList = certificatesChain;
}
override public byte[] Sign(Stream data)
{
byte[] sigContainer = base.Sign(data);
//Get the hash
IDigest messageDigest = DigestUtilities.GetDigest("SHA-256");
byte[] messageHash = DigestAlgorithms.Digest(data, messageDigest);
#region Log
var messageHashFilePath = $"{PdfTempFilePath}.messageHash-b64.txt";
System.IO.File.WriteAllText(messageHashFilePath, Convert.ToBase64String(messageHash));
#endregion Log
//Add hash prefix
byte[] sha256Prefix = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };
byte[] digestInfo = new byte[sha256Prefix.Length + messageHash.Length];
sha256Prefix.CopyTo(digestInfo, 0);
messageHash.CopyTo(digestInfo, sha256Prefix.Length);
#region Log
var messageHashWithPrefixFilePath = $"{PdfTempFilePath}.messageHash-with-prefix-b64.txt";
System.IO.File.WriteAllText(messageHashWithPrefixFilePath, Convert.ToBase64String(digestInfo));
#endregion Log
var sgn = new PdfPKCS7(null, this.CertificatesList, "SHA256", false);
var authenticatedAttributeBytes =
sgn.getAuthenticatedAttributeBytes(messageHash, null, null, CryptoStandard.CMS);
PdfHash = authenticatedAttributeBytes;
return sigContainer;
}
}
public class MyExternalSignatureContainer : IExternalSignatureContainer
{
public byte[] Hash { get; set; }
public byte[] SignedHash { get; set; }
public ICollection<X509Certificate> CertificatesList { get; set; }
public MyExternalSignatureContainer(byte[] hash, byte[] signedHash, ICollection<X509Certificate> certificatesList)
{
Hash = hash;
SignedHash = signedHash;
CertificatesList = certificatesList;
}
public byte[] Sign(Stream data)
{
PdfPKCS7 sgn = new PdfPKCS7(null, this.CertificatesList, "SHA256", false);
sgn.SetExternalDigest(this.SignedHash, null, "RSA");
return sgn.GetEncodedPKCS7(this.Hash, null, null, null, CryptoStandard.CMS);
}
public void ModifySigningDictionary(PdfDictionary signDic) { }
}
private ICollection<X509Certificate> GetCertificatesChain(byte[] certByteArray)
{
ICollection<X509Certificate> certChain = new Collection<X509Certificate>();
X509Certificate2 cert = new X509Certificate2(certByteArray);
X509Certificate regularCert = new X509CertificateParser()
.ReadCertificate(cert.GetRawCertData());
certChain.Add(regularCert);
return certChain;
}
EDIT: Signed PDF
EDIT:
Adjusted CreateFinalSignature to use messageHash which was saved into a .txt file. The result is the same.
Signed PDF
private void CreateFinalSignature(string preparedSigPdfFilePath, string signedPdfFilePath, byte[] signedHash, ICollection<X509Certificate> certificatesChain)
{
var messageHashFilePath = $"{preparedSigPdfFilePath}.messageHash-b64.txt";
string hashString = System.IO.File.ReadAllText(messageHashFilePath);
byte[] hash = Convert.FromBase64String(hashString);
using (PdfReader reader = new PdfReader(preparedSigPdfFilePath))
{
using (FileStream baos = System.IO.File.OpenWrite(signedPdfFilePath))
{
IExternalSignatureContainer externalSigContainer = new MyExternalSignatureContainer(hash, signedHash, certificatesChain);
MakeSignature.SignDeferred(reader, SIG_FIELD_NAME, baos, externalSigContainer);
}
}
}
Hashes are identical, as shown below. I put some breakpoints to try and catch the values before saving and after reading from the file.
Byte array before saving:
[0] = {byte} 133
[1] = {byte} 170
[2] = {byte} 124
[3] = {byte} 73
[4] = {byte} 225
[5] = {byte} 104
[6] = {byte} 242
[7] = {byte} 79
[8] = {byte} 44
[9] = {byte} 52
[10] = {byte} 173
[11] = {byte} 6
[12] = {byte} 7
[13] = {byte} 250
[14] = {byte} 171
[15] = {byte} 50
[16] = {byte} 226
[17] = {byte} 132
[18] = {byte} 113
[19] = {byte} 31
[20] = {byte} 125
[21] = {byte} 174
[22] = {byte} 53
[23] = {byte} 98
[24] = {byte} 68
[25] = {byte} 117
[26] = {byte} 102
[27] = {byte} 191
[28] = {byte} 109
[29] = {byte} 180
[30] = {byte} 88
[31] = {byte} 133
Byte array read from .txt file in CreateFinalSignature:
[0] = {byte} 133
[1] = {byte} 170
[2] = {byte} 124
[3] = {byte} 73
[4] = {byte} 225
[5] = {byte} 104
[6] = {byte} 242
[7] = {byte} 79
[8] = {byte} 44
[9] = {byte} 52
[10] = {byte} 173
[11] = {byte} 6
[12] = {byte} 7
[13] = {byte} 250
[14] = {byte} 171
[15] = {byte} 50
[16] = {byte} 226
[17] = {byte} 132
[18] = {byte} 113
[19] = {byte} 31
[20] = {byte} 125
[21] = {byte} 174
[22] = {byte} 53
[23] = {byte} 98
[24] = {byte} 68
[25] = {byte} 117
[26] = {byte} 102
[27] = {byte} 191
[28] = {byte} 109
[29] = {byte} 180
[30] = {byte} 88
[31] = {byte} 133
EDIT: Hashing authenticatedAttributeBytes and then returning that hash to be signed by the client.
Tried 3 different ways of hashing, with same result:
PdfHash = DigestAlgorithms.Digest(new MemoryStream(authenticatedAttributeBytes), messageDigest)
PdfHash = SHA256.Create().ComputeHash(authenticatedAttributeBytes)
PdfHash = SHA256Managed.Create().ComputeHash(authenticatedAttributeBytes)
Usage of GetPDFHash
byte[] bytesToSign = GetPDFHash(Path.Combine(_configuration["documentFileSystemStore:DocumentFolder"], "SignMeMightySigner.pdf"), Convert.FromBase64String(dto.base64certificateValue));
Usage of SignPDFHash
SignPDFHash(Path.Combine(_configuration["documentFileSystemStore:DocumentFolder"], "SignMeMightySigner.pdf"),Convert.FromBase64String(dto.base64signature), Convert.FromBase64String(dto.base64certificateValue));
EDIT (29.3.2020):
I have checked my client side and can't find anything problematic. I choose the RSASSA-PKCS1-v1_5 alg to get the signature and verify it successfully afterwards. In some other questions I found that it could be a problem with transferring the byte array between the server and client, but I have checked and the values are the same, both base64 and the byte array.
Decided to open the PDF in a text editor and compare it to a regularly signed PDF (same text content, just signed directly through Adobe Reader).
What bothers and worries me, is that the PDF signed with iText is missing a huge chunk of "text" inside, that the directly signed one has.
Is there anything else I can provide for possible further analysis? I have seen a trend of people on Stack Overflow not being able to get past this problem, some even giving up on it completely. I do not want and can not do that and want to get to the bottom of it.
Directly signed through Adobe Reader
Deferred signing with iText
EDIT 30.3.2020:
As mentioned above I hash the AuthenticatedAttributeBytes
PdfHash = SHA256Managed.Create().ComputeHash(authenticatedAttributeBytes);
AuthenticatedAttributeBytes
49 75 48 24 6 9 42 134 72 134 247 13 1 9 3 49 11 6 9 42 134 72 134 247 13 1 7 1 48 47 6 9 42 134 72 134 247 13 1 9 4 49 34 4 32 122 115 111 54 139 240 60 168 176 67 64 158 55 107 233 48 77 220 19 208 139 187 42 1 141 149 20 241 151 80 31 79
AuthenticatedAttributeBytes - hashed
33 25 105 92 244 51 72 93 179 135 158 84 249 178 103 91 236 247 253 35 232 124 169 112 108 214 63 206 206 2 88 107
(returned to client) AuthenticatedAttributeBytes - hashed & base64 encoded
IRlpXPQzSF2zh55U+bJnW+z3/SPofKlwbNY/zs4CWGs=
Hash signed (signature)
76 13 184 229 123 212 2 8 140 24 34 88 95 31 255 142 105 220 204 186 172 110 61 75 156 44 185 62 81 209 238 226 67 133 115 247 76 24 182 144 38 164 71 92 124 140 77 16 212 43 52 156 173 90 163 116 0 124 119 119 103 8 12 74 147 1 207 51 156 104 52 231 112 125 115 140 28 105 160 117 235 199 224 166 30 220 111 35 165 49 18 85 253 194 112 254 142 117 46 58 87 13 110 161 151 228 95 238 115 171 70 117 203 103 204 222 233 42 163 37 105 91 177 117 190 238 135 137 162 6 54 125 108 64 148 219 7 198 93 117 12 164 130 123 213 197 233 173 145 77 209 11 166 91 29 137 142 25 20 96 90 130 251 169 234 9 44 245 230 20 46 243 254 98 179 98 148 87 104 151 228 246 231 23 94 134 144 84 177 219 235 90 11 130 33 139 94 155 73 112 60 88 53 150 59 49 184 100 210 82 32 71 66 168 21 167 91 141 94 239 221 156 96 23 132 147 237 15 237 232 112 214 224 61 117 46 143 208 41 64 13 128 44 69 135 172 113 58 8 85 5 176 192 254 107 92
(received from client) Hash signed (signature) - base64
TA245XvUAgiMGCJYXx//jmnczLqsbj1LnCy5PlHR7uJDhXP3TBi2kCakR1x8jE0Q1Cs0nK1ao3QAfHd3ZwgMSpMBzzOcaDTncH1zjBxpoHXrx+CmHtxvI6UxElX9wnD+jnUuOlcNbqGX5F/uc6tGdctnzN7pKqMlaVuxdb7uh4miBjZ9bECU2wfGXXUMpIJ71cXprZFN0QumWx2JjhkUYFqC+6nqCSz15hQu8/5is2KUV2iX5PbnF16GkFSx2+taC4Ihi16bSXA8WDWWOzG4ZNJSIEdCqBWnW41e792cYBeEk+0P7ehw1uA9dS6P0ClADYAsRYescToIVQWwwP5rXA==
The signature bytes (decoded from base64) match the logged uint8array on client side.
Your original code
In MyExternalEmptySignatureContainer.Sign you correctly determine the authenticated attributes using the naked hash of the PDF range stream:
var authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(messageHash, null, null, CryptoStandard.CMS);
Inspecting your example file, though, I find that the signed Message Digest attribute contains the hash embedded in a DigestInfo object, in other works with the sha256Prefix you apply to a copy of the message digest in MyExternalEmptySignatureContainer.Sign.
Apparently, therefore, when you re-create the autheticated attributes in MyExternalSignatureContainer.Sign
return sgn.GetEncodedPKCS7(this.Hash, null, null, null, CryptoStandard.CMS);
you do so with the wrong value in this.Hash. This has two effects, on one hand obviously the value of the Message Digest attribute now is incorrect and on the other hand the signature value created for the original, correct authenticated attributes does not match your incorrect ones. Thus, the resulting PDF signature is doubly incorrect.
To fix this use the correct hash value here, the hash of the PDF range stream without that prefix.
As you don't show how exactly you use your methods GetPDFHash and SignPDFHash, I cannot pinpoint the error more precisely.
Your updated code
Indeed, now the correct hash is in the Message Digest attribute but the signature still signs a wrong hash, in case of your new example:
Signed Attributes Hash: 54B2F135A542EEAA55270AB19210E363D00A7684405403E89B170591A7BCAB5F
Decrypted signature digest: 22D906E686A83FA1A490895A21CD6F9A9272C13FB9B16D8A6E862168458F3640
The cause probably is that the contents of your MyExternalEmptySignatureContainer property PdfHash is not a hash but the complete authenticated attributes bytes, cf. MyExternalEmptySignatureContainer.Sign:
var authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(messageHash, null, null, CryptoStandard.CMS);
PdfHash = authenticatedAttributeBytes;
You probably have to calculate the hash of authenticatedAttributeBytes and put that into PdfHash.
As you don't show how exactly you use your methods GetPDFHash and SignPDFHash, though, this can only be guessed.
Your logged hashes
On March 30th you shared logs of the relevant data transported in one run. In particular:
AuthenticatedAttributeBytes - hashed
33 25 105 92 244 51 72 93 179 135 158 84 249 178 103 91 236 247 253 35 232 124 169 112 108 214 63 206 206 2 88 107
and
Hash signed (signature)
76 13 184 229 123 212 2 8 140 24 34 88 95 31 255 142 105 220 204 186 172 110 61 75 156 44 185 62 81 209 238 226 67 133 115 247 76 24 182 144 38 164 71 92 124 140 77 16 212 43 52 156 173 90 163 116 0 124 119 119 103 8 12 74 147 1 207 51 156 104 52 231 112 125 115 140 28 105 160 117 235 199 224 166 30 220 111 35 165 49 18 85 253 194 112 254 142 117 46 58 87 13 110 161 151 228 95 238 115 171 70 117 203 103 204 222 233 42 163 37 105 91 177 117 190 238 135 137 162 6 54 125 108 64 148 219 7 198 93 117 12 164 130 123 213 197 233 173 145 77 209 11 166 91 29 137 142 25 20 96 90 130 251 169 234 9 44 245 230 20 46 243 254 98 179 98 148 87 104 151 228 246 231 23 94 134 144 84 177 219 235 90 11 130 33 139 94 155 73 112 60 88 53 150 59 49 184 100 210 82 32 71 66 168 21 167 91 141 94 239 221 156 96 23 132 147 237 15 237 232 112 214 224 61 117 46 143 208 41 64 13 128 44 69 135 172 113 58 8 85 5 176 192 254 107 92
Decrypting that latter signed hash value using the public key from your certificate, though, one gets a DigestInfo object containing this hash:
136 138 205 115 82 228 115 151 231 220 177 93 171 239 123 224 245 180 234 166 132 201 244 54 69 22 18 16 115 223 70 193
Thus, whatever your client side code does, it does not create a signature for your pre-hashed AuthenticatedAttributeBytes. Probably it hashes the hash bytes again, probably it hashes a base64 representation of them, probably it uses some random number, but it does not what you expect it to do.
You should find out what your client code actually does and fix it or feed it the data it requires.
E.g. if your client side code cannot be kept from re-hashing the data, feed it the un-hashed authenticated attribute bytes.

How to decode the payload sent on handshake for a Websocket (I'm using Websocket-Sharp)?

I'm using the Websocket-Sharp library to make a client connection to an existing socket service.
My client code has this:
using (var ws = new WebSocketSharp.WebSocket("wss://localhost"))
{
ws.OnMessage += (sender, e) => Console.WriteLine("Received: " + e.Data);
ws.Connect();
ws.Send(myByteBuffer);
}
When the .Connect() call is made, it hits a breakpoint in my service code. The buffer payload contains some payload that looks like a handshake payload but I'm not sure how to decode this.
The buffer has a length of 113 and has an output of this:
[0]: 22
[1]: 3
[2]: 1
[3]: 0
[4]: 108
[5]: 1
[6]: 0
[7]: 0
[8]: 104
[9]: 3
[10]: 1
[11]: 93
[12]: 167
[13]: 1
[14]: 205
[15]: 150
[16]: 142
[17]: 39
[18]: 230
[19]: 167
[20]: 52
[21]: 174
[22]: 70
[23]: 22
[24]: 9
[25]: 114
[26]: 33
[27]: 155
[28]: 53
[29]: 94
[30]: 87
[31]: 212
[32]: 71
[33]: 71
[34]: 107
[35]: 172
[36]: 202
[37]: 248
[38]: 191
[39]: 215
[40]: 29
[41]: 156
[42]: 98
[43]: 0
[44]: 0
[45]: 14
[46]: 192
[47]: 10
[48]: 192
[49]: 9
[50]: 192
[51]: 20
[52]: 192
[53]: 19
[54]: 0
[55]: 53
[56]: 0
[57]: 47
[58]: 0
[59]: 10
[60]: 1
[61]: 0
[62]: 0
[63]: 49
[64]: 0
[65]: 0
[66]: 0
[67]: 14
[68]: 0
[69]: 12
[70]: 0
[71]: 0
[72]: 9
[73]: 108
[74]: 111
[75]: 99
[76]: 97
[77]: 108
[78]: 104
[79]: 111
[80]: 115
[81]: 116
[82]: 0
[83]: 10
[84]: 0
[85]: 8
[86]: 0
[87]: 6
[88]: 0
[89]: 29
[90]: 0
[91]: 23
[92]: 0
[93]: 24
[94]: 0
[95]: 11
[96]: 0
[97]: 2
[98]: 1
[99]: 0
[100]: 0
[101]: 35
[102]: 0
[103]: 0
[104]: 0
[105]: 23
[106]: 0
[107]: 0
[108]: 255
[109]: 1
[110]: 0
[111]: 1
[112]: 0
Does anyone know how I can decode this and handle this? I assume it's a standard handshake message that needs to be handled but I can't work out how to do it correctly.
Thanks in advance

While loop to populate datagridview with array

I have a set of data that I need to populate a data grid view with once it reaches a certain point in the text file.
Once the (StreamReader reader = new StreamReader(fileOpen)) reaches [HRData] in the file I would like to store each column into an array for storing into a datagridview and looping to the end of the file
[HRData]
91 154 70 309 83 6451
91 154 70 309 83 6451
92 160 75 309 87 5687
94 173 80 309 87 5687
96 187 87 309 95 4662
100 190 93 309 123 4407
101 192 97 309 141 4915
103 191 98 309 145 5429
106 190 99 309 157 4662
106 187 98 309 166 4399
107 186 97 309 171 4143
107 185 97 309 170 4914
108 184 96 309 171 5426
108 183 95 309 170 5688
you can use LINQ to produce a list (each element is a line) of arrays (each element is number in that line)
List<string[]> result = File.ReadAllLines("filePath") //read all lines in the file
.SkipWhile(x => x != "[HRData]") //skip lines until reaching the "[HRData]"
.Select(x => x.Split(null, StringSplitOptions.RemoveEmptyEntries)) //split line by whitespace to get numbers in line
.ToList(); // convert the result to a list
you can then use result.ForEach(x => dataGridView1.Rows.Add(x))

Fastest way to query a Map of Integers to extract related Linked Integers

I am writing code for an embedded device, I have a map of numbers, shown below is a subset ranging from 151 to 66, the adjacent numbers are linked numbers, so for 151, its linked numbers would be 150 - 148 - 146 - 136 - 131 - 91 - and so on, I have a method which accepts two parameters int startNum and int endNum and the goal is to return an array containing 2 integers which will link me from startNum to endNum, so for an example see below
startNum = 126
endNum = 75
linked nums would be 105,90, since 126 brings me to 105, 105 brings me to 90 and 90 takes me to 75, and there are several other paths which will do this, my question is is it possible to figure out these linked numbers without using nested for loops and testing every possible combination.
151 = 150 - 148 - 146 - 136 - 131 - 91 -
150 = 149 - 147 - 145 - 135 - 130 - 90 -
149 = 148 - 146 - 144 - 134 - 129 - 89 -
148 = 147 - 145 - 143 - 133 - 128 - 88 -
147 = 146 - 144 - 142 - 132 - 127 - 87 -
146 = 143 - 139 - 137 - 127 - 125 - 89 -
145 = 144 - 142 - 140 - 130 - 125 - 85 -
144 = 143 - 141 - 139 - 129 - 124 - 84 -
143 = 142 - 140 - 138 - 128 - 123 - 83 -
142 = 141 - 139 - 137 - 127 - 122 - 82 -
141 = 140 - 138 - 136 - 126 - 121 - 81 -
140 = 139 - 137 - 135 - 125 - 120 - 80 -
139 = 136 - 132 - 130 - 120 - 118 - 82 -
138 = 137 - 135 - 133 - 123 - 118 - 78 -
137 = 136 - 134 - 132 - 122 - 117 - 77 -
136 = 135 - 133 - 131 - 121 - 116 - 76 -
135 = 134 - 133 - 132 - 131 - 130 - 129 -
134 = 133 - 131 - 129 - 119 - 114 - 74 -
133 = 132 - 130 - 128 - 118 - 113 - 73 -
132 = 131 - 130 - 129 - 128 - 127 - 126 -
131 = 130 - 128 - 126 - 116 - 111 - 71 -
130 = 129 - 127 - 125 - 115 - 110 - 70 -
129 = 126 - 122 - 120 - 110 - 108 - 72 -
128 = 127 - 125 - 124 - 116 - 110 - 74 -
127 = 126 - 124 - 122 - 112 - 107 - 67 -
126 = 123 - 119 - 117 - 107 - 105 - 69 -
125 = 124 - 123 - 122 - 121 - 120 - 119 -
124 = 123 - 121 - 119 - 109 - 104 - 64 -
123 = 120 - 116 - 114 - 104 - 102 - 66 -
122 = 121 - 119 - 118 - 110 - 104 - 68 -
121 = 120 - 118 - 116 - 106 - 101 - 61 -
120 = 119 - 117 - 115 - 105 - 100 - 60 -
119 = 116 - 112 - 110 - 100 - 98 - 62 -
118 = 117 - 115 - 113 - 103 - 98 - 58 -
117 = 116 - 114 - 112 - 102 - 97 - 57 -
116 = 115 - 113 - 111 - 101 - 96 - 56 -
115 = 112 - 108 - 106 - 96 - 94 - 58 -
114 = 113 - 111 - 109 - 99 - 94 - 54 -
113 = 112 - 110 - 108 - 98 - 93 - 53 -
112 = 111 - 109 - 107 - 97 - 92 - 52 -
111 = 108 - 104 - 102 - 92 - 90 - 54 -
110 = 109 - 107 - 105 - 95 - 90 - 50 -
109 = 108 - 106 - 104 - 94 - 89 - 49 -
108 = 105 - 101 - 99 - 89 - 87 - 51 -
107 = 106 - 104 - 102 - 92 - 87 - 47 -
106 = 105 - 103 - 101 - 91 - 86 - 46 -
105 = 104 - 102 - 100 - 90 - 85 - 45 -
104 = 103 - 101 - 99 - 89 - 84 - 44 -
103 = 102 - 100 - 98 - 88 - 83 - 43 -
102 = 101 - 99 - 97 - 87 - 82 - 42 -
101 = 100 - 98 - 96 - 86 - 81 - 41 -
100 = 99 - 97 - 95 - 85 - 80 - 40 -
99 = 96 - 92 - 90 - 80 - 78 - 42 -
98 = 97 - 95 - 93 - 83 - 78 - 38 -
97 = 94 - 90 - 88 - 78 - 76 - 40 -
96 = 95 - 93 - 91 - 81 - 76 - 36 -
95 = 94 - 93 - 92 - 91 - 90 - 89 -
94 = 93 - 92 - 91 - 90 - 89 - 88 -
93 = 92 - 91 - 90 - 89 - 88 - 87 -
92 = 91 - 89 - 87 - 77 - 72 - 32 -
91 = 90 - 89 - 88 - 87 - 86 - 85 -
90 = 89 - 87 - 85 - 75 - 70 - 30 -
89 = 86 - 82 - 80 - 70 - 68 - 32 -
88 = 87 - 85 - 83 - 73 - 68 - 28 -
87 = 85 - 84 - 81 - 78 - 70 - 36 -
86 = 85 - 83 - 82 - 74 - 68 - 32 -
85 = 82 - 78 - 76 - 66 - 64 - 28 -
84 = 83 - 81 - 79 - 69 - 64 - 24 -
83 = 81 - 80 - 77 - 74 - 66 - 32 -
82 = 81 - 80 - 79 - 78 - 77 - 76 -
81 = 78 - 74 - 72 - 62 - 60 - 24 -
80 = 79 - 77 - 75 - 65 - 60 - 20 -
79 = 76 - 72 - 70 - 60 - 58 - 22 -
78 = 77 - 75 - 74 - 66 - 60 - 24 -
77 = 74 - 70 - 68 - 58 - 56 - 20 -
76 = 75 - 73 - 71 - 61 - 56 - 16 -
75 = 73 - 72 - 69 - 66 - 58 - 24 -
74 = 65 - 63 - 60 - 47 - 41 - 32 -
73 = 70 - 66 - 64 - 54 - 52 - 16 -
72 = 65 - 64 - 56 - 51 - 48 - 24 -
71 = 67 - 65 - 59 - 58 - 53 - 32 -
70 = 69 - 67 - 66 - 58 - 52 - 16 -
69 = 67 - 63 - 59 - 54 - 39 - 24 -
68 = 63 - 59 - 56 - 53 - 41 - 32 -
67 = 65 - 64 - 61 - 58 - 50 - 16 -
66 = 60 - 56 - 51 - 48 - 36 - 21 -
I would model these lists of linked numbers as a graph i.e. numbers as nodes/vertices and links between nodes as edges. The first line in your example looks as follows:
151 = 136 - 148 - 146 - 150 - 91 - 131 -
So a node 151 would be connected with a node 136, the node 136 with a node 148, the node 148 with a node 146 etc.
EDIT
After a comment from #cahinton I'm not sure if above interpretation of these lists is correct. Another one is that a node 151 would be connected with nodes: 136, 148, 146, 150...
You can read line by line adding nodes and edges to your graph. Each edge should have the same weight = 1. When you have a final graph you can use Dijkstra's algorithm to find the shortes paths between any two numbers (nodes).
The complexity of the basic implementation of Dijkstra's algorithm is O(N^2) where N - number of nodes. There are also more efficient implementations if you need it. In your case the basic solution should be enough because you will have only 151 - 66 = 85 nodes.
If you don't want to implement everything from the scratch you can use one of many graph libraries. Personally I like QuickGraph There is even a question how to use Dijkstra in this library.

RTSP converting ASF RTP-Packets to video data

I'm working on a program processing streaming data based on MS-RTSP protocol
and it's working quite well so far, getting UDP packet by RTSP.
The problem is- I cannot get through converting UDP packets to video data.
I have MS-RTSP-SPEC, RFC-2326 and MS-ASF-SPECIFICATION document,
But I have no idea what kind of data structure do 'ASF payload headers and compressed media data'
MS-RTSP DOCUMENT
Following data is one of the received packets from RTP connection,
And I have no idea which part of this MS-ASF-SPEC document has explanation of the 'ASF payload headers and compressed media data'
MS-ASF-SPECIFICATION DOCUMENT
Please help me QQ
Message Log
::first Packet
==RTP Header==
00 = 128 096 059 199 000 000 000 000 006 072 087 109
==RTP Payload format Header==
00 = 128 000 000 000
S=True L=False R=False D=False I=False RES=0 LENGTH=0
==ASF Data packet Header==
00 = 130 000 000 009 093 000 000 000 000 000 000 000
==ASF payload headers and compressed media data==
00 = 131 130 001 000 000 000 000 010 026 001 000 000 184 011 000 000
01 = 041 000 026 001 000 008 016 048 060 087 225 225 222 023 133 225
02 = 120 094 023 133 225 120 094 023 133 225 120 094 023 133 225 120
03 = 094 023 133 225 120 094 023 133 225 120 094 023 133 225 120 094
04 = 023 133 225 120 094 023 133 225 120 094 023 133 225 120 094 023
...
45 = 211 227 138 112 047 081 032 192 234 137 112
::second Packet
==RTP Header==
00 = 128 224 059 200 000 000 000 000 006 072 087 109
==RTP Payload format Header==
00 = 128 000 002 247
S=True L=False R=False D=False I=False RES=0 LENGTH=759
==ASF Data packet Header==
00 = 088 009 135 027 150 032 101 060 144 095 176 022
==ASF payload headers and compressed media data==
00 = 045 096 089 208 024 094 230 135 137 246 055 245 023 109 003 128
01 = 008 243 194 154 187 080 155 234 249 117 095 023 070 136 140 081
02 = 176 175 040 219 021 248 092 231 166 111 200 153 103 223 156 114
03 = 062 050 010 096 205 196 048 116 121 052 095 073 177 008 122 180
04 = 022 078 008 140 224 142 132 220 040 144 226 088 099 177 189 244
...
45 = 173 184 024 007 238 195 035 015 012 125 041
Microsoft implemented this in their ConferenceXP package. Download the stuff here:
http://research.microsoft.com/en-us/projects/conferencexp/
Then use your favorite .NET disassembler to pull apart the RtpStream/RtpPacket stuff from the MSR.LST.Net.Rtp assembly. Or you could possibly use their classes to deal with your data.

Categories