internal override void Execute <TModel, TResponse>(Merchant merchant, Request <TModel, TResponse> request) { if (!string.IsNullOrEmpty(FileContent)) { _billFile = CertUtil.Inflater(FileContent); } }
private void btnFirmarHuella_Click(object sender, EventArgs e) { if (!rbInternnallyDetached.Checked) { MessageBox.Show("Por favor, seleccione el tipo de firma internally detached."); return; } if (string.IsNullOrEmpty(txtFichero.Text)) { MessageBox.Show("Debe seleccionar un fichero para firmar."); return; } XadesService xadesService = new XadesService(); SignatureParameters parametros = ObtenerParametrosFirma(); parametros.SignaturePackaging = SignaturePackaging.HASH_INTERNALLY_DETACHED; parametros.DataFormat = new DataFormat(); parametros.DataFormat.MimeType = "hash/sha256"; parametros.DataFormat.Description = "Hash value encoded in binary format"; using (FileStream fs = new FileStream(txtFichero.Text, FileMode.Open)) { using (parametros.Signer = new Signer(CertUtil.SelectCertificate())) { _signatureDocument = xadesService.Sign(fs, parametros); } } MessageBox.Show("Firma completada, ahora puede Guardar la firma o ampliarla a Xades-T.", "Test firma XADES", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private void btnFirmar_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtFichero.Text)) { MessageBox.Show("Debe seleccionar un fichero para firmar."); return; } CadesService cs = new CadesService(); SignatureParameters parametros = ObtenerParametrosFirma(); parametros.Certificate = CertUtil.SelectCertificate(); parametros.MimeType = MimeTypeInfo.GetMimeType(txtFichero.Text); if (rbAttachedImplicit.Checked) { parametros.SignaturePackaging = SignaturePackaging.ATTACHED_IMPLICIT; } else { parametros.SignaturePackaging = SignaturePackaging.DETACHED_EXPLICIT; } using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate)) { using (FileStream fs = new FileStream(txtFichero.Text, FileMode.Open)) { _signatureDocument = cs.Sign(fs, parametros); } } MessageBox.Show("Signature completed, you can now save the signature or extend it to CAdES-T.", "CAdES signature test", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private void btnContraFirma_Click(object sender, EventArgs e) { if (_signatureDocument == null) { return; } FrmSeleccionarFirma frm = new FrmSeleccionarFirma(_signatureDocument); if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK) { MessageBox.Show("Debe seleccionar una firma"); return; } SignatureParameters parametros = ObtenerParametrosFirma(); parametros.SignaturePolicyInfo = null; parametros.Certificate = CertUtil.SelectCertificate(); using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate)) { CadesService cs = new CadesService(); _signatureDocument = cs.CounterSign(_signatureDocument, frm.SignerInfo, parametros); } MessageBox.Show("Signature completed, you can now save the signature or extend it to CAdES-T.", "CAdES signature test", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public override void SendRequest() { Dictionary <string, string> data = new Dictionary <string, string>(); BUConfig.MerId = SDKConfig.MerId = this.Vmid; SDKConfig.SignCertPwd = this.Key; SDKConfig.signCertPath = Path.Combine(SDKConfig.validateCertDir, this.SignCertFileName); BUConfig.CertId = CertUtil.GetSignCertId(); data.Add("version", BUConfig.Version); data.Add("encoding", BUConfig.Encoding); data.Add("certId", BUConfig.CertId); data.Add("signMethod", BUConfig.SignMethod); data.Add("txnType", BUConfig.TxnType); data.Add("txnSubType", BUConfig.TxnSubType); data.Add("bizType", BUConfig.BizType); data.Add("channelType", BUConfig.ChannelType); data.Add("frontUrl", BUConfig.FrontUrl); data.Add("backUrl", BUConfig.BackUrl); data.Add("accessType", BUConfig.AccessType); data.Add("merId", BUConfig.MerId); data.Add("orderId", BUConfig.OrderId); data.Add("txnTime", BUConfig.TxnTime); data.Add("txnAmt", BUConfig.TxnAmt); data.Add("currencyCode", BUConfig.CurrencyCode); data.Add("userMac", "userMac"); SDKUtil.Sign(data, Encoding.UTF8); string msg = SDKUtil.CreateAutoSubmitForm("https://gateway.95516.com/gateway/api/frontTransReq.do", data, Encoding.UTF8); PayLog.writeLog(data, "", "", msg, LogType.BankUnion_GateWay); this.SubmitPaymentForm(msg); }
/// <summary> /// Make sure the test cert is deleted from the current user store. /// </summary> public void Dispose() { // Delete the cert X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(Constants.TestCert), string.Empty); CertUtil.DeleteCertificate(cert.Thumbprint); }
private static void ConfigureCosmosDB(IServiceCollection services, IConfiguration configuration) { services.AddTransient <Func <string, CosmosDbSetting> >(serviceProvider => name => { var kvSetting = serviceProvider.GetRequiredService <KeyVaultSetting>(); var kvCert = CertUtil.FindCertificateByThumbprint(kvSetting.AuthCertThumbprint); var kvClient = new KeyVaultUtil(kvSetting.VaultName, kvSetting.AuthClientId, kvCert); switch (name) { case "graph": var graphDbKey = kvClient.GetSecret(kvSetting.GraphDbAuthKeySecretName).Result; var graphDbSetting = new CosmosDbSetting() { AccountName = configuration["graphDb:accountName"], DbName = configuration["graphDb:dbName"], CollectionName = configuration["graphDb:collectionName"], AuthKey = graphDbKey }; return(graphDbSetting); default: var docDbKey = kvClient.GetSecret(kvSetting.DocDbAuthKeySecretName).Result; var docDbSetting = new CosmosDbSetting() { AccountName = configuration["docDb:accountName"], DbName = configuration["docDb:dbName"], CollectionName = configuration["docDb:collectionName"], AuthKey = docDbKey }; return(docDbSetting); } }); }
public void Can_Read_Add_Find_Remove_And_FindNot() { //read var certFromFile = CertUtil.GetFromFile(_certPath, _certPassword); certFromFile.Should().NotBeNull("Failed to read"); var serial = certFromFile.SerialNumber; //add CertUtil.AddCertificate(certFromFile); CertUtil.AddCertificate(certFromFile, System.Security.Cryptography.X509Certificates.StoreName.TrustedPublisher); //find var cert1 = CertUtil.GetBySerial(serial); cert1.Should().NotBeNull("Failed to add"); cert1.SerialNumber.Should().BeEquivalentTo(serial); //remove CertUtil.RemoveCertificate(serial); CertUtil.RemoveCertificate(serial, System.Security.Cryptography.X509Certificates.StoreName.TrustedPublisher); //find-not var cert2 = CertUtil.GetBySerial(serial); cert2.Should().BeNull("Failed to remove"); }
public void CanNormalizeSerial() { var input = " 54 03 4b e4 23 43 48 4A 50 c3 9A 00 d4 3c e1 cb "; var expected = "54034be42343484A50c39A00d43ce1cb"; var actual = CertUtil.NormalizeSerialString(input); actual.Should().BeEquivalentTo(expected); }
public void ShouldNormalizedNullSerialToEmptyString() { string input = null; var expected = ""; var actual = CertUtil.NormalizeSerialString(input); actual.Should().BeEquivalentTo(expected); }
/// <summary> /// Insert the certificate in the certificate list and check the certificate validity. /// </summary> /// <param name="cert"></param> /// <param name="unsignedProperties"></param> /// <param name="addCert"></param> /// <param name="ocspServers"></param> /// <param name="crlList"></param> /// <param name="digestMethod"></param> /// <param name="addCertificateOcspUrl"></param> /// <param name="extraCerts"></param> /// <param name="useNonce">If true then nonce will be used. The ocsp server should support this. OCSP reposnder in Microsoft Windows must be configured explicitly to support nonce.</param> private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, IEnumerable <OcspServer> ocspServers, IEnumerable <X509Crl> crlList, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl, X509Certificate2[] extraCerts = null, bool useNonce = true) { if (addCert) { if (CertificateChecked(cert, unsignedProperties)) { return; } string guidCert = Guid.NewGuid().ToString(); Cert chainCert = new Cert(); chainCert.IssuerSerial.X509IssuerName = cert.IssuerName.Name; chainCert.IssuerSerial.X509SerialNumber = cert.GetSerialNumberAsDecimalString(); DigestUtil.SetCertDigest(cert.GetRawCertData(), digestMethod, chainCert.CertDigest); chainCert.URI = "#Cert" + guidCert; unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(chainCert); EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate { Id = "Cert" + guidCert, PkiData = cert.GetRawCertData() }; unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate); } var chain = CertUtil.GetCertChain(cert, extraCerts).ChainElements; if (chain.Count > 1) { X509ChainElementEnumerator enumerator = chain.GetEnumerator(); enumerator.MoveNext(); // el mismo certificado que el pasado por parametro enumerator.MoveNext(); bool valid = ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate, crlList, digestMethod); if (!valid) { var ocspCerts = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate, ocspServers, digestMethod, addCertificateOcspUrl, useNonce); if (ocspCerts != null) { X509Certificate2 startOcspCert = DetermineStartCert(ocspCerts); if (!EquivalentDN(startOcspCert.IssuerName, enumerator.Current.Certificate.SubjectName)) { var chainOcsp = CertUtil.GetCertChain(startOcspCert, ocspCerts); AddCertificate(chainOcsp.ChainElements[1].Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, ocspCerts); } } } AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, extraCerts); } }
/// <summary> /// 生成App支付订单参数信息 /// </summary> /// <param name="outTradeNo">业务单号</param> /// <param name="subject">支付标题</param> /// <param name="body">支付内容</param> /// <param name="totalFee">支付金额</param> /// <returns></returns> public static UniionpayResult GetPayString(string outTradeNo, string orderDesc, decimal totalAmount, bool isPrePay, out string payParam) { UniionpayResult result = new UniionpayResult(); //构造待签名数据 Dictionary <string, string> param = new Dictionary <string, string>(); try { //填写参数 param["version"] = "5.0.0"; //版本号 param["encoding"] = "UTF-8"; //编码方式 param["certId"] = CertUtil.GetSignCertId(); //证书ID param["txnType"] = isPrePay ? TxnType.PrePay : TxnType.Consume; //交易类型 param["txnSubType"] = "01"; //交易子类 param["bizType"] = "000000"; //业务类型 param["backUrl"] = SDKConfig.BackTransUrl; //后台异步通知地址 param["signMethod"] = "01"; //签名方法,01:表示采用RSA param["channelType"] = "08"; //渠道类型,07-PC,08-手机 param["accessType"] = "0"; //接入类型,0:商户直连接入 1:收单机构接入 2:平台商户接入 param["merId"] = SDKConfig.MerId; //商户号,请改成自己的商户号 param["orderId"] = outTradeNo; //商户订单号 param["txnTime"] = DateTime.Now.ToString("yyyyMMddHHmmss"); //订单发送时间 param["txnAmt"] = (totalAmount * 100).ToString("0"); //交易金额,单位分 param["currencyCode"] = "156"; //交易币种 param["orderDesc"] = orderDesc; //订单描述,可不上送,上送时控件中会显示该信息 SDKUtil.Sign(param, Encoding.UTF8); // 签名 payParam = JsonConvert.SerializeObject(param); // 初始化通信处理类 HttpClient hc = new HttpClient(SDKConfig.AppRequestUrl); // 发送请求获取通信应答 int status = hc.Send(param, Encoding.UTF8); // 返回结果 string results = hc.Result; Dictionary <string, string> resData = SDKUtil.CoverstringToDictionary(results); result.respcode = resData["respCode"]; if (result.respcode != "00") { result.respMsg = resData["respMsg"]; return(result); } if (!SDKUtil.Validate(resData, Encoding.UTF8)) { LogHelper.SaveFileLog("获取银联支付信息失败!", "商户端验证返回报文签名失败:" + JsonConvert.SerializeObject(resData)); result.respMsg = resData["respMsg"]; return(result); } result.tn = resData["tn"]; } catch (Exception ex) { payParam = JsonConvert.SerializeObject(param); LogHelper.SaveFileLog("获取银联支付信息失败!", ex.Message); result.respcode = ""; result.respMsg = ""; } return(result); }
/// <summary> /// Inserta en la lista de certificados el certificado y comprueba la valided del certificado. /// </summary> /// <param name="cert"></param> /// <param name="unsignedProperties"></param> /// <param name="addCertValue"></param> /// <param name="extraCerts"></param> private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, X509Certificate2[] extraCerts = null) { if (addCert) { if (CertificateChecked(cert, unsignedProperties)) { return; } string guidCert = Guid.NewGuid().ToString(); Cert chainCert = new Cert(); chainCert.IssuerSerial.X509IssuerName = cert.IssuerName.Name; chainCert.IssuerSerial.X509SerialNumber = CertUtil.HexToDecimal(cert.SerialNumber); DigestUtil.SetCertDigest(cert.GetRawCertData(), _firma.RefsDigestMethod, chainCert.CertDigest); chainCert.URI = "#Cert" + guidCert; unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(chainCert); EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate(); encapsulatedX509Certificate.Id = "Cert" + guidCert; encapsulatedX509Certificate.PkiData = cert.GetRawCertData(); unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate); } var chain = CertUtil.GetCertChain(cert, extraCerts).ChainElements; if (chain.Count > 1) { X509ChainElementEnumerator enumerator = chain.GetEnumerator(); enumerator.MoveNext(); // el mismo certificado que el pasado por parametro enumerator.MoveNext(); bool valid = ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate); if (!valid) { var ocspCerts = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate); if (ocspCerts != null) { X509Certificate2 startOcspCert = DetermineStartCert(new List <X509Certificate2>(ocspCerts)); if (startOcspCert.IssuerName.Name != enumerator.Current.Certificate.SubjectName.Name) { var chainOcsp = CertUtil.GetCertChain(startOcspCert, ocspCerts); AddCertificate(chainOcsp.ChainElements[1].Certificate, unsignedProperties, true, ocspCerts); } } } AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, extraCerts); } }
public IActionResult get_ssl_certificate() { var rootCA = CertUtil.getInstance().getRootCA(); ViewBag.Issued = rootCA.GetNameInfo(X509NameType.SimpleName, true); ViewBag.NotBefore = rootCA.NotBefore.ToLongDateString() + " " + rootCA.NotBefore.ToLongTimeString(); ViewBag.NotAfter = rootCA.NotAfter.ToLongDateString() + " " + rootCA.NotAfter.ToLongTimeString(); ViewBag.Serial = rootCA.SerialNumber; ViewBag.Thumbprint = rootCA.Thumbprint; ViewBag.PublicKey = rootCA.GetPublicKeyString(); return(View()); }
private void btnContraFirma_Click(object sender, EventArgs e) { SignatureParameters parametros = ObtenerParametrosFirma(); using (parametros.Signer = new Signer(CertUtil.SelectCertificate())) { _signatureDocument = _xadesService.CounterSign(_signatureDocument, parametros); } MessageBox.Show("Firma completada correctamente.", "Test firma XADES", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private void btnFirmar_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtFichero.Text)) { MessageBox.Show("Debe seleccionar un fichero para firmar."); return; } XadesService xadesService = new XadesService(); SignatureParameters parametros = ObtenerParametrosFirma(); if (rbInternnallyDetached.Checked) { parametros.SignaturePolicyInfo = ObtenerPolitica(); parametros.SignaturePackaging = SignaturePackaging.INTERNALLY_DETACHED; parametros.DataFormat = new DataFormat(); parametros.DataFormat.MimeType = MimeTypeInfo.GetMimeType(txtFichero.Text); } else if (rbExternallyDetached.Checked) { parametros.SignaturePackaging = SignaturePackaging.EXTERNALLY_DETACHED; parametros.ExternalContentUri = txtFichero.Text; } else if (rbEnveloped.Checked) { parametros.SignaturePackaging = SignaturePackaging.ENVELOPED; } else if (rbEnveloping.Checked) { parametros.SignaturePackaging = SignaturePackaging.ENVELOPING; } using (parametros.Signer = new Signer(CertUtil.SelectCertificate())) { if (parametros.SignaturePackaging != SignaturePackaging.EXTERNALLY_DETACHED) { using (FileStream fs = new FileStream(txtFichero.Text, FileMode.Open)) { _signatureDocument = xadesService.Sign(fs, parametros); } } else { _signatureDocument = xadesService.Sign(null, parametros); } } MessageBox.Show("Firma completada, ahora puede Guardar la firma o ampliarla a Xades-T.", "Test firma XADES", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private bool ValidateCertificateByCRL(UnsignedProperties unsignedProperties, X509Certificate2 certificate, X509Certificate2 issuer) { Org.BouncyCastle.X509.X509Certificate clientCert = CertUtil.ConvertToX509Certificate(certificate); Org.BouncyCastle.X509.X509Certificate issuerCert = CertUtil.ConvertToX509Certificate(issuer); foreach (var crlEntry in _firma.CRLEntries) { if (crlEntry.IssuerDN.Equivalent(issuerCert.SubjectDN) && crlEntry.NextUpdate.Value > DateTime.Now) { if (!crlEntry.IsRevoked(clientCert)) { if (!ExistsCRL(unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection, issuer.Subject)) { string idCrlValue = "CRLValue-" + Guid.NewGuid().ToString(); CRLRef crlRef = new CRLRef(); crlRef.CRLIdentifier.UriAttribute = "#" + idCrlValue; crlRef.CRLIdentifier.Issuer = issuer.Subject; crlRef.CRLIdentifier.IssueTime = crlEntry.ThisUpdate.ToLocalTime(); var crlNumber = GetCRLNumber(crlEntry); if (crlNumber.HasValue) { crlRef.CRLIdentifier.Number = crlNumber.Value; } byte[] crlEncoded = crlEntry.GetEncoded(); DigestUtil.SetCertDigest(crlEncoded, _firma.RefsDigestMethod, crlRef.CertDigest); CRLValue crlValue = new CRLValue(); crlValue.PkiData = crlEncoded; crlValue.Id = idCrlValue; unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection.Add(crlRef); unsignedProperties.UnsignedSignatureProperties.RevocationValues.CRLValues.CRLValueCollection.Add(crlValue); } return(true); } else { throw new Exception("Certificado revocado"); } } } return(false); }
private void btnFirmar_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtFichero.Text)) { MessageBox.Show("Debe seleccionar un fichero para firmar."); return; } SignatureParameters parametros = ObtenerParametrosFirma(); if (rbInternnallyDetached.Checked) { // TODO: gestionar correctamente los tipos MIME string mimeType = "application/" + System.IO.Path.GetExtension(txtFichero.Text).ToLower().Replace(".", ""); parametros.SignaturePolicyInfo = ObtenerPolitica(); parametros.SignaturePackaging = SignaturePackaging.INTERNALLY_DETACHED; parametros.InputMimeType = mimeType; } else if (rbExternallyDetached.Checked) { parametros.SignaturePackaging = SignaturePackaging.EXTERNALLY_DETACHED; parametros.ExternalContentUri = txtFichero.Text; } else if (rbEnveloped.Checked) { parametros.SignaturePackaging = SignaturePackaging.ENVELOPED; } using (parametros.Signer = new Signer(CertUtil.SelectCertificate())) { if (parametros.SignaturePackaging != SignaturePackaging.EXTERNALLY_DETACHED) { using (FileStream fs = new FileStream(txtFichero.Text, FileMode.Open)) { _signatureDocument = _xadesService.Sign(fs, parametros); } } else { _signatureDocument = _xadesService.Sign(null, parametros); } } MessageBox.Show("Firma completada, ahora puede Guardar la firma o ampliarla a Xades-T.", "Test firma XADES", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public void InvalidStoreLocationTest() { // Import the test certificate. X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(Constants.TestCert), string.Empty); CertUtil.ImportCertificate(cert); // MockAuthenticationContext is being asked to act like client cert auth suceeded. MockAuthenticationContext mockAuthenticationContext = new MockAuthenticationContext(MockAuthenticationContext.MockAuthenticationContextTestType.AcquireTokenAsyncClientCertificateSuccess); // Create ClientCertificateAzureServiceTokenProvider instance var exception = Assert.Throws <ArgumentException>(() => new ClientCertificateAzureServiceTokenProvider(Constants.TestAppId, cert.Thumbprint, CertificateIdentifierType.Thumbprint, Constants.InvalidString, Constants.TenantId, Constants.AzureAdInstance, mockAuthenticationContext)); Assert.Contains(Constants.InvalidCertLocationError, exception.ToString()); }
public void SimpleXadesTSign(object input) { Console.WriteLine(input.ToString()); Assert.True(CertUtil.VerifyCertificate(_signCertificate, _rootCert, X509RevocationMode.NoCheck)); using (var inputStream = System.IO.File.OpenRead(Path.Combine(rootDirectory, @"Sample.xml"))) { var result = SignDocument(_signCertificate, inputStream, new SignatureProductionPlace { City = "Sofia", CountryName = "Bulgaria", PostalCode = "1303", StateOrProvince = "Sofia" }, "http://timestamp.comodoca.com/rfc3161"); ValidateDocument(result); ValidateDocumentSignatureOnly(result); } }
public ChinaUnionViewModel() { Version = "5.0.0"; Encoding = "UTF-8"; CertId = CertUtil.GetSignCertId(); SignMethod = "01"; TxnType = "31"; TxnSubType = "00"; BizType = "000201"; AccessType = "0"; ChannelType = "07"; TxnTime = DateTime.Now.ToString("yyyyMMddHHmmss"); MerId = "898110279910127"; BackUrl = "http://" + HttpContext.Current.Request.Url.Host + "/ChinaUnion/BackReceive"; FrontUrl = "http://" + HttpContext.Current.Request.Url.Host + "/ChinaUnion/FrontUrl"; }
private void AddSignatureProperties(SignedSignatureProperties signedSignatureProperties, SignedDataObjectProperties signedDataObjectProperties, UnsignedSignatureProperties unsignedSignatureProperties, string mimeType, X509Certificate2 certificado) { Cert cert; cert = new Cert(); cert.IssuerSerial.X509IssuerName = certificado.IssuerName.Name; cert.IssuerSerial.X509SerialNumber = CertUtil.HexToDecimal(certificado.SerialNumber); DigestUtil.SetCertDigest(_signCertificate.GetRawCertData(), _refsMethodUri, cert.CertDigest); signedSignatureProperties.SigningCertificate.CertCollection.Add(cert); if (!string.IsNullOrEmpty(_policyId)) { signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = false; signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyId.Identifier.IdentifierUri = _policyId; } if (!string.IsNullOrEmpty(_policyUri)) { SigPolicyQualifier spq = new SigPolicyQualifier(); spq.AnyXmlElement = _document.CreateElement("SPURI", XadesSignedXml.XadesNamespaceUri); spq.AnyXmlElement.InnerText = _policyUri; signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyQualifiers.SigPolicyQualifierCollection.Add(spq); } if (!string.IsNullOrEmpty(_policyHash)) { signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestMethod.Algorithm = SignedXml.XmlDsigSHA1Url; signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestValue = Convert.FromBase64String(PolicyHash); } signedSignatureProperties.SigningTime = DateTime.Now; if (!string.IsNullOrEmpty(mimeType)) { DataObjectFormat newDataObjectFormat = new DataObjectFormat(); newDataObjectFormat.MimeType = mimeType; newDataObjectFormat.ObjectReferenceAttribute = "#" + _objectReference; signedDataObjectProperties.DataObjectFormatCollection.Add(newDataObjectFormat); } }
public void CanSignX(string inputName, string outputName) { var input = Path.Combine(_inputPath, inputName); var output = Path.Combine(_outputPath, outputName); if (File.Exists(output)) { File.Delete(output); } File.Exists(output).Should().BeFalse(); var signer = DocumentSigner.For(input); var cert = CertUtil.GetFromFile(_certPath, _certPassword); var serial = cert.SerialNumber; signer.Sign(input, output, cert); File.Exists(output).Should().BeTrue(); CanVerifyX(output, serial); }
private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, IEnumerable <string> ocspServers, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod, X509Certificate2[] extraCerts = null) { if (addCert) { if (CertificateChecked(cert, unsignedProperties)) { return; } string str = Guid.NewGuid().ToString(); Cert cert2 = new Cert(); cert2.IssuerSerial.X509IssuerName = cert.IssuerName.Name; cert2.IssuerSerial.X509SerialNumber = cert.GetSerialNumberAsDecimalString(); DigestUtil.SetCertDigest(cert.GetRawCertData(), digestMethod, cert2.CertDigest); cert2.URI = "#Cert" + str; unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(cert2); EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate(); encapsulatedX509Certificate.Id = "Cert" + str; encapsulatedX509Certificate.PkiData = cert.GetRawCertData(); unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate); } X509ChainElementCollection chainElements = CertUtil.GetCertChain(cert, extraCerts).ChainElements; if (chainElements.Count > 1) { X509ChainElementEnumerator enumerator = chainElements.GetEnumerator(); enumerator.MoveNext(); enumerator.MoveNext(); if (!ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate, crlList, digestMethod)) { X509Certificate2[] array = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate, ocspServers, digestMethod); if (array != null) { X509Certificate2 x509Certificate = DetermineStartCert(new List <X509Certificate2>(array)); if (x509Certificate.IssuerName.Name != enumerator.Current.Certificate.SubjectName.Name) { X509Chain certChain = CertUtil.GetCertChain(x509Certificate, array); AddCertificate(certChain.ChainElements[1].Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, array); } } } AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, extraCerts); } }
/// <summary> /// Creates a new certificate and saves it as X.509 cert file and a PFX file /// </summary> private static void Create() { // Create a self-signed cert byte[] pfxBytes = CertUtil.CreateSelfSignedCert( new X500DistinguishedName("CN=Windows Azure Tools"), keyAlias, DateTime.Now, expirationDate, password); // Write the cert into the .pfx file File.WriteAllBytes(pfxFileName, pfxBytes); // Export as x.509 cert (without the public key) byte[] cerBytes = new X509Certificate2(pfxBytes, password).Export(X509ContentType.Cert); // Write into the .cer file File.WriteAllBytes(certFileName, cerBytes); }
public static void SignByCertInfo(Dictionary <string, string> resData, Encoding encoding, ref string errorMessage) { try { //Dictionary<string, string> resData_Sign = resData; string signMethod = resData["signMethod"]; string certPath = Application.StartupPath + "\\Certificate\\" + "TestSign.pfx"; string certPwd = "00000000"; if ("01".Equals(signMethod)) { //resData["certId"] = CertUtil.GetSignCertId(certPath, certPwd); //将Dictionary信息转换成key1=value1&key2=value2的形式 string stringData = SDKUtil.CreateLinkString(resData, true, false, encoding); byte[] signDigest = SecurityUtil.Sha256(stringData, encoding); string stringSignDigest = SDKUtil.ByteArray2HexString(signDigest); byte[] byteSign = SecurityUtil.SignSha256WithRsa(CertUtil.GetSignKeyFromPfx(certPath, certPwd), encoding.GetBytes(stringSignDigest)); string stringSign = Convert.ToBase64String(byteSign); //设置签名域值 resData["signature"] = stringSign; return; } else { return; //log.Error("Error signMethod [" + signMethod + "] in SignByCertInfo. "); } } catch (Exception e) { errorMessage += e.Message; } }
/// <summary> /// The is valid crypto request. /// </summary> /// <param name="certificate"> /// The certificate. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> private static bool IsValidCryptoCertificate(X509Certificate certificate) { var certin = certificate as X509Certificate2; if (certin != null) { X509Certificate2 certOut = null; if (CertUtil.TryResolveCertificate(StoreName.CertificateAuthority, StoreLocation.LocalMachine, X509FindType.FindByThumbprint, certin.Thumbprint, out certOut)) { return(true); } // azure website only supports the current user store. if (CertUtil.TryResolveCertificate(StoreName.My, StoreLocation.CurrentUser, X509FindType.FindByThumbprint, certin.Thumbprint, out certOut)) { return(true); } } return(false); }
public async Task ThumbprintFailTest() { // Import the test certificate. X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(Constants.TestCert), string.Empty); CertUtil.ImportCertificate(cert); // MockAuthenticationContext is being asked to act like client cert auth failed. MockAuthenticationContext mockAuthenticationContext = new MockAuthenticationContext(MockAuthenticationContext.MockAuthenticationContextTestType.AcquireTokenAsyncClientCertificateFail); // Create ClientCertificateAzureServiceTokenProvider instance ClientCertificateAzureServiceTokenProvider provider = new ClientCertificateAzureServiceTokenProvider(Constants.TestAppId, cert.Thumbprint, CertificateIdentifierType.Thumbprint, Constants.CurrentUserStore, Constants.TenantId, Constants.AzureAdInstance, mockAuthenticationContext); // Ensure exception is thrown when getting the token var exception = await Assert.ThrowsAsync <AzureServiceTokenProviderException>(() => provider.GetAuthResultAsync(Constants.KeyVaultResourceId, Constants.TenantId)); Assert.Contains(AzureServiceTokenProviderException.GenericErrorMessage, exception.ToString()); // Delete the cert, since testing is done. CertUtil.DeleteCertificate(cert.Thumbprint); }
private static bool IsValidCryptoCertificate(X509Certificate certificate) { var certin = certificate as X509Certificate2; if (certin != null) { X509Certificate2 certOut = null; if (CertUtil.TryResolveCertificate(StoreName.CertificateAuthority, StoreLocation.LocalMachine, X509FindType.FindByThumbprint, certin.Thumbprint, out certOut)) { return(true); } // TODO: this is a temporary fix to allow fiddler certificates to pass validation. if (CertUtil.TryResolveCertificate(StoreName.My, StoreLocation.CurrentUser, X509FindType.FindByThumbprint, certin.Thumbprint, out certOut)) { return(true); } } return(false); }
public async Task ThumbprintSuccessTest() { // Import the test certificate. X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(Constants.TestCert), string.Empty); CertUtil.ImportCertificate(cert); // MockAuthenticationContext is being asked to act like client cert auth suceeded. MockAuthenticationContext mockAuthenticationContext = new MockAuthenticationContext(MockAuthenticationContext.MockAuthenticationContextTestType.AcquireTokenAsyncClientCertificateSuccess); // Create ClientCertificateAzureServiceTokenProvider instance ClientCertificateAzureServiceTokenProvider provider = new ClientCertificateAzureServiceTokenProvider(Constants.TestAppId, cert.Thumbprint, CertificateIdentifierType.Thumbprint, Constants.CurrentUserStore, Constants.TenantId, Constants.AzureAdInstance, mockAuthenticationContext); // Get the token. This will test that ClientCertificateAzureServiceTokenProvider could fetch the cert from CurrentUser store based on thumbprint in the connection string. var authResult = await provider.GetAuthResultAsync(Constants.KeyVaultResourceId, Constants.TenantId).ConfigureAwait(false); // Delete the cert, since testing is done. CertUtil.DeleteCertificate(cert.Thumbprint); Validator.ValidateToken(authResult.AccessToken, provider.PrincipalUsed, Constants.AppType, Constants.TenantId, Constants.TestAppId, cert.Thumbprint, expiresOn: authResult.ExpiresOn); }