make an identical sha512 in C # and mysql - c#

I want to make an identical sha512 in C# and mysql.
c#
System.Security.Cryptography.SHA512.Create().ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes("test"));
C# results Length 64
238 38 176 221 74 247 231 73 170 26 142 227 193 10 233 146 63 97 137 128 119 46 71 63 136 25 165 212 148 14 13 178 122 193 133 248 160 225 213 248 79 136 188 136 127 214 123 20 55 50 195 4 204 95 169 173 142 111 87 245 0 40 168 255
mysql
INSERT INTO users_table (password) VALUES ( SHA2("test", 512));
// password is a BINARY(128)
mysql results Length 128
101 101 50 54 98 48 100 100 52 97 102 55 101 55 52 57 97 97 49 97 56 101 101 51 99 49 48 97 101 57 57 50 51 102 54 49 56 57 56 48 55 55 50 101 52 55 51 102 56 56 49 57 97 53 100 52 57 52 48 101 48 100 98 50 55 97 99 49 56 53 102 56 97 48 101 49 100 53 102 56 52 102 56 56 98 99 56 56 55 102 100 54 55 98 49 52 51 55 51 50 99 51 48 52 99 99 53 102 97 57 97 100 56 101 54 102 53 55 102 53 48 48 50 56 97 56 102 102
I compare them in bytes from,
but the results are different from each other : (
thankful for help!
best regards johan

MySql is returning a hex-encoded string:
As of MySQL 5.5.6, the return value is a nonbinary string in the
connection character set. Before 5.5.6, the return value is a binary
string; see the notes at the beginning of this section about using the
value as a nonbinary string.
You can tell this is happening because C#'s first byte is 238, which is 0xee, and the ASCII code for e is 101 -- MySql's return begins with 101 101. So you just need to turn the hex-encoded string into a binary string again with UNHEX (but only on MySql > 5.5.6).
So to receive identical results in your case:
INSERT INTO users_table (password) VALUES (UNHEX(SHA2("test", 512)));
And using MySql conditional comments (oh the ugliness!) to be portable across versions:
INSERT INTO users_table (password) VALUES (/*!50506 UNHEX(*/SHA2("test",512)/*!50506 )*/);

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.

C# RegEx a value between numbers and characters?

Hello I want to search for the first occurrence of a specific string and capture a value between a set length of numbers and characters that change.
Using Nate Barbettini’s https://dotnetfiddle.net/vhkUV5 example I butchered it into doing what I almost need, it won’t compile and from what I’ve seen my RegEx is way off so I defiantly need help with it.
In my example I want to find the first occurrence of the PID value “116c” for chrome.exe and not all three PID values. What’s the best way to get one PID value?
Code:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var output = #"
0a80 6e 6f 74 65 70 61 64 2b 2b 2e 65 78 65 20 20 20 notepad++.exe
0a90 50 49 44 3d 31 64 38 63 7c 30 37 35 36 34 0d 0a PID=1d8c|07564..
0aa0 6a 68 69 5f 73 65 72 76 69 63 65 2e 65 78 20 20 jhi_service.ex
0ab0 50 49 44 3d 31 38 64 34 7c 30 36 33 35 36 0d 0a PID=18d4|06356..
0ac0 4c 4d 53 2e 65 78 65 20 20 20 20 20 20 20 20 20 LMS.exe
0ad0 50 49 44 3d 31 63 36 38 7c 30 37 32 37 32 0d 0a PID=1c68|07272..
0ae0 63 6d 64 2e 65 78 65 20 20 20 20 20 20 20 20 20 cmd.exe
0af0 50 49 44 3d 30 66 37 38 7c 30 33 39 36 30 0d 0a PID=0f78|03960..
0b00 63 6f 6e 68 6f 73 74 2e 65 78 65 20 20 20 20 20 conhost.exe
0b10 50 49 44 3d 30 62 64 30 7c 30 33 30 32 34 0d 0a PID=0bd0|03024..
0b20 76 63 74 69 70 2e 65 78 65 20 20 20 20 20 20 20 vctip.exe
0b30 50 49 44 3d 31 38 30 38 7c 30 36 31 35 32 0d 0a PID=1808|06152..
0b40 63 68 72 6f 6d 65 2e 65 78 65 20 20 20 20 20 20 chrome.exe
0b50 50 49 44 3d 31 31 36 63 7c 30 34 34 36 30 0d 0a PID=116c|04460..
0b60 63 68 72 6f 6d 65 2e 65 78 65 20 20 20 20 20 20 chrome.exe
0b70 50 49 44 3d 31 36 39 34 7c 30 35 37 38 30 0d 0a PID=1694|05780..
0b80 63 68 72 6f 6d 65 2e 65 78 65 20 20 20 20 20 20 chrome.exe
0b90 50 49 44 3d 31 30 62 30 7c 30 34 32 37 32 0d 0a PID=10b0|04272..";
var regex = new Regex(#"chrome.exe[\s].................................................................(.*)........");
var resultList = new List<string>();
foreach (Match match in regex.Matches(output))
{
resultList.Add(match.Groups[1].ToString());
}
var pid = string.Join(", ", resultList);
Console.WriteLine(pid);
}
}
Output:
116c, 1694, 10b0
I’m extremely new so any help or pointers are welcome.
Try this code:
var regex = new Regex("chrome\\.exe\\s*.*PID=(.*)\\|");
var pid = regex.Matches(output)
.Cast<Match>()
.Select(match => match.Groups[1].ToString())
.First();
You can test the regular expression here.

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