本文整理汇总了C#中System.Security.Cryptography.Pkcs.SignedCms.CheckSignature方法的典型用法代码示例。如果您正苦于以下问题:C# SignedCms.CheckSignature方法的具体用法?C# SignedCms.CheckSignature怎么用?C# SignedCms.CheckSignature使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.Pkcs.SignedCms
的用法示例。
在下文中一共展示了SignedCms.CheckSignature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CheckSig
protected string CheckSig()
{
var formData = Request.Form;
var text = formData["txtSign"];
var sig = formData["txtSig"];
string output = "INVALID!";
if (!string.IsNullOrEmpty(sig))
{
try
{
ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(text));
SignedCms signedCms = new SignedCms(contentInfo, true);
signedCms.Decode(Convert.FromBase64String(sig));
// This checks if the signature is valid, but doensn't actually verify the cert (TODO)
signedCms.CheckSignature(true);
output = "Signature valid.";
signedCms.CheckSignature(false);
output += "<br>Cert valid";
}
catch (Exception e)
{
output += "<br>" + e.ToString();
}
}
return output;
}
示例2: CheckSig
public static void CheckSig(byte[] sig, byte[] data)
{
ContentInfo contentInfo = new ContentInfo(data);
SignedCms signedCms = new SignedCms(contentInfo, true);
signedCms.Decode(sig);
// This checks if the signature is valid, but doensn't actually verify the cert (TODO)
signedCms.CheckSignature(true);
signedCms.CheckSignature(false);
}
示例3: Verify
public bool Verify(byte[] data, byte[] signature)
{
var signedCms = new SignedCms();
signedCms.Decode(signature);
try
{
signedCms.CheckSignature(_certificate2Collection, false);
}
catch(Exception e)
{
return false;
}
return signedCms.ContentInfo.Content.SequenceEqual(_md5.ComputeHash(data));
}
示例4: CheckFileSignature
public static String CheckFileSignature(ContentInfo content, byte[] signature)
{
var verifyCms = new SignedCms(content, true);
verifyCms.Decode(signature);
var cert = verifyCms.SignerInfos[0].Certificate;
try
{
verifyCms.CheckSignature(new X509Certificate2Collection(cert), false);
return @"Signature is valid";
}
catch (CryptographicException)
{
return @"Signature is not valid for content";
}
}
示例5: Sign
public static SignatureResponse Sign(byte[] data)
{
// TODO:
// padding configuration
// algorithm configuration
// encoding configuration
/*
SHA1Managed sha1 = new SHA1Managed();
byte[] hash = sha1.ComputeHash(data);
var sig = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
//sig = csp.SignData(Encoding.UTF8.GetBytes(text), CryptoConfig.MapNameToOID("SHA1"));
MessageBox.Show("SignData");
*/
var content = new ContentInfo(data);
var cms = new SignedCms(content, true); // TODO detached config
var signer = new CmsSigner();
signer.IncludeOption = X509IncludeOption.EndCertOnly;
cms.ComputeSignature(signer, false);
var sig = cms.Encode();
//ensure my signature is correct before continuing.
cms.CheckSignature(true);
var newCMS = new SignedCms(content, false);
newCMS.Decode(sig);
newCMS.CheckSignature(true);
var cert = cms.Certificates[0];
CheckSig(sig, data);
return new SignatureResponse
{
publicKey = Convert.ToBase64String(cert.PublicKey.EncodedKeyValue.RawData),
signature = Convert.ToBase64String(sig),
fullSig = null // TODO
};
}
示例6: GetTimestampInformation
private TimestampInformation GetTimestampInformation(X509Native.AXL_AUTHENTICODE_TIMESTAMPER_INFO timestamper,
XmlElement licenseNode) {
Debug.Assert(licenseNode != null, "licenseNode != null");
TimestampInformation timestamp = null;
// If the timestamper is a trusted publisher, then CAPI has done the work for us;
// If the leaf certificate is not explicitly a trusted publisher, CAPI will not process
// the timestamp information so we will verify it ourselves. In any other case, we will
// return no timestamp information.
if (timestamper.dwError == (int)SignatureVerificationResult.Valid) {
timestamp = new TimestampInformation(timestamper);
}
else if (timestamper.dwError == (int)SignatureVerificationResult.CertificateNotExplicitlyTrusted ||
timestamper.dwError == (int)SignatureVerificationResult.MissingSignature) {
XmlElement timestampElement = licenseNode.SelectSingleNode("r:issuer/ds:Signature/ds:Object/as:Timestamp",
m_namespaceManager) as XmlElement;
if (timestampElement != null) {
// The timestamp is held as a parameter of a base64 encoded PKCS7 message in the signature
byte[] timestampBlob = Convert.FromBase64String(timestampElement.InnerText);
try {
SignedCms timestampCms = new SignedCms();
timestampCms.Decode(timestampBlob);
timestampCms.CheckSignature(true);
// The SignedCms class does not expose a way to read arbitrary properties from the
// message, nor does it expose the HCRYPTMSG to P/Invoke with. We cannot access the
// actual timestamp because of this, so for signatures which are not created by a
// trusted publisher, we will return a null timestamp. This should be corrected in
// v3 of the CLR, as we can extend SignedCms to have the properties we need to
// pull all of this information.
timestamp = null;
}
catch (CryptographicException e) {
timestamp = new TimestampInformation((SignatureVerificationResult)Marshal.GetHRForException(e));
}
}
}
else {
timestamp = null;
}
return timestamp;
}
示例7: ToStream
/// <summary>
/// Stores MIME entity body to the specified stream.
/// </summary>
/// <param name="stream">Stream where to store body data.</param>
/// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param>
/// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param>
/// <param name="headerReencode">If true always specified encoding is used for header. If false and header field value not modified,
/// original encoding is kept.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
internal protected override void ToStream(Stream stream,MIME_Encoding_EncodedWord headerWordEncoder,Encoding headerParmetersCharset,bool headerReencode)
{
// We have signer certificate, sign this entity.
if(this.BodyParts.Count > 0 && m_pSignerCert != null){
// Remove old signature if there is any.
if(this.BodyParts.Count > 1){
this.BodyParts.Remove(1);
}
// Store entity to tmp stream.
MemoryStream tmpDataEntityStream = new MemoryStream();
this.BodyParts[0].ToStream(tmpDataEntityStream,null,null,false);
// Compute PKCS #7 message.
SignedCms signedCms = new SignedCms(new ContentInfo(tmpDataEntityStream.ToArray()),true);
signedCms.ComputeSignature(new CmsSigner(m_pSignerCert));
byte[] pkcs7 = signedCms.Encode();
// Create PKCS 7 entity.
MIME_Entity entity_application_pkcs7 = new MIME_Entity();
MIME_b_Application application_pkcs7 = new MIME_b_Application(MIME_MediaTypes.Application.x_pkcs7_signature);
entity_application_pkcs7.Body = application_pkcs7;
application_pkcs7.SetData(new MemoryStream(pkcs7),MIME_TransferEncodings.Base64);
entity_application_pkcs7.ContentType.Param_Name = "smime.p7s";
entity_application_pkcs7.ContentDescription = "S/MIME Cryptographic Signature";
this.BodyParts.Add(entity_application_pkcs7);
signedCms.Decode(application_pkcs7.Data);
signedCms.CheckSignature(true);
}
base.ToStream(stream,headerWordEncoder,headerParmetersCharset,headerReencode);
}
示例8: CheckSignAndGetCertificate
private X509Certificate2 CheckSignAndGetCertificate(FullDocumentInfo documentInfo, Sign sign)
{
var document = documentInfo.Document;
if (document.NeedReceipt && IsNoticeRequired(documentInfo))
{
UserInput.Warning("Не удалось проверить подпись документа т.к. на него запрошено УОП");
return null;
}
var contentInfo = new ContentInfo(GetDocumentContent(document));
var signedCms = new SignedCms(contentInfo, true);
try
{
// проверям подпись (действительность сервтификата не проверям для простоты)
signedCms.Decode(sign.Raw);
signedCms.CheckSignature(true);
}
catch (CryptographicException)
{
UserInput.Error("Подпись на документ {0} недействительна", document.Id);
return null;
}
var certificate = signedCms.Certificates[0];
return certificate;
}
示例9: VerifyAndRemoveSignature
public static byte[] VerifyAndRemoveSignature(byte[] data)
{
SignedCms signedMessage = new SignedCms();
signedMessage.Decode(data);
signedMessage.CheckSignature(false);
foreach (SignerInfo signer in signedMessage.SignerInfos)
{
Console.WriteLine("Subject: {0}", signer.Certificate.Subject);
}
return signedMessage.ContentInfo.Content;
}
示例10: VerifyMsg
// Verify the encoded SignedCms message and return a Boolean
// value that specifies whether the verification was successful.
// Also return the original message that was signed, which is
// available as part of the SignedCms message after it
// is decoded.
public static bool VerifyMsg(byte[] encodedSignedCms,
out byte[] origMsg)
{
// Prepare a SignedCms object in which to decode
// and verify.
SignedCms signedCms = new SignedCms();
signedCms.Decode(encodedSignedCms);
// Catch a verification exception in the event you want to
// advise the message recipient that security actions
// might be appropriate.
try
{
// Verify signature. Do not validate signer
// certificate for the purposes of this example.
// Note that in a production environment, validating
// the signer certificate chain will probably be
// necessary.
Console.Write("Checking signature on message ... ");
signedCms.CheckSignature(true);
Console.WriteLine("Done.");
}
catch (System.Security.Cryptography.CryptographicException e)
{
Console.WriteLine("VerifyMsg caught exception: {0}",
e.Message);
Console.WriteLine("The message may have been modified " +
"in transit or storage. Authenticity of the " +
"message is not guaranteed.");
origMsg = null;
return false;
}
origMsg = signedCms.ContentInfo.Content;
return true;
}
示例11: LoadEncryptedAndMeabySignedMessage
/// <summary>
/// Load's and parses a signed message. The signed message should be in an attachment called smime.p7m
/// </summary>
/// <param name="storage"></param>
private void LoadEncryptedAndMeabySignedMessage(NativeMethods.IStorage storage)
{
// Create attachment from attachment storage
var attachment = new Attachment(new Storage(storage), null);
if (attachment.FileName.ToUpperInvariant() != "SMIME.P7M")
throw new MRInvalidSignedFile(
"The signed file is not valid, it should contain an attachment called smime.p7m but it didn't");
// If the message is signed then it always only contains one attachment called smime.p7m
var signedCms = new SignedCms();
signedCms.Decode(attachment.Data);
try
{
signedCms.CheckSignature(signedCms.Certificates, false);
SignatureIsValid = true;
foreach (var cryptographicAttributeObject in signedCms.SignerInfos[0].SignedAttributes)
{
if (cryptographicAttributeObject.Values[0] is Pkcs9SigningTime)
{
var pkcs9SigningTime = (Pkcs9SigningTime)cryptographicAttributeObject.Values[0];
SignedOn = pkcs9SigningTime.SigningTime.ToLocalTime();
}
}
var certificate = signedCms.SignerInfos[0].Certificate;
if (certificate != null)
SignedBy = certificate.GetNameInfo(X509NameType.SimpleName, false);
}
catch (CryptographicException)
{
SignatureIsValid = false;
}
// Get the decoded attachment
using (var memoryStream = new MemoryStream(signedCms.ContentInfo.Content))
{
var eml = Mime.Message.Load(memoryStream);
_bodyText = eml.TextBody.GetBodyAsText();
_bodyHtml = eml.HtmlBody.GetBodyAsText();
foreach (var emlAttachment in eml.Attachments)
_attachments.Add(new Attachment(emlAttachment));
}
}
示例12: CheckSignatureDetachedSignedCms
public void CheckSignatureDetachedSignedCms ()
{
string path = Path.Combine ("Test", "System.Security.Cryptography.Pkcs");
var signedBytes = File.ReadAllBytes (Path.Combine (path, "detached.data"));
var bytes = File.ReadAllBytes (Path.Combine (path, "detached.p7"));
var oid = new Oid ("1.2.840.113549.1.7.2");
var contentInfo = new ContentInfo (oid, signedBytes);
var signedCms = new SignedCms (contentInfo, true);
signedCms.Decode (bytes);
signedCms.CheckSignature (true);
}
示例13: ExtractMIMEParts
//.........这里部分代码省略.........
mimeParts.Add(mimePart);
}
else if (contentTypeToUpper.StartsWith("APPLICATION/PKCS7-MIME") || contentTypeToUpper.StartsWith("APPLICATION/X-PKCS7-MIME"))
{
// Don't attempt to decrypt if this is a signed message only.
if (contentType.IndexOf("smime-type=signed-data") < 0)
{
// Unless a flag has been set to include this *.p7m block, exclude it from attachments.
if ((processingFlags & MailMessageProcessingFlags.IncludeSmimeEncryptedEnvelopeData) > 0)
mimeParts.Add(new MimePart("smime.p7m", contentType, "", "", "", body));
// Decrypt the MIME part and recurse through embedded MIME parts.
List<MimePart> returnedMIMEParts = ReturnSmimeDecryptedMimeParts(contentType, contentTransferEncoding, body, processingFlags, depth + 1);
if (returnedMIMEParts != null)
{
foreach (MimePart returnedMIMEPart in returnedMIMEParts)
mimeParts.Add(returnedMIMEPart);
}
else
{
// If we were unable to decrypt the message, pass it along as-is.
mimeParts.Add(new MimePart(Functions.ReturnBetween(contentType + ";", "name=", ";").Replace("\"", ""), contentType, "", "", contentTransferEncoding, body));
}
}
else
{
// Hydrate the signature CMS object.
SignedCms signedCms = new SignedCms();
try
{
// Attempt to decode the signature block and verify the passed in signature.
signedCms.Decode(Convert.FromBase64String(body));
signedCms.CheckSignature(true);
string mimeContents = Encoding.UTF8.GetString(signedCms.ContentInfo.Content);
int mimeDivider = mimeContents.IndexOf("\r\n\r\n");
string mimeHeaders;
if (mimeDivider > -1)
mimeHeaders = mimeContents.Substring(0, mimeDivider);
else
mimeHeaders = mimeContents;
if (mimeHeaders.Length > 0)
{
// Extract the body portion of the current MIME part.
string mimeBody = mimeContents.Substring(mimeDivider + 4);
string mimeCharSet = "", mimeContentDisposition = "", mimeContentID = "", mimeContentType = "", mimeContentTransferEncoding = "", mimeFileName = "";
ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID);
List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags, depth + 1);
foreach (MimePart returnedMIMEPart in returnedMIMEParts)
mimeParts.Add(returnedMIMEPart);
}
}
catch
{
// If an exception occured, the signature could not be verified.
}
}
}
else if (contentTypeToUpper == "MESSAGE/RFC822")
{
int mimeDivider = body.IndexOf("\r\n\r\n");
示例14: GetSignerCertificate
internal static X509Certificate GetSignerCertificate(Stream stream)
{
stream.Seek(60, SeekOrigin.Begin);
BinaryReader br = new BinaryReader(stream);
int peSignatureOffset = br.ReadInt32();
int checksumOffset = peSignatureOffset + 24 + 64;
// seek to the IMAGE_OPTIONAL_HEADER
stream.Seek(peSignatureOffset + 24, SeekOrigin.Begin);
int certificateTableDataDirectoryOffset;
switch (br.ReadUInt16())
{
case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
certificateTableDataDirectoryOffset = peSignatureOffset + 24 + (64 + 4 * 8) + 8 * 4;
break;
case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
certificateTableDataDirectoryOffset = peSignatureOffset + 24 + (64 + 4 * 8 + 16) + 8 * 4;
break;
default:
throw new BadImageFormatException();
}
stream.Seek(certificateTableDataDirectoryOffset, SeekOrigin.Begin);
int certificateTableOffset = br.ReadInt32();
int certificateTableLength = br.ReadInt32();
stream.Seek(certificateTableOffset, SeekOrigin.Begin);
int dwLength = br.ReadInt32();
short wRevision = br.ReadInt16();
short wCertificateType = br.ReadInt16();
if (wRevision != WIN_CERT_REVISION_2_0)
{
return null;
}
if (wCertificateType != WIN_CERT_TYPE_PKCS_SIGNED_DATA)
{
return null;
}
byte[] buf = new byte[certificateTableLength - 8];
stream.Read(buf, 0, buf.Length);
SignedCms cms = new SignedCms();
try
{
cms.Decode(buf);
cms.CheckSignature(false);
}
catch (CryptographicException)
{
return null;
}
SignerInfo signerInfo = cms.SignerInfos[0];
int[] offsets = new int[] { checksumOffset, certificateTableDataDirectoryOffset, certificateTableOffset };
int[] lengths = new int[] { 4, 8, certificateTableLength };
byte[] actualHash = ComputeHashWithSkip(stream, signerInfo.DigestAlgorithm.FriendlyName, offsets, lengths);
byte[] requiredHash = DecodeASN1(cms.ContentInfo.Content, 0, 1, 1);
if (requiredHash == null || actualHash.Length != requiredHash.Length)
{
return null;
}
for (int i = 0; i < actualHash.Length; i++)
{
if (actualHash[i] != requiredHash[i])
{
return null;
}
}
return signerInfo.Certificate;
}
示例15: CheckSignature
public bool CheckSignature (SignedCms cms)
{
try {
cms.CheckSignature (false);
return true;
}
catch {
}
return false;
}