private Attribute MakeSigningCertificateAttribute(SignatureParameters parameters) { try { byte[] certHash = DigestUtilities.CalculateDigest (parameters.DigestAlgorithm.GetName(), parameters.SigningCertificate.GetEncoded()); if (parameters.DigestAlgorithm == DigestAlgorithm.SHA1) { SigningCertificate sc = new SigningCertificate(new EssCertID(certHash)); return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(sc ))); } else { EssCertIDv2 essCert = new EssCertIDv2(new AlgorithmIdentifier(parameters.DigestAlgorithm .GetOid()), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert } ); return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet (scv2))); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (CertificateException e) { throw new RuntimeException(e); } }
public void TestBadSignature() { string certificateChain = WebUtility.UrlDecode("-----BEGIN%20CERTIFICATE-----%0AMIIEoTCCAwmgAwIBAgIJANEHdl0yo7CWMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV%0ABAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwLU2FudGEgQ2xhcmExGjAYBgNV%0ABAoMEUludGVsIENvcnBvcmF0aW9uMTAwLgYDVQQDDCdJbnRlbCBTR1ggQXR0ZXN0%0AYXRpb24gUmVwb3J0IFNpZ25pbmcgQ0EwHhcNMTYxMTIyMDkzNjU4WhcNMjYxMTIw%0AMDkzNjU4WjB7MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFDASBgNVBAcMC1Nh%0AbnRhIENsYXJhMRowGAYDVQQKDBFJbnRlbCBDb3Jwb3JhdGlvbjEtMCsGA1UEAwwk%0ASW50ZWwgU0dYIEF0dGVzdGF0aW9uIFJlcG9ydCBTaWduaW5nMIIBIjANBgkqhkiG%0A9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqXot4OZuphR8nudFrAFiaGxxkgma/Es/BA%2Bt%0AbeCTUR106AL1ENcWA4FX3K%2BE9BBL0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dJANXxLLIn6CfyvUZddMtePrTOLpC2e5QTQxB4RwtWmFfr7nxRdFUtA3dH2DAQL5DqqlmPv46ZWSPfiiOXUsu8vNgX3Z4Znt4Q+dIPIquNPY8ZmiAcpKR7n2K3QtabgOnJ2EyngabY3LMQTtriXbZjpl53ynhVhV1rciMdvMaTz4DUYt7gKi+KeNd3CBFSev+eTgYPC3em96J/3bfVR+wC5m3JGbIBCrwAsbO05JkiNIMck3s+p4d/hwiABR75EplxaWmGgIm6VvUKtGhdJ/cNrmF0nxMX6Vi6N2WaLTA=="; string signatureBody = "{\"id\":\"287419896494669543891634765983074535548\",\"timestamp\":\"2019-03-11T20:01:21.658293\",\"version\":3,\"isvEnclaveQuoteStatus\":\"OK\",\"isvEnclaveQuoteBody\":\"AgAAADILAAAIAAcAAAAAAPiLWcRSSA3shraxepsGV9qF4zYUPJgE42ZZZXS2G9zaBQUCBP//AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAHAAAAAAAAAM1s/DQpN7I7G907v5chqlYVrJ/1CnXFUn1EHNMnaCbJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADrzm117Qj8NlEllyDkV4Pae4UgsPjgVXtAA5UsG90gVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACHgz6GaO6bkxfPLBYcR5rEf9Itrt81OEanXteSMcd/BQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"}"; SigningCertificate certificate = new SigningCertificate(certificateChain); byte[] decodedSignature = Base64.Decode(signature); for (int i = 0; i < signature.Length; i++) { for (int j = 0; i < 8; i++) { byte[] malformedSignature = new byte[decodedSignature.Length]; Array.Copy(decodedSignature, 0, malformedSignature, 0, decodedSignature.Length); malformedSignature[i] ^= (byte)(0x01 << j); try { certificate.VerifySignature(signatureBody, Base64.EncodeBytes(malformedSignature)); Assert.Fail("Signature verification should fail!"); } catch (SignatureException) { // good } } } }
private static IServiceCollection AddSigningCertificates(IServiceCollection services, SigningCertificate signingCertificates) { CheckServiceProviderCetificatePrivateKey(signingCertificates); services.AddSingleton <ICertificateProvider>(new CertificateProvider(signingCertificates)); return(services); }
public TimeStampToken( CmsSignedData signedData) { this.tsToken = signedData; if (!this.tsToken.SignedContentTypeOid.Equals(PkcsObjectIdentifiers.IdCTTstInfo.Id)) { throw new TspValidationException("ContentInfo object not for a time stamp."); } ICollection signers = tsToken.GetSignerInfos().GetSigners(); if (signers.Count != 1) { throw new ArgumentException("Time-stamp token signed by " + signers.Count + " signers, but it must contain just the TSA signature."); } IEnumerator signerEnum = signers.GetEnumerator(); signerEnum.MoveNext(); tsaSignerInfo = (SignerInformation)signerEnum.Current; try { CmsProcessable content = tsToken.SignedContent; MemoryStream bOut = new MemoryStream(); content.Write(bOut); this.tstInfo = new TimeStampTokenInfo( TstInfo.GetInstance( Asn1Object.FromByteArray(bOut.ToArray()))); Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[ PkcsObjectIdentifiers.IdAASigningCertificate]; if (attr == null) { throw new TspValidationException( "no signing certificate attribute found, time stamp invalid."); } SigningCertificate signCert = SigningCertificate.GetInstance( attr.AttrValues[0]); this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]); } catch (CmsException e) { throw new TspException(e.Message, e.InnerException); } }
private static void CheckServiceProviderCetificatePrivateKey(SigningCertificate signingCertificates) { if (signingCertificates == null) { throw new ArgumentNullException(nameof(signingCertificates)); } if (!signingCertificates.ServiceProvider.HasPrivateKey) { throw new InvalidOperationException("Certificate does not have a private key."); } }
public PdfSignInfo(PdfPKCS7 pkcs7) { SignType = SignTypes.PAdES.ToString(); SignDate = pkcs7.SignDate; Reason = pkcs7.Reason; try { IsVerified = pkcs7.Verify(); } catch (Exception ex) { Console.WriteLine(string.Format("Verifica validità fallita: {0}", ex.Message)); } Certificate = new SigningCertificate() { SerialNumber = pkcs7.SigningCertificate.SerialNumber.IntValue.ToString("X"), NotBefore = pkcs7.SigningCertificate.NotBefore, NotAfter = pkcs7.SigningCertificate.NotAfter }; var issuerFields = CertificateInfo.GetIssuerFields(pkcs7.SigningCertificate); Certificate.Issuer = new IssuerDN() { SerialNumber = issuerFields.GetField("SN"), Organization = issuerFields.GetField("O"), OrganizationUnit = issuerFields.GetField("OU") }; var subjectFields = CertificateInfo.GetSubjectFields(pkcs7.SigningCertificate); Certificate.Subject = new SubjectDN() { SerialNumber = subjectFields.GetField("SN"), GivenName = subjectFields.GetField("GIVENNAME"), Surname = subjectFields.GetField("SURNAME"), CommonName = subjectFields.GetField("CN"), Organization = subjectFields.GetField("O") }; if (pkcs7.TimeStampToken != null) { Children = new List <SignInfo>() { new TsSignInfo(pkcs7) } } ; } }
public void IdentityManagementServiceUploadSigningCertificate() { #region e67489b6-7b73-4e30-9ed3-9a9e0231e458 var response = client.UploadSigningCertificate(new UploadSigningCertificateRequest { CertificateBody = "-----BEGIN CERTIFICATE-----<certificate-body>-----END CERTIFICATE-----", UserName = "******" }); SigningCertificate certificate = response.Certificate; #endregion }
public void TestBadChain() { string certificateChain = WebUtility.UrlDecode("-----BEGIN%20CERTIFICATE-----%0AMIIEoTCCAwmgAwIBAgIJANEHdl0yo7CWMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV%0ABAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwLU2FudGEgQ2xhcmExGjAYBgNV%0ABAoMEUludGVsIENvcnBvcmF0aW9uMTAwLgYDVQQDDCdJbnRlbCBTR1ggQXR0ZXN0%0AYXRpb24gUmVwb3J0IFNpZ25pbmcgQ0EwHhcNMTYxMTIyMDkzNjU4W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yleDnbuS8UicjJijvqA%0A152Sq049ESDz%2B1rRGc2NVEqh1KaGXmtXvqxXcTB%2BLjy5Bw2ke0v8iGngFBPqCTVB%0A3op5KBG3RjbF6RRSzwzuWfL7QErNC8WEy5yDVARzTA5%2BxmBc388v9Dm21HGfcC8O%0ADD%2BgT9sSpssq0ascmvH49MOgjt1yoysLtdCtJW/9FZpoOypaHx0R%2BmJTLwPXVMrv%0ADaVzWh5aiEx%2BidkSGMnX%0A-----END%20CERTIFICATE-----%0A"); SigningCertificate certificate = null; try { certificate = new SigningCertificate(certificateChain); Assert.Fail("Should not be a valid chain"); } catch (PkixCertPathValidatorException) { // Good } }
public TimeStampToken(CmsSignedData signedData) { tsToken = signedData; if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo)) { throw new TspValidationException("ContentInfo object not for a time stamp."); } ICollection signers = tsToken.GetSignerInfos().GetSigners(); if (signers.Count != 1) { throw new ArgumentException("Time-stamp token signed by " + signers.Count + " signers, but it must contain just the TSA signature."); } IEnumerator enumerator = signers.GetEnumerator(); enumerator.MoveNext(); tsaSignerInfo = (SignerInformation)enumerator.Current; try { CmsProcessable signedContent = tsToken.SignedContent; MemoryStream memoryStream = new MemoryStream(); signedContent.Write(memoryStream); tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(memoryStream.ToArray()))); Org.BouncyCastle.Asn1.Cms.Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate]; if (attribute != null) { SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]); certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0])); } else { attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]; if (attribute == null) { throw new TspValidationException("no signing certificate attribute found, time stamp invalid."); } SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]); certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0])); } } catch (CmsException ex) { throw new TspException(ex.Message, ex.InnerException); } }
internal void Validate() { if (MyHerId <= 0) { throw new ArgumentOutOfRangeException(nameof(MyHerId)); } if (DecryptionCertificate == null) { throw new ArgumentNullException(nameof(DecryptionCertificate)); } DecryptionCertificate.Validate(); if (SigningCertificate == null) { throw new ArgumentNullException(nameof(SigningCertificate)); } SigningCertificate.Validate(); ServiceBus.Validate(); }
public TimeStampToken(CmsSignedData signedData) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown tsToken = signedData; if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo)) { throw new TspValidationException("ContentInfo object not for a time stamp."); } global::System.Collections.ICollection signers = tsToken.GetSignerInfos().GetSigners(); if (signers.get_Count() != 1) { throw new ArgumentException(string.Concat((object)"Time-stamp token signed by ", (object)signers.get_Count(), (object)" signers, but it must contain just the TSA signature.")); } global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)signers).GetEnumerator(); enumerator.MoveNext(); tsaSignerInfo = (SignerInformation)enumerator.get_Current(); try { CmsProcessable signedContent = tsToken.SignedContent; MemoryStream val = new MemoryStream(); signedContent.Write((Stream)(object)val); tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(val.ToArray()))); Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate]; if (attribute != null) { SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]); certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0])); return; } attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]; if (attribute == null) { throw new TspValidationException("no signing certificate attribute found, time stamp invalid."); } SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]); certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0])); } catch (CmsException ex) { throw new TspException(((global::System.Exception)ex).get_Message(), ((global::System.Exception)ex).get_InnerException()); } }
/// <summary> /// Método para crear el atributo que contiene la información del certificado empleado para la firma /// </summary> /// <param name="parameters"></param> /// <returns></returns> private BcCms.Attribute MakeSigningCertificateAttribute(SignatureParameters parameters) { X509Certificate certificate = new X509CertificateParser().ReadCertificate(parameters.Certificate.GetRawCertData()); TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray( certificate.GetTbsCertificate())); GeneralName gn = new GeneralName(tbs.Issuer); GeneralNames gns = new GeneralNames(gn); IssuerSerial issuerSerial = new IssuerSerial(gns, tbs.SerialNumber); byte[] certHash = DigestUtilities.CalculateDigest(parameters.DigestMethod.Name, certificate.GetEncoded()); var policies = GetPolicyInformation(certificate); if (parameters.DigestMethod == DigestMethod.SHA1) { SigningCertificate sc = null; if (policies != null) { Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerSequence(new EssCertID(certHash, issuerSerial))); v.Add(new DerSequence(policies)); sc = SigningCertificate.GetInstance(new DerSequence(v)); } else { sc = new SigningCertificate(new EssCertID(certHash, issuerSerial)); } return(new BcCms.Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(sc))); } else { EssCertIDv2 essCert = new EssCertIDv2(new AlgorithmIdentifier(parameters.DigestMethod .Oid), certHash, issuerSerial); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert }, policies); return(new BcCms.Attribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet (scv2))); } }
private static SigningCertificate GetSigningCertificates(X509FindType findType, string serviceProviderCertificateName, string identityProviderCertificateName) { if (string.IsNullOrEmpty(serviceProviderCertificateName)) { throw new ArgumentNullException(nameof(serviceProviderCertificateName)); } if (string.IsNullOrEmpty(identityProviderCertificateName)) { throw new ArgumentNullException(nameof(identityProviderCertificateName)); } var serviceProviderCertificate = GetCertificate(serviceProviderCertificateName, findType); var identityProviderCertificate = GetCertificate(identityProviderCertificateName, findType); var certificates = new SigningCertificate(identityProviderCertificate, serviceProviderCertificate); return(certificates); }
private Attribute MakeSigningCertificateAttribute(SignatureParameters parameters) { byte[] certHash = DigestUtilities.CalculateDigest(Helpers.CmsSignedHelper.Instance.GetDigestAlgName(parameters.DigestAlgorithmOID), parameters.SigningCertificate.GetEncoded()); if (parameters.DigestAlgorithmOID == DigestAlgorithm.SHA1.OID) { SigningCertificate sc = new SigningCertificate(new EssCertID(certHash, new IssuerSerial( new GeneralNames(new GeneralName(parameters.SigningCertificate.IssuerDN)), new DerInteger(parameters.SigningCertificate.SerialNumber)))); //SigningCertificate sc = new SigningCertificate(new EssCertID(certHash)); return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(sc))); } else { EssCertIDv2 essCert = new EssCertIDv2(new AlgorithmIdentifier(new DerObjectIdentifier(parameters.DigestAlgorithmOID)), certHash, new IssuerSerial( new GeneralNames(new GeneralName(parameters.SigningCertificate.IssuerDN)), new DerInteger(parameters.SigningCertificate.SerialNumber))); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert }); return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2))); } }
public static string GetTokenFromApiKeyAsync(this HttpContext context) { var apiKey = context.Request.Query["ApiKey"]; var key = SigningCertificate.Load().GetRSAPrivateKey(); var client = (HttpClient)context.RequestServices.GetService(typeof(HttpClient)); var keys = (List <ApiKeyConfig>)Service.Config.ServiceConfiguration.ApiKeys; var validApiKey = keys.FirstOrDefault(x => x.ApiKey == apiKey); if (validApiKey == null) { return(null); } var decryptedApiKey = Encoding.UTF8.GetString(key.Decrypt(Convert.FromBase64String(validApiKey.EncryptedCredentials), RSAEncryptionPadding.OaepSHA512)); var userName = decryptedApiKey.Split(':')[0]; var password = decryptedApiKey.Split(':')[1]; var json = Login(validApiKey, userName, password, client).Result; return(json?.access_token); }
public P7kSignInfo(DigestSession digest, int pades, int p7k, int x509, int num, SignTypes signType) { SignType = signType.ToString(); SignDate = (DateTime?)digest.P7kGetSignAttribute(p7k, num, "signingTime"); var unstructuredName = digest.P7kGetSignAttribute(p7k, false, num, "unstructuredName"); Reason = GetReason((string)unstructuredName); switch (signType) { case SignTypes.PAdES: IsVerified = digest.PADES_Verify(pades); break; default: IsVerified = digest.P7kVerifySignature(p7k, num); break; } Certificate = new SigningCertificate() { SerialNumber = digest.X509GetInfo(x509, enumCertInfoCategory.CC_GENERAL, enumCertInfoItem.CI_SERIALNUMBER), NotBefore = digest.X509GetInfo(x509, enumCertInfoCategory.CC_GENERAL, enumCertInfoItem.CI_VALID_FROM).ChangeType <DateTime>(), NotAfter = digest.X509GetInfo(x509, enumCertInfoCategory.CC_GENERAL, enumCertInfoItem.CI_VALID_TO).ChangeType <DateTime>() }; Certificate.Issuer = new IssuerDN() { SerialNumber = digest.X509GetInfo(x509, enumCertInfoCategory.CC_ISSUER, enumCertInfoItem.CI_SERIALNUMBER), Organization = digest.X509GetInfo(x509, enumCertInfoCategory.CC_ISSUER, enumCertInfoItem.CI_NAME) }; Certificate.Subject = new SubjectDN() { SerialNumber = digest.X509GetInfo(x509, enumCertInfoCategory.CC_SUBJECT, enumCertInfoItem.CI_FISCALCODE), GivenName = digest.X509GetInfo(x509, enumCertInfoCategory.CC_SUBJECT, enumCertInfoItem.CI_FIRSTNAME), Surname = digest.X509GetInfo(x509, enumCertInfoCategory.CC_SUBJECT, enumCertInfoItem.CI_LASTNAME), CommonName = digest.X509GetInfo(x509, enumCertInfoCategory.CC_SUBJECT, enumCertInfoItem.CI_NAME) }; }
public override void OnActionExecuting(ActionExecutingContext context) { var apiKey = context.HttpContext.Request.Query["ApiKey"]; var jwtToken = context.HttpContext.Request.Query.ContainsKey("ApiKey") ? GetTokenFromApiKeyAsync(context.HttpContext.Request.Query["ApiKey"]) : GetAuthJwtToken(context) ; try { var key = SigningCertificate.Load().GetRSAPrivateKey(); var payload = JWT.Decode <JwtToken>(jwtToken.Replace("Bearer ", ""), key, JwsAlgorithm.RS256); var tokenExpires = DateTimeOffset.FromUnixTimeSeconds(payload.exp); _user = tokenExpires > DateTime.UtcNow ? _userManager.SetUser(payload, jwtToken) : null; } catch (Exception e) { LoggingBootstrapper.GetLogger().Fatal(e); _user = null; } base.OnActionExecuting(context); }
public TSSignInfo(DigestSession digest, int p7x, int ts, int index) { SignType = SignTypes.TimeStamp.ToString(); SignDate = digest.TSGetDateAndTime(ts); IsVerified = digest.TSVerify(ts); Certificate = new SigningCertificate() { SerialNumber = digest.TSGetTSPInfo(ts, enumCertInfoCategory.CC_GENERAL, enumCertInfoItem.CI_SERIALNUMBER), NotBefore = digest.TSGetTSPInfo(ts, enumCertInfoCategory.CC_GENERAL, enumCertInfoItem.CI_VALID_FROM).ChangeType <DateTime>(), NotAfter = digest.TSGetTSPInfo(ts, enumCertInfoCategory.CC_GENERAL, enumCertInfoItem.CI_VALID_TO).ChangeType <DateTime>() }; Certificate.Issuer = new IssuerDN() { Organization = digest.TSGetTSPInfo(ts, enumCertInfoCategory.CC_ISSUER, enumCertInfoItem.CI_NAME) }; Certificate.Subject = new SubjectDN() { CommonName = digest.TSGetTSPInfo(ts, enumCertInfoCategory.CC_SUBJECT, enumCertInfoItem.CI_NAME) }; }
public void ConfigureServices(IServiceCollection services) { var database = services.AddMongoDatabase(Configuration); services.AddDataProtection() .SetApplicationName("identityserver") .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"/var/dpkeys/")); var mongoUserStore = new MongoUserStore(database); var hasher = new PasswordHasher <MongoExternalUser>(); // var mongoExternalUser = mongoUserStore.AutoProvisionUser("IdSrv", "alex", new List<Claim>() // { // new Claim(JwtClaimTypes.Name,"alex"), // new Claim(JwtClaimTypes.Email, "*****@*****.**") // }).Result; // var hash = hasher.HashPassword(mongoExternalUser as MongoExternalUser, "test"); // var updateResult = mongoUserStore.SetPasswordHashForUser(mongoExternalUser, hash).Result; services.AddSingleton <MongoUserStore>(mongoUserStore); services.AddRepositories(database); services.AddMvc(); services.AddIdentityServer() .AddSigningCredential(SigningCertificate.GetSigningCertificate()) .AddMongoRepository() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddIdentityApiResources() .AddPersistedGrants() .AddInMemoryClients(Config.GetClients(Configuration)) .AddProfileService <ProfileService>(); services .AddAuthentication() .AddExternalAuth(Configuration); }
public TsSignInfo(PdfPKCS7 pkcs7) { SignType = "TimeStamp"; SignDate = pkcs7.TimeStampDate; try { IsVerified = pkcs7.VerifyTimestampImprint(); } catch (Exception ex) { Console.WriteLine(string.Format("Verifica validità fallita: {0}", ex.Message)); } Certificate = new SigningCertificate() { SerialNumber = pkcs7.TimeStampToken.SignerID.SerialNumber.IntValue.ToString("X"), }; if (pkcs7.TimeStampToken.SignerID.Certificate != null) { Certificate.NotBefore = pkcs7.TimeStampToken.SignerID.Certificate.NotBefore; Certificate.NotAfter = pkcs7.TimeStampToken.SignerID.Certificate.NotAfter; } var tsa = (X509Name)pkcs7.TimeStampToken.TimeStampInfo.Tsa.Name; Certificate.Issuer = new IssuerDN() { Organization = tsa.GetValues(new DerObjectIdentifier(OID_O)).ToArray().FirstOrDefault().ToString(), OrganizationUnit = tsa.GetValues(new DerObjectIdentifier(OID_OU)).ToArray().FirstOrDefault().ToString() }; Certificate.Subject = new SubjectDN() { CommonName = tsa.GetValues(new DerObjectIdentifier(OID_CN)).ToArray().FirstOrDefault().ToString() }; }
private void ReadInformation() { if (_signerInformation.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime] != null) { _signingDate = DerUtcTime.GetInstance(_signerInformation.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime].AttrValues[0]).ToDateTime().ToLocalTime(); } if (_signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAAEtsSignerAttr] != null) { var signerAttr = SignerAttribute.GetInstance(_signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAAEtsSignerAttr].AttrValues[0]); List <string> claimedRoles = new List <string>(); foreach (BcCms.Attribute claimedAttr in signerAttr.ClaimedAttributes) { foreach (var value in claimedAttr.AttrValues) { claimedRoles.Add(DerUtf8String.GetInstance(value).GetString()); } } _signerRoles = claimedRoles; } if (_signerInformation.UnsignedAttributes != null && _signerInformation.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] != null) { _timeStamp = new TimeStampToken(new CmsSignedData(_signerInformation.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrValues[0].GetEncoded())); } // Se leen las contrafirmas var signers = _signerInformation.GetCounterSignatures().GetSigners(); _counterSignatures = new List <SignerInfoNode>(); foreach (var signer in signers) { SignerInfoNode node = new SignerInfoNode((SignerInformation)signer, _sigDocument); _counterSignatures.Add(node); } // Se intenta identificar el certificado empleado para la firma, esto quizás se pueda mejorar byte[] certHash = null; IssuerSerial issuerSerial = null; if (_signerInformation.DigestAlgOid == DigestMethod.SHA1.Oid) { BcCms.Attribute attr = _signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate]; SigningCertificate sc = SigningCertificate.GetInstance(attr.AttrValues[0]); EssCertID ecid = sc.GetCerts()[0]; issuerSerial = ecid.IssuerSerial; certHash = ecid.GetCertHash(); } else { BcCms.Attribute attr = _signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]; SigningCertificateV2 sc2 = SigningCertificateV2.GetInstance(attr.AttrValues[0]); EssCertIDv2 ecid = sc2.GetCerts()[0]; issuerSerial = ecid.IssuerSerial; certHash = ecid.GetCertHash(); } DigestMethod digestMethod = DigestMethod.GetByOid(_signerInformation.DigestAlgOid); foreach (X509CertificateStructure cs in _sigDocument.Certificates) { if (issuerSerial == null || cs.TbsCertificate.SerialNumber.Equals(issuerSerial.Serial)) { byte[] currentCertHash = digestMethod.CalculateDigest(cs.GetEncoded()); if (certHash.SequenceEqual(currentCertHash)) { _certificate = new X509Certificate(cs); break; } } } }
private CmsSignedData GenerateTimestamp( TimeStampRequest request, BigInteger serialNumber, DateTime generalizedTime) { var messageImprint = new MessageImprint( new AlgorithmIdentifier( new DerObjectIdentifier(request.MessageImprintAlgOid)), request.GetMessageImprintDigest()); DerInteger nonce = request.Nonce == null ? null : new DerInteger(request.Nonce); var tstInfo = new TstInfo( new DerObjectIdentifier(_options.Policy.Value), messageImprint, new DerInteger(serialNumber), new DerGeneralizedTime(generalizedTime), _options.Accuracy, DerBoolean.False, nonce, tsa: null, extensions: null); var content = new CmsProcessableByteArray(tstInfo.GetEncoded()); var signedAttributes = new Asn1EncodableVector(); var certificateBytes = new Lazy <byte[]>(() => Certificate.GetEncoded()); if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V1)) { byte[] hash = _options.SigningCertificateV1Hash ?? DigestUtilities.CalculateDigest("SHA-1", certificateBytes.Value); var signingCertificate = new SigningCertificate(new EssCertID(hash)); var attributeValue = new DerSet(signingCertificate); var attribute = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificate, attributeValue); signedAttributes.Add(attribute); } if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V2)) { byte[] hash = DigestUtilities.CalculateDigest("SHA-256", certificateBytes.Value); var signingCertificateV2 = new SigningCertificateV2(new EssCertIDv2(hash)); var attributeValue = new DerSet(signingCertificateV2); var attribute = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, attributeValue); signedAttributes.Add(attribute); } var generator = new CmsSignedDataGenerator(); if (_options.ReturnSigningCertificate) { var certificates = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(new[] { Certificate })); generator.AddCertificates(certificates); } generator.AddSigner( _keyPair.Private, Certificate, _options.SignatureHashAlgorithm.Value, new BcAttributeTable(signedAttributes), new BcAttributeTable(DerSet.Empty)); CmsSignedData signedCms = generator.Generate( PkcsObjectIdentifiers.IdCTTstInfo.Id, content, encapsulate: true); return(signedCms); }
public static Asn1EncodableVector GenerateSignerInfo(X509Certificate2 cert, String digestAlgorithmName, byte[] datos, AdESPolicy policy, bool signingCertificateV2, byte[] messageDigest, DateTime signDate, bool padesMode, String contentType, String contentDescription) { // ALGORITMO DE HUELLA DIGITAL AlgorithmIdentifier digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName)); // // ATRIBUTOS // authenticatedAttributes Asn1EncodableVector contexExpecific = InitContexExpecific( digestAlgorithmName, datos, Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id, messageDigest, signDate, padesMode ); // Serial Number // comentar lo de abajo para version del rfc 3852 if (signingCertificateV2) { // INICIO SINGING CERTIFICATE-V2 /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber * CertificateSerialNumber */ TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray( new Org.BouncyCastle.X509.X509Certificate( X509CertificateStructure.GetInstance( Asn1Object.FromByteArray( cert.GetRawCertData()))).GetTbsCertificate())); GeneralNames gns = new GeneralNames(new GeneralName(tbs.Issuer)); IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber); /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial * IssuerSerial OPTIONAL } * Hash ::= OCTET STRING */ byte[] certHash = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName); EssCertIDv2[] essCertIDv2 = { new EssCertIDv2(digestAlgorithmOID, certHash, isuerSerial) }; /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId, * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo * OPTIONAL } * CertPolicyId ::= OBJECT IDENTIFIER * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */ SigningCertificateV2 scv2; if (policy.GetPolicyIdentifier() != null) { /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL * } */ scv2 = new SigningCertificateV2(essCertIDv2, GetPolicyInformation(policy)); // con politica } else { scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica } // Secuencia con singningCertificate contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2))); // FIN SINGING CERTIFICATE-V2 } else { // INICIO SINGNING CERTIFICATE /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber * CertificateSerialNumber } */ TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray( new Org.BouncyCastle.X509.X509Certificate( X509CertificateStructure.GetInstance( Asn1Object.FromByteArray( cert.GetRawCertData()))).GetTbsCertificate())); GeneralName gn = new GeneralName(tbs.Issuer); GeneralNames gns = new GeneralNames(gn); IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber); /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial * OPTIONAL } * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */ byte[] certHash = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName); EssCertID essCertID = new EssCertID(certHash, isuerSerial); /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId, * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo * OPTIONAL } * CertPolicyId ::= OBJECT IDENTIFIER * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */ SigningCertificate scv; if (policy.GetPolicyIdentifier() != null) { /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL * } */ /* * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY * CASTLE NO TIENE DICHO CONSTRUCTOR. */ Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerSequence(essCertID)); v.Add(new DerSequence(GetPolicyInformation(policy))); scv = SigningCertificate.GetInstance(new DerSequence(v)); // con politica } else { scv = new SigningCertificate(essCertID); // Sin politica } /** id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1) * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16) * id-aa(2) 12 } */ // Secuencia con singningCertificate contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(scv))); } // INICIO SIGPOLICYID ATTRIBUTE if (policy.GetPolicyIdentifier() != null) { /** * SigPolicyId ::= OBJECT IDENTIFIER Politica de firma. */ DerObjectIdentifier doiSigPolicyId = new DerObjectIdentifier(policy.GetPolicyIdentifier().ToLower().Replace("urn:oid:", "")); /** * OtherHashAlgAndValue ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * hashValue OCTET STRING } * */ // Algoritmo para el hash AlgorithmIdentifier hashid; // si tenemos algoritmo de calculo de hash, lo ponemos if (policy.GetPolicyIdentifierHashAlgorithm() != null) { hashid = SigUtils.MakeAlgId( AOAlgorithmID.GetOID( AOSignConstants.GetDigestAlgorithmName( policy.GetPolicyIdentifierHashAlgorithm()))); } // si no tenemos, ponemos el algoritmo de firma. else { hashid = digestAlgorithmOID; } // hash del documento, descifrado en b64 byte[] hashed; if (policy.GetPolicyIdentifierHash() != null) { hashed = System.Convert.FromBase64String(policy.GetPolicyIdentifierHash()); } else { hashed = new byte[] { 0 }; } DigestInfo otherHashAlgAndValue = new DigestInfo(hashid, hashed); /** * SigPolicyQualifierInfo ::= SEQUENCE { * SigPolicyQualifierId SigPolicyQualifierId, * SigQualifier ANY DEFINED BY policyQualifierId } */ AOSigPolicyQualifierInfo spqInfo = null; if (policy.GetPolicyQualifier() != null) { spqInfo = new AOSigPolicyQualifierInfo(policy.GetPolicyQualifier().ToString()); } /** * SignaturePolicyId ::= SEQUENCE { * sigPolicyId SigPolicyId, * sigPolicyHash SigPolicyHash, * sigPolicyQualifiers SEQUENCE SIZE (1..MAX) OF * AOSigPolicyQualifierInfo OPTIONAL} * */ Asn1EncodableVector v = new Asn1EncodableVector(); // sigPolicyId v.Add(doiSigPolicyId); // sigPolicyHash v.Add(otherHashAlgAndValue.ToAsn1Object()); // como sequence // sigPolicyQualifiers if (spqInfo != null) { v.Add(spqInfo.toASN1Primitive()); } DerSequence ds = new DerSequence(v); // Secuencia con singningCertificate contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAEtsSigPolicyID, new DerSet(ds.ToAsn1Object()))); // FIN SIGPOLICYID ATTRIBUTE } /** * Secuencia con el tipo de contenido firmado. No se agrega en firmas PAdES. * * ContentHints ::= SEQUENCE { * contentDescription UTF8String (SIZE (1..MAX)) OPTIONAL, * contentType ContentType } */ if (contentType != null && !padesMode) { ContentHints contentHints; if (contentDescription != null) { contentHints = new ContentHints(new DerObjectIdentifier(contentType), new DerUtf8String(contentDescription)); } else { contentHints = new ContentHints(new DerObjectIdentifier(contentType)); } contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute( Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAContentHint, new DerSet(contentHints.ToAsn1Object()))); } return(contexExpecific); }
private void overrideAttrsTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { SignerInfoGeneratorBuilder signerInfoGenBuilder = new SignerInfoGeneratorBuilder(); IssuerSerial issuerSerial = new IssuerSerial( new GeneralNames( new GeneralName( X509CertificateStructure.GetInstance(cert.GetEncoded()).Issuer)), new DerInteger(cert.SerialNumber)); byte[] certHash256; byte[] certHash; { Asn1DigestFactory digCalc = Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1); IStreamCalculator calc = digCalc.CreateCalculator(); using (Stream s = calc.Stream) { byte[] crt = cert.GetEncoded(); s.Write(crt, 0, crt.Length); } certHash = ((SimpleBlockResult)calc.GetResult()).Collect(); } { Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256); IStreamCalculator calc = digCalc.CreateCalculator(); using (Stream s = calc.Stream) { byte[] crt = cert.GetEncoded(); s.Write(crt, 0, crt.Length); } certHash256 = ((SimpleBlockResult)calc.GetResult()).Collect(); } EssCertID essCertID = new EssCertID(certHash, issuerSerial); EssCertIDv2 essCertIDv2 = new EssCertIDv2(certHash256, issuerSerial); signerInfoGenBuilder.WithSignedAttributeGenerator(new TestAttrGen(essCertID, essCertIDv2)); Asn1SignatureFactory sigfact = new Asn1SignatureFactory("SHA1WithRSA", privateKey); SignerInfoGenerator signerInfoGenerator = signerInfoGenBuilder.Build(sigfact, cert); TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(signerInfoGenerator, Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1), new DerObjectIdentifier("1.2"), true); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); Asn1.Cms.AttributeTable table = tsToken.SignedAttributes; Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found"); Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2], "no signingCertificateV2 attribute found"); SigningCertificate sigCert = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificate].AttrValues[0]); Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCert.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name)); Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCert.GetCerts()[0].IssuerSerial.Serial.Value)); Assert.IsTrue(Arrays.AreEqual(certHash, sigCert.GetCerts()[0].GetCertHash())); SigningCertificate sigCertV2 = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]); Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name)); Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Serial.Value)); Assert.IsTrue(Arrays.AreEqual(certHash256, sigCertV2.GetCerts()[0].GetCertHash())); }
public X509Certificate2 GetSigningCertificate() { return(SigningCertificate.GetCertificate() ?? EmbeddedSigningCertificate.GetCertificate()); }