I am receiving an AS2 message from my trading partner. I have successfully decrypted it and it has following content:
Content-Type: multipart/signed; boundary="----1E2FB76A361B53C9D12B3971C32BC0D8"; protocol="application/pkcs7-signature"; micalg="sha-256"
------1E2FB76A361B53C9D12B3971C32BC0D8
Content-Transfer-Encoding: binary
Content-Disposition: attachment; filename="edi.dat"
Content-Type: application/octet-stream; charset="ascii"; name="edi.dat"
ISA*00* *00* *ZZ*SPSAS2 *ZZ*SPSAS2 *140919*1159*|*00501*100000001*0*P*>
GS*PO*AS2S3REC*AS2S3SEND*20140919*1159*123*X*005010
ST*850*1234
BEG*00*SA*SPSAS2TEST**20121017
REF*IA*TEST
PER*OC*Someone*TE*2844994944
DTM*001*20121025
N1*ST*SomeoneElse
N3*My address is private
N4*ST THOMAS*VI*00801
PO1*54812*1*EA***SK*123546*VP*123546*UP*123456987111
CTT*1
SE*11*1234
GE*1*123
IEA*1*100000001
------1E2FB76A361B53C9D12B3971C32BC0D8
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"
Content-Type: application/pkcs7-signature; name="smime.p7s"
MIIL5gYJKoZIhvcNAQcCoIIL1zCCC9MCAQExDzANBglghkgBZQMEAgEFADALBgkq
hkiG9w0BBwGgggg3MIIIMzCCBxugAwIBAgIQCq+jbObLeCwtsdF61BAtBzANBgkq
hkiG9w0BAQsFADBNMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
MScwJQYDVQQDEx5EaWdpQ2VydCBTSEEyIFNlY3VyZSBTZXJ2ZXIgQ0EwHhcNMTgw
MjA5MDAwMDAwWhcNMjEwMjE3MTIwMDAwWjCBgjELMAkGA1UEBhMCVVMxEjAQBgNV
BAgTCU1pbm5lc290YTEUMBIGA1UEBxMLTWlubmVhcG9saXMxGzAZBgNVBAoTElNQ
UyBDb21tZXJjZSwgSW5jLjELMAkGA1UECxMCSVQxHzAdBgNVBAMTFnNwc2FzMi5j
b21tZXJjZXZhbi5jb20wggIiMA0GCSqGSIb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iGyHa
GQef4vZL1faz7ljxnx/MJKiWAbq07F7tYEHGyVTkO3MGF/wBe8vDlYs3U1T4v+2g
hjEWiOyREYTt9a4XJ1QcscjbGCRl28BajmxBBHibkSM2o5ztLxPUoiEKjY3XQc6J
oHX3Gmj63qMQPQz58AVoalGtwxOxlJiFc0Y13NIydbxMRuxep0XHVNE5XFQGE1K/
2r5iV4pS1f+EarDxfjzkrUwZFYJLdO27DqIL//6m6uTiIgZBXnzqulWlLxX17MCD
2yUOTRPGqo9eRhnrtbeh3PYGXG0zhGSdmzoTQr2mf2k7EDB/48BGvUWeHGsc7sQT
LUrlnLKqiG1uRB4sWTWMtxsKtH8kGP824ihszLh+13IXlMztCEg+kh472KQENguC
Yxt8DzcvxMi0rIsbsC/Thq3nxpFCGDV7m3Q=
------1E2FB76A361B53C9D12B3971C32BC0D8--
It has the signature in "Base64" format and "pkcs7-signature". I am not able to match signature. I am considering following part as main data:
ISA*00* *00* *ZZ*SPSAS2 *ZZ*SPSAS2 *140919*1159*|*00501*100000001*0*P*>
GS*PO*AS2S3REC*AS2S3SEND*20140919*1159*123*X*005010
ST*850*1234
BEG*00*SA*SPSAS2TEST**20121017
REF*IA*TEST
PER*OC*Someone*TE*2844994944
DTM*001*20121025
N1*ST*SomeoneElse
N3*My address is private
N4*ST THOMAS*VI*00801
PO1*54812*1*EA***SK*123546*VP*123546*UP*123456987111
CTT*1
SE*11*1234
GE*1*123
IEA*1*100000001
and base64 string as sign. and sung following function to match sign:
static bool Verify(string text, byte[] signature, string certPath)
{
X509Certificate2 cert = new X509Certificate2(certPath);
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
// Verify the signature with the hash
return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
}
But this function is not matching the signature.
Please help me with this problem.
Thank you...
I can't, personally, get the data to validate. (I'm assuming that either there are trailing spaces that aren't copying correctly or that the payload has been altered (e.g. "My address is private"))
The flow that I expect is happening:
The pkcs7 content is a CMS SignedData with detached content.
The signed content was specified in the first stream
So you need to do something like:
byte[] dataBytes = ReadFirstSegment();
byte[] signatureBytes = ReadSecondSegment();
SignedCms cms = new SignedCms(new ContentInfo(dataBytes), detached: true);
cms.Decode(signatureBytes);
// This next line throws a CryptographicException if the signature can't be verified
cms.CheckSignature(true);
SignerInfoCollection signers = cms.SignerInfos;
if (signers.Count != 1)
{
// probably fail
}
if (!IsExpectedCertificate(signers[0].Certificate))
{
// fail
}
// success
Related
I am using Mimekit to do rsa pss cms sign, to simulate this openssl command
openssl cms -sign -in keys.zip -binary -nodetach -signer selfsigned.crt -inkey keypair.pem -out keys.zip.signed -keyopt rsa_padding_mode:pss
public byte[] Sign(byte[] data, byte[] signCert, byte[] privateKey, CmsKeyOpt cmsKeyOpt)
{
MimeMessage message = new MimeMessage
{
Body = new MimePart()
{
Content = new MimeContent(new MemoryStream(data)),
ContentTransferEncoding = ContentEncoding.Binary,
},
};
// Load private key from byte array
StreamReader stream = new StreamReader(new MemoryStream(privateKey), Encoding.Default);
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)new PemReader(stream).ReadObject();
// load certifacte from byte array
X509CertificateParser parser = new X509CertificateParser();
X509Certificate certificate = parser.ReadCertificate(signCert);
// Create RSA PSS CMS signer
CmsSigner signer = new CmsSigner(certificate, keyPair.Private)
{
RsaSignaturePadding = RsaSignaturePadding.Pss,
DigestAlgorithm = DigestAlgorithm.Sha256,
};
// Create BouncyCastle Secure MimeContext
BouncyCastleSecureMimeContext ctx = new TemporarySecureMimeContext();
ctx.EncapsulatedSign(signer, new MemoryStream(data));
// Get signed message body and override it
message.Body = MultipartSigned.Create(ctx, signer, message.Body);
byte[] singedData;
using (var memory = new MemoryStream())
{
message.WriteTo(memory);
singedData = memory.ToArray();
}
return singedData;
}
And everything works fine, my question how I can achieve verify by Mimekit/BouncyCastle, to simulate this openssl command
openssl cms -verify -in keys.zip.signed.dec -CAfile selfsigned.crt -out keys_dec_unsigned.zip
I tried this but I got exception System.NotSupportedException: 'SQLite is not available on pkcs7.Verify(out original) line
public byte[] Verify(byte[] data, byte[] signCert, byte[] privateKey)
{
bool valid = false;
// Load private key from byte array
StreamReader stream = new StreamReader(new MemoryStream(privateKey), Encoding.Default);
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)new PemReader(stream).ReadObject();
// load certifacte from byte array
X509CertificateParser parser = new X509CertificateParser();
X509Certificate certificate = parser.ReadCertificate(signCert);
MimeMessage message = MimeMessage.Load(new MemoryStream(data));
// Create BouncyCastle Secure MimeContext
MimeEntity original;
ApplicationPkcs7Mime pkcs7 = message.Body as ApplicationPkcs7Mime;
if (pkcs7 != null && pkcs7.SecureMimeType == SecureMimeType.SignedData)
{
foreach (var signature in pkcs7.Verify(out original))
{
try
{
valid = signature.Verify();
}
catch (DigitalSignatureVerifyException)
{
// There was an error verifying the signature.
}
}
}
byte[] res = { 0 };
return res;
}
Is there any guide I can follow to verify and return the data to it's origin forum, or an example?
By default, MimeKit tries to instantiate a S/MIME verify context based on its SQLite backend for certificate storage.
If you don't have SQLite installed and/or don't have your certificates stored in the SQLite database that MimeKit will maintain for you, then you need to either register a different backend for certificate storage/retrieval or instantiate your own S/MIME context (like you did for signing).
MimeKit comes with 2 options:
TemporarySecureMimeContext which stores certificates in memory and is what you used to sign the message in your code snippet above.
WindowsSecureMimeContext which uses the Windows OS X.509 certificate store.
Once you decide on which of those to use, you will need to import your certificate(s) into the context (which will import them into the appropriate backend storage location).
Then, after that, you can do this:
using (BouncyCastleSecureMimeContext ctx = new TemporarySecureMimeContext()) {
ctx.Import (...);
foreach (var signature in pkcs7.Verify(ctx, out original)) {
// ...
}
}
Update:
This devolved into misuse of the openssl cms sign command and an inability to verify the signature using MimeKit because MimeKit expects the encapsulated signed data to be in MIME format as it is supposed to be according to the S/MIME specifications.
Here's the deal:
The openssl cms sign command can be used to sign arbitrary data and the corresponding openssl cms verify command can be used to verify such signed output. HOWEVER, it is only valid S/MIME if the original content signed by the openssl cms sign command is/was in MIME format.
MimeKit expects valid S/MIME because it is... surprise, surprise... a MIME library.
As you might have noticed, the Verify() method has an output parameter (out MimeEntity originalEntity). This means that the Verify() method extracts the encapsulated content from within the signed data and parses it into a MIME entity and returns it to you, the caller, in the form of said output parameter.
If the encapsulated content is not in MIME format, then, obviously, the parser will fail to parse it.
Additional background with how CMS signatures work:
When you sign content using the CMS signing routine (e.g. openssl cms sign ...), it produces something that looks a bit like this:
MIME-Version: 1.0
Content-Disposition: attachment; filename="smime.p7m"
Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m"
Content-Transfer-Encoding: base64
MIIQgAYJKoZIhvcNAQcCoIIQcTCCEG0CAQExDTALBglghkgBZQMEAgEwggkPBgkq...
The base64 content in the above MIME part includes both the original content and the CMS signature data (i.e. a list of signatures).
Therefor, MimeKit's Verify() method needs to separate the signatures from the original content after base64 decoding it. MimeKit then returns to you, the caller, the original content (which it expects to be in MIME format) and the list of signatures that you can then independently verify the authenticity of.
When I kept repeating myself that it mattered what format the file.bin file was in when you signed the content, I was not saying that openssl or MimeKit needed to parse file.bin when verifying the signature, I was saying that file.bin has exactly the same content as what would be extracted from the base64 blob in the S/MIME output produced by openssl cms sign ... and therefore, it needs to be in MIME format.
I need to validate a user by using an external authorize API. This API requires me to send a SHA-256 hash of something unique on my client side. I should use this to validate the signature later on.
I'm generating the Hash like this. As text I'm sending a unique Session ID:
private static string CalculateSHA256Hash(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA256Managed hashString = new SHA256Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
From the API I received a public signing key as a string:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA185vTa2xheB
<..>
SLhDuNk0SkiL7f8KbOG3tP9IDmAcAfoZWw/o2XjUxVLp1uw9V/hj4oJoapyS2sW4
cwIDAQAB
-----END PUBLIC KEY-----
I should use this key somehow to validate the response. The response I receive is this 512 character long string:
"57ec50faf72340f9618cf690160ab6b251a2d76fcce61583779804a07f8ac1f520bf09a4f5918a3
<...>
245f8d00b2cce3fa1ecc849f8771be0c8"
Now I should be able to Validate the signature I've received with the Public-key-string and my own hashed value.
How do I do this?
Edit
The hasing & padding scheme used on the API is "SHA256_RSA_PKCS_PSS"
I am building login workflow using Google for user. Once user is authenticated, I call GetAuthResponse to get idToken.
https://developers.google.com/identity/sign-in/web/backend-auth
Now, I need to verify certificate against Google certificate. I am using JwtSecurityToken(C#) for the same.
I am referencing for verification - http://blogs.msdn.com/b/alejacma/archive/2008/06/25/how-to-sign-and-verify-the-signature-with-net-and-a-certificate-c.aspx
Issue is - I always gets false from VerifyHash. As, VerifyHash returns just false without any reason, I am not able to find way to verify whether idToken is
valid or not. My code is given below
String strID = ""; // idToken received from Google AuthResponse
JwtSecurityToken token = new JwtSecurityToken(strID);
byte[] text = GetHash(token.RawData);
SHA256Cng sha1 = new SHA256Cng();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
byte[] signature = Encoding.Unicode.GetBytes(token.RawSignature);
// Modulus and exponent value from https://www.googleapis.com/oauth2/v2/certs - second set of keys
String modulus = "uHzGq7cMlx21nydbz9VsW1PItetb9mqvnpLp_8E3Knyk-mjv9DlaPhKGHYlJfHYGzKa2190C5vfsLLb1MIeGfdAv7ftpFsanIWawl8Zo0g-l0m7T2yG_7XerqcVK91lFifeJtgxKI86cPdZkgRy6DaYxMuAwAlhvpi3_UhPvsIwi7M6mxE8nUNpUWodh_YjJNu3wOxKDwbBZuRV2itjY6Z7RjFgJt1CsKF-QjqSVvWjAl0LaCaeMS_8yae0ln5YNeS8rAb6xkmcOuYeyhYsiBzwLRvgpXzEVLjLr631Z99oUHTpP9vWJDpGhfkrClkbmdtZ-ZCwX-eFW6ndd54BJEQ==";
String exponent = "AQAB";
modulus = modulus.Replace('-', '+').Replace('_', '/'); // Else it gives Base64 error
StringBuilder sb = new StringBuilder();
sb.Append("<RSAKeyValue>");
sb.Append("<Modulus>");
sb.Append(modulus);
sb.Append("</Modulus>");
sb.Append("<Exponent>");
sb.Append(exponent);
sb.Append("</Exponent>");
sb.Append("</RSAKeyValue>");
RSACryptoServiceProvider RSAVerifier = new RSACryptoServiceProvider();
RSAVerifier.FromXmlString(sb.ToString());
// Verify the signature with the hash
return RSAVerifier.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA256"), signature);
You might want to try as done in the Google+ Token Verification project - this fork includes a few minor updates that are still in review.
An alternative approach is to just verify the tokens using Google's token verification endpoints:
curl https://www.googleapis.com/oauth2/v2/tokeninfo?id_token=eyJhbGciOiJSUzI1NiIsImtpZCI6IjkyNGE0NjA2NDgxM2I5YTA5ZmFjZGJiNzYwZGI5OTMwMWU0ZjBkZjAifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTEwNTcwOTc3MjI2ODMwNTc3MjMwIiwiYXpwIjoiMzY0MzgxNDQxMzEwLXRuOGw2ZnY2OWdnOGY3a3VjanJhYTFyZWpmaXRxbGpuLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXRfaGFzaCI6IlAzLU1HZTdocWZhUkZ5Si1qcWRidHciLCJhdWQiOiIzNjQzODE0NDEzMTAtdG44bDZmdjY5Z2c4ZjdrdWNqcmFhMXJlamZpdHFsam4uYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJjX2hhc2giOiJjd3hsdXBUSkc4N2FnbU1pb0tSYUV3IiwiaWF0IjoxNDM0NDcyODc2LCJleHAiOjE0MzQ0NzY0NzZ9.Gz_WljZOV9NphDdClakLstutEKk65PNpEof7mxM2j-AOfVwh-SS0L5uxIaknFOk4-nDGmip42vrPYgNvbQWKZY63XuCs94YQgVVmTNCTJnao1IavtrhYvpDqGuGKdEB3Wemg5sS81pEthdvHwyxfwLPYukIhT8-u4ESfbFacsRtR77QRIOk-iLJAVYWTROJ05Gpa-EkTunEBVmZyYetbMfSoYkbwFKxYOlHLY-ENz_XfHTGhYhb-GyGrrw0r4FyHb81IWJ6Jf-7w6y3RiUJik7kYRkvnFouXUFSm8GBwxsioi9AAkavUWUk27s15Kcv-_hkPXzVrW5SvR1zoTI_IMw
I have an email application that creates encrypted emails. It works fine in outlook and all the email counterparties I send the email to reports no issues.
However when I try to decrypt them with Mimekit I get a "Bad data" exception.
Some of the stack trace:
at System.Security.Cryptography.Pkcs.EnvelopedCms.DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection extraStore)
at System.Security.Cryptography.Pkcs.EnvelopedCms.Decrypt()
at MimeKit.Cryptography.WindowsSecure...
My email mime looks like this:
Received: from Dx ([x]) by
x ([x]) with mapi id
x; Fri, 7 Mar 2014 14:48:49 +0100
From: x <x#x.com>
To: x <x2#x.com>
Subject:
xxxxxxxx
07-03-2014 14:48:46
Thread-Topic:
xxxxxxx
07-03-2014 14:48:46
Thread-Index: AQHPOgv3JHiUE6wuJk+EQu4eAA1oDA==
Date: Fri, 7 Mar 2014 14:48:48 +0100
Message-ID: <x>
Accept-Language: da-DK, en-US
Content-Language: en-US
X-MS-Exchange-Organization-AuthAs: x
X-MS-Exchange-Organization-AuthMechanism: x
X-MS-Exchange-Organization-AuthSource: x
X-MS-Has-Attach: yes
X-MS-Exchange-Organization-SCL: -1
X-MS-TNEF-Correlator:
Content-Type: application/pkcs7-mime; name="smime.p7m";
smime-type=enveloped-data
Content-Disposition: attachment; filename="smime.p7m"
Content-Transfer-Encoding: base64
MIME-Version: 1.0
MIIeOgYJKoZIhvcNAQcDoIIeKzCCHicCAQAxggLnMIIC4wIBADCByjCBxDEfMB0GA1UEChMWRGFu
c2tlIENv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jpOc
x9NHNbMHGyiRxKPOGHB1ffe1q+S6QUQ3ghngo2rKsZbR7C8nijdFcgUI0tpCqGwUA+72TYtIi2ui
QxGfJvXgXYsAn5gFbrrpxRaT0yYr5OaMuZuCmJopKyTDE/2mjuxaexFTklhMgClTULWnOuBv5j2b
FFDrtIJTHuM8F1laq5k5ehiWVRYWjh3ZMTBWeecEoWaIobMNYvTD3xbSzx6SH+20T59rdR8p0mJB
ECVc0pl3QQugE5w0Qrp7/CJ2Pxrmcc7tCWdnVOjglp3JcUBL2ZRJeQBPk5Bm6OCczR+sviFux2Me
MF/3E7TSRspBPscL9XHHH8eBznnjZ8fJAu0YAhTGjzL1DOjjVZ9KNlxWwGG+mCALm+XU8DpJNKg9
Nuq2uYSRu4p5K4+lEAyRM2cdiPLVcDuGKQpBGQnhsB6DslLImiYXSzy6OcHIsUf4kyAGes5tsBxR
i1IfNHcW4G/7i4VUy+530PqA0+TECNkpgiGxrevWk0gF0NgD+DDNgDzZRjJaRpMx0ufbP9twVvv+
6J/meqKiykYcU/NUYV/TuNiERKrOOWZs697IyY/g3nPWHZurZXJbmk9MpND2wn5PZzRTx7qyBVfn
nenl/WtSVMmKA4D1dLnHoeN1hoAyQgrfqS4yymL26UemhCXIV87hAYwwoAbpfr4=
This is how I perform my encryption:
public static string EncryptContent(string content, X509Certificate2 certificate)
{
byte[] contentBytes = Encoding.ASCII.GetBytes(content);
var envelopedCms = new EnvelopedCms(SubjectIdentifierType.IssuerAndSerialNumber, new ContentInfo(contentBytes));
var recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate);
envelopedCms.Encrypt(recipient);
var encodedData = envelopedCms.Encode();
var encodedDataBase64 = Convert.ToBase64String(encodedData, Base64FormattingOptions.InsertLineBreaks);
return encodedDataBase64;
}
and this is how I attempt to decrypt:
var primarySecureMimeContext = CreateSecureMimeContext(certificateInfo.PrimaryCertificate,
certificateInfo.PrimaryPassword);
var primaryDecryptedEntity = entity.Decrypt(primarySecureMimeContext);
private SecureMimeContext CreateSecureMimeContext(string certificateFilename, string certificatePassword)
{
var secureMimeContext = new WindowsSecureMimeContext();
var certificate = new X509Certificate2(certificateFilename,
certificatePassword);
var bouncyX509Certificate = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate);
secureMimeContext.Import(bouncyX509Certificate);
return secureMimeContext;
}
When I decrypt the content myself using enveloped cms directly, there are no issues.
This is the email after my own decryption:
Content-Type: multipart/mixed;
boundary="5511bd79-26dc-41e5-ac96-7adfdea5f6e5"
--5511bd79-26dc-41e5-ac96-7adfdea5f6e5
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: quoted-printable
--5511bd79-26dc-41e5-ac96-7adfdea5f6e5
Content-Type: application/octet-stream;
name="TestFile.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="TestFile.txt"
77u/VGVlZWVlZXN0
--5511bd79-26dc-41e5-ac96-7adfdea5f6e5--
Can anyone see what is causing this?
After having using the DummySecureMimeContext as proposed by jstedfast it works. A more thorough walkthrough can be found here: https://github.com/jstedfast/MimeKit/issues/38
I think the problem is the way you are adding the certificate to the context:
private SecureMimeContext CreateSecureMimeContext(string certificateFilename, string certificatePassword)
{
var secureMimeContext = new WindowsSecureMimeContext();
var certificate = new X509Certificate2(certificateFilename,
certificatePassword);
var bouncyX509Certificate = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate);
secureMimeContext.Import(bouncyX509Certificate);
return secureMimeContext;
}
What this is doing is adding the certificate to the AddressBook certificate store, but where you actually want to add it in order to decrypt it (because you'll need the private key password as well) is the personal cert store.
Try this:
private SecureMimeContext CreateSecureMimeContext (string certificateFilename, string certificatePassword)
{
var secureMimeContext = new WindowsSecureMimeContext ();
using (var stream = File.OpenRead (certificateFilename))
secureMimeContext.Import (stream, certificatePassword);
return secureMimeContext;
}
The exception message you are getting isn't very helpful, but I am guessing that it means that it can't find the certificate and/or private key. I wrote a test program and have been unsuccessful in reproducing this bug, so I could be wrong... but since my certificates/private keys are already imported into my personal cert store, I'm not sure how to remove them to test this theory.
Let me know how that works out for you.
Update: Oops, I done goofed. Just updated CreateSecureMimeContext() above to open the certificate file stream because WindowsSecureMimeContext.Import() takes a stream, not a file name.
This code fails every time I pass it an APK file that has a certification chain (intermediate and Root CA). If the file is self-signed it works correctly.
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)Cert.PublicKey.Key;
bool verified = csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), vData)
"hash" is the sha1 digest of the signature file (SF) and vData the encrypted hash of a signature (CMSG_ENCRYPTED_DIGEST,), both are byte arrays.
I will answer my own question after finding the answer. The problem resides when specifying the digest method.
A X509 certificate uses two algorithms that may not coincide (SignatureAlgorithm.FriendlyName and PublicKey.Key.SignatureAlgorithm). When verifying the hash you must make sure that it matches the SignatureAlgorithm of the certificate and not the algorithm used in the public key (which was my fault).
If in doubt, check both:
if (cert.SignatureAlgorithm.FriendlyName.ToString().Contains("sha256"))
{
SHA256Managed sha256 = new SHA256Managed();
byte[] hash256 = sha256.ComputeHash(sig);
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
verify_all.Add(csp.VerifyHash(hash256, CryptoConfig.MapNameToOID("SHA256"), vData));
}
else if (cert.SignatureAlgorithm.FriendlyName.ToString().Contains("sha1"))
{
SHA1Managed Sha1 = new SHA1Managed();
byte[] hash1 = sha1.ComputeHash(sig);
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
verify_all.Add(csp.VerifyHash(hash1, CryptoConfig.MapNameToOID("SHA256"), vData));
}