Example #1
0
        public void CreateTimeStampASN1()
        {
            try
            {
                DocumentHash documentHash = new DocumentHash();
                documentHash.DigestMethod           = new DigestMethodType();
                documentHash.DigestMethod.Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
                documentHash.DigestValue            = CrearHashTexto("TEXTODEPRUEBA");

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Creando sello de tiempo"));

                var timeStamp = _tsaService.CreateTimeStamp(RequestSignatureType.ASN1, documentHash);

                string resultado = TestContext.TestRunResultsDirectory + "\\Sello_Base64.txt";

                File.WriteAllText(resultado, Convert.ToBase64String(timeStamp.Item as byte[]));

                TestContext.AddResultFile(resultado);

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Sello aplicado"));
            }
            catch (AfirmaResultException afirmaEx)
            {
                Assert.Fail(string.Format("Error devuelto por @firma: {0}", afirmaEx.Message));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
            }
        }
Example #2
0
        public void ValidarSelloXML()
        {
            // NOTA: el servidor de desarrollo devuelve java.lang.NullPointerException, en producción funciona correctamente

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(SignatureType));
                SignatureType sello      = (SignatureType)serializer.Deserialize(ObtenerStreamRecurso("IntegraAfirmaNet.Test.SellosTiempo.Sello.xml"));

                DocumentHash documentHash = new DocumentHash();
                documentHash.DigestMethod           = new DigestMethodType();
                documentHash.DigestMethod.Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
                documentHash.DigestValue            = CrearHashTexto("TEXTODEPRUEBA");

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Validando sello de tiempo"));

                Timestamp timeStamp = new Timestamp();
                timeStamp.Item = sello;

                VerifyResponse resultado = _tsaService.VerifyTimestamp(documentHash, timeStamp);

                Assert.AreEqual(ResultType.Success.Uri, resultado.Result.ResultMajor);

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Sello válido"));
            }
            catch (AfirmaResultException afirmaEx)
            {
                Assert.Fail(string.Format("Error devuelto por @firma: {0}", afirmaEx.Message));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
            }
        }
Example #3
0
        public void ValidarFirmaCadesDetached()
        {
            try
            {
                byte[] firma = ObtenerRecurso("IntegraAfirmaNet.Test.Firmas.cades_detached_explicit.csig");

                DocumentHash docHash = new DocumentHash();
                docHash.DigestMethod           = new DigestMethodType();
                docHash.DigestMethod.Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
                docHash.DigestValue            = Convert.FromBase64String("11I1LxBkDvUpLwZqf2PHDmlQRM2vpf3t2Bg0kKODA8c=");

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Verificando firma"));

                VerifyResponse resultado = _afirmaService.VerifySignature(firma, SignatureFormat.CAdES, true, new DocumentBaseType[] { docHash });

                Assert.AreEqual(ResultType.ValidSignature.Uri, resultado.Result.ResultMajor);

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Firma válida"));
            }
            catch (AfirmaResultException afirmaEx)
            {
                Assert.Fail(string.Format("Error devuelto por @firma: {0}", afirmaEx.Message));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
            }
        }
Example #4
0
        public void ValidarSelloASN1()
        {
            try
            {
                string sellob64 = Encoding.UTF8.GetString(ObtenerRecurso("IntegraAfirmaNet.Test.SellosTiempo.Sello_Base64.txt"));

                DocumentHash documentHash = new DocumentHash();
                documentHash.DigestMethod           = new DigestMethodType();
                documentHash.DigestMethod.Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
                documentHash.DigestValue            = CrearHashTexto("TEXTODEPRUEBA");

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Validando sello de tiempo"));

                Timestamp timeStamp = new Timestamp();
                timeStamp.Item = Convert.FromBase64String(sellob64);

                VerifyResponse resultado = _tsaService.VerifyTimestamp(documentHash, timeStamp);

                Assert.AreEqual(ResultType.Success.Uri, resultado.Result.ResultMajor);

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Sello válido"));
            }
            catch (AfirmaResultException afirmaEx)
            {
                Assert.Fail(string.Format("Error devuelto por @firma: {0}", afirmaEx.Message));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
            }
        }
Example #5
0
        public async Task GetPublishReportsById()
        {
            // arrange
            IMongoCollection <Schema> schemas =
                _mongoResource.CreateCollection <Schema>();
            IMongoCollection <SchemaVersion> versions =
                _mongoResource.CreateCollection <SchemaVersion>();
            IMongoCollection <SchemaPublishReport> publishReports =
                _mongoResource.CreateCollection <SchemaPublishReport>();

            var initial = new Schema("foo", "bar");
            await schemas.InsertOneAsync(initial, options : null, default);

            var initialVersion = new SchemaVersion(
                initial.Id, "foo",
                DocumentHash.FromSourceText("abc"),
                Array.Empty <Tag>(),
                DateTime.UtcNow);
            await versions.InsertOneAsync(initialVersion, options : null, default);

            var initialReport = new SchemaPublishReport(
                initialVersion.Id, Guid.NewGuid(), Array.Empty <Issue>(),
                PublishState.Published, DateTime.UtcNow);
            await publishReports.InsertOneAsync(initialReport, options : null, default);

            var repository = new SchemaRepository(schemas, versions, publishReports);

            // act
            IReadOnlyDictionary <Guid, SchemaPublishReport> retrieved =
                await repository.GetPublishReportsAsync(new[] { initialReport.Id });

            // assert
            Assert.True(retrieved.ContainsKey(initialReport.Id));
        }
Example #6
0
        public void AmpliarACadesADetached()
        {
            try
            {
                byte[] firma = ObtenerRecurso("IntegraAfirmaNet.Test.Firmas.cades_detached_explicit.csig");

                DocumentHash docHash = new DocumentHash();
                docHash.DigestMethod           = new DigestMethodType();
                docHash.DigestMethod.Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
                docHash.DigestValue            = Convert.FromBase64String("11I1LxBkDvUpLwZqf2PHDmlQRM2vpf3t2Bg0kKODA8c=");

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Ampliando firma"));

                byte[] firmaAmpliada = _afirmaService.UpgradeSignature(firma, SignatureFormat.CAdES, ReturnUpdatedSignatureType.AdES_A, null, new DocumentBaseType[] { docHash });

                string resultado = TestContext.TestRunResultsDirectory + "\\FirmaCades-Detached-A.csig";

                File.WriteAllBytes(resultado, firmaAmpliada);

                TestContext.AddResultFile(resultado);

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Firma ampliada"));
            }
            catch (AfirmaResultException afirmaEx)
            {
                Assert.Fail(string.Format("Error devuelto por @firma: {0}", afirmaEx.Message));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
            }
        }
Example #7
0
 public RelayQuery(
     string name,
     DocumentHash hash,
     string sourceText)
 {
     Name       = name;
     Hash       = hash;
     SourceText = sourceText;
 }
Example #8
0
        private async Task HandleInternalAsync(
            PublishDocumentMessage message,
            CancellationToken cancellationToken)
        {
            var issueLogger = new IssueLogger(message.SessionId, _eventSender);

            try
            {
                IFileContainer fileContainer =
                    await _fileStorage.GetContainerAsync(message.SessionId).ConfigureAwait(false);

                IEnumerable <IFile> files =
                    await fileContainer.GetFilesAsync(cancellationToken).ConfigureAwait(false);

                IFile schemaFile = files.Single();

                DocumentNode?schemaDocument = await TryParseSchemaAsync(
                    schemaFile, issueLogger, cancellationToken)
                                              .ConfigureAwait(false);

                string formattedSourceText = schemaDocument is { }
                    ?  PrintSchema(schemaDocument)
                    : await ReadSchemaSourceTextAsync(
                    schemaFile, cancellationToken)
                .ConfigureAwait(false);

                DocumentHash documentHash = DocumentHash.FromSourceText(formattedSourceText);

                SchemaVersion?schemaVersion =
                    await _schemaRepository.GetSchemaVersionByHashAsync(
                        documentHash.Hash, cancellationToken)
                    .ConfigureAwait(false);

                if (schemaVersion is null)
                {
                    await PublishNewSchemaVersionAsync(
                        message,
                        schemaDocument,
                        formattedSourceText,
                        issueLogger,
                        cancellationToken)
                    .ConfigureAwait(false);
                }
                else
                {
                    await PublishExistingSchemaVersionAsync(
                        message,
                        schemaDocument,
                        schemaVersion,
                        issueLogger,
                        cancellationToken)
                    .ConfigureAwait(false);
                }

                await fileContainer.DeleteAsync(cancellationToken).ConfigureAwait(false);
            }
 public XElement Serialize()
 {
     return(new XElement(UblNames.Cac + nameof(ExternalReference),
                         URI.Serialize(nameof(URI)),
                         DocumentHash.Serialize(nameof(DocumentHash)),
                         HashAlgorithmMethod.Serialize(nameof(HashAlgorithmMethod)),
                         ExpiryDate.Serialize(nameof(ExpiryDate)),
                         ExpiryTime.Serialize(nameof(ExpiryTime)),
                         MimeCode.Serialize(nameof(MimeCode)),
                         FormatCode.Serialize(nameof(FormatCode)),
                         EncodingCode.Serialize(nameof(EncodingCode)),
                         CharacterSetCode.Serialize(nameof(CharacterSetCode)),
                         FileName.Serialize(nameof(FileName)),
                         Description.Serialize(nameof(Description))
                         ));
 }
Example #10
0
        public async Task UpdatePublishReport()
        {
            // arrange
            IMongoCollection <Schema> schemas =
                _mongoResource.CreateCollection <Schema>();
            IMongoCollection <SchemaVersion> versions =
                _mongoResource.CreateCollection <SchemaVersion>();
            IMongoCollection <SchemaPublishReport> publishReports =
                _mongoResource.CreateCollection <SchemaPublishReport>();
            IMongoCollection <PublishedSchema> publishedSchemas =
                _mongoResource.CreateCollection <PublishedSchema>();

            var initial = new Schema("foo", "bar");
            await schemas.InsertOneAsync(initial, options : null, default);

            var initialVersion = new SchemaVersion(
                initial.Id,
                "foo",
                DocumentHash.FromSourceText("bar"),
                Array.Empty <Tag>(),
                DateTime.UtcNow);
            await versions.InsertOneAsync(initialVersion, options : null, default);

            var initialReport = new SchemaPublishReport(
                initialVersion.Id, Guid.NewGuid(), Array.Empty <Issue>(),
                PublishState.Published, DateTime.UtcNow);
            await publishReports.InsertOneAsync(initialReport, options : null, default);

            var repository = new SchemaRepository(
                schemas, versions, publishReports, publishedSchemas);

            // act
            await repository.SetPublishReportAsync(new SchemaPublishReport(
                                                       initialReport.Id, initialReport.SchemaVersionId,
                                                       initialReport.EnvironmentId, initialReport.Issues,
                                                       PublishState.Rejected, DateTime.UtcNow));

            // assert
            IReadOnlyDictionary <Guid, SchemaPublishReport> retrieved =
                await repository.GetPublishReportsAsync(new[] { initialReport.Id });

            Assert.Equal(PublishState.Rejected, retrieved[initialReport.Id].State);
        }
Example #11
0
        public async Task GetSchemaVersionAsNode()
        {
            // arrange
            var serializer = new IdSerializer();
            var schema     = new Schema(Guid.NewGuid(), "abc", "def");
            await SchemaRepository.AddSchemaAsync(schema);

            var schemaVersion = new SchemaVersion(
                Guid.NewGuid(), schema.Id, "abc", DocumentHash.FromSourceText("def"),
                Array.Empty <Tag>(), DateTime.UnixEpoch);
            await SchemaRepository.AddSchemaVersionAsync(schemaVersion);

            string id = serializer.Serialize("SchemaVersion", schemaVersion.Id);

            IFileContainer container = await Storage.CreateContainerAsync(
                schemaVersion.Id.ToString("N", CultureInfo.InvariantCulture));

            byte[] buffer = Encoding.UTF8.GetBytes("SourceTextAbc");
            await container.CreateFileAsync("schema.graphql", buffer, 0, buffer.Length);

            // act
            IExecutionResult result = await Executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQuery(
                    @"query($id: ID!) {
                            node(id: $id) {
                                id
                                ... on SchemaVersion {
                                    sourceText
                                    hash {
                                        hash
                                    }
                                }
                            }
                        }")
                .SetVariableValue("id", id)
                .Create());

            // assert
            result.MatchSnapshot(o =>
                                 o.Assert(fo =>
                                          Assert.Equal(id, fo.Field <string>("Data.node.id"))));
        }
Example #12
0
        public void ReSelladoXML()
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(SignatureType));
                SignatureType sello      = (SignatureType)serializer.Deserialize(ObtenerStreamRecurso("IntegraAfirmaNet.Test.SellosTiempo.Sello.xml"));

                DocumentHash documentHash = new DocumentHash();
                documentHash.DigestMethod           = new DigestMethodType();
                documentHash.DigestMethod.Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
                documentHash.DigestValue            = CrearHashTexto("TEXTODEPRUEBA");

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Validando sello de tiempo"));

                Timestamp timeStamp = new Timestamp();
                timeStamp.Item = sello;

                var newTimestamp = _tsaService.RenewTimeStamp(timeStamp, documentHash);

                sello = newTimestamp.Item as SignatureType;

                string resultado = TestContext.TestRunResultsDirectory + "\\Sello.xml";

                using (XmlWriter writer = XmlWriter.Create(resultado))
                {
                    serializer.Serialize(writer, sello);
                }

                TestContext.AddResultFile(resultado);

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Sello aplicado"));
            }
            catch (AfirmaResultException afirmaEx)
            {
                Assert.Fail(string.Format("Error devuelto por @firma: {0}", afirmaEx.Message));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
            }
        }
Example #13
0
        public async Task GetSchemaVersion_By_ExternalId()
        {
            // arrange
            IMongoCollection <Schema> schemas =
                _mongoResource.CreateCollection <Schema>();
            IMongoCollection <SchemaVersion> versions =
                _mongoResource.CreateCollection <SchemaVersion>();
            IMongoCollection <SchemaPublishReport> publishReports =
                _mongoResource.CreateCollection <SchemaPublishReport>();
            IMongoCollection <PublishedSchema> publishedSchemas =
                _mongoResource.CreateCollection <PublishedSchema>();

            var repository = new SchemaRepository(
                schemas, versions, publishReports, publishedSchemas);

            var schema = new Schema("foo", "bar");
            await repository.AddSchemaAsync(schema);

            var schemaVersion = new SchemaVersion(
                schema.Id,
                "bar",
                DocumentHash.FromSourceText("bar"),
                new[]
            {
                new Tag("a", "b", DateTime.UtcNow)
            },
                DateTime.UtcNow);
            await repository.AddSchemaVersionAsync(schemaVersion);

            // act
            SchemaVersion retrieved = await repository.GetSchemaVersionByExternalIdAsync(
                schemaVersion.ExternalId);

            // assert
            Assert.NotNull(retrieved);
            Assert.Equal(schemaVersion.Id, retrieved.Id);
            Assert.Equal(schemaVersion.Published, retrieved.Published, TimeSpan.FromSeconds(1));
            Assert.Equal(schemaVersion.SchemaId, retrieved.SchemaId);
            Assert.Equal(schemaVersion.ExternalId, retrieved.ExternalId);
            Assert.Equal(schemaVersion.Tags.Count, retrieved.Tags.Count);
        }
        /// <inheritdoc />
        public async Task <TryteString> PublishInvoiceHashAsync(byte[] document, CngKey key)
        {
            var payload = new InvoicePayload(DocumentHash.Create(document),
                                             Encryption.CreateSignatureScheme(key).SignData(document));

            var bundle = new Bundle();

            bundle.AddTransfer(new Transfer
            {
                Address   = new Address(Seed.Random().Value),
                Message   = payload.ToTryteString(),
                Timestamp = Timestamp.UnixSecondsTimestamp,
                Tag       = new Tag("CHECKCHEQUE")
            });

            bundle.Finalize();
            bundle.Sign();

            await this.IotaRepository.SendTrytesAsync(bundle.Transactions, 2);

            return(bundle.Hash);
        }
Example #15
0
        public async Task TestSignatureMatchShouldReturnTrue()
        {
            var invoice = new Invoice
            {
                Hash = Hash.Empty, KvkNumber = "123456789", Payload = Encoding.UTF8.GetBytes("Somebody once told me")
            };
            var signatureScheme = Encryption.CreateSignatureScheme(Encryption.Create());

            var dltPayload = new InvoicePayload(DocumentHash.Create(invoice.Payload),
                                                signatureScheme.SignData(invoice.Payload));

            var invoiceRepository = new Mock <IInvoiceRepository>();

            invoiceRepository.Setup(i => i.LoadInvoiceInformationAsync(It.IsAny <Hash>())).ReturnsAsync(dltPayload);

            var kvkRepository = new Mock <IKvkRepository>();

            kvkRepository.Setup(k => k.GetCompanyPublicKeyAsync(It.IsAny <string>()))
            .ReturnsAsync(signatureScheme.Key.Export(CngKeyBlobFormat.EccFullPublicBlob));

            var verificator = new InvoiceVerificator(invoiceRepository.Object, kvkRepository.Object);

            Assert.IsTrue(await verificator.IsValid(invoice));
        }
Example #16
0
        public async Task GetSchemaVersionsById_Invalid_Id_Type()
        {
            // arrange
            var serializer = new IdSerializer();
            var schema     = new Schema(Guid.NewGuid(), "abc", "def");
            await SchemaRepository.AddSchemaAsync(schema);

            var schemaVersion = new SchemaVersion(
                Guid.NewGuid(), schema.Id, "abc", DocumentHash.FromSourceText("def"),
                Array.Empty <Tag>(), DateTime.UnixEpoch);
            await SchemaRepository.AddSchemaVersionAsync(schemaVersion);

            string id = serializer.Serialize("Foo", schemaVersion.Id);

            IFileContainer container = await Storage.CreateContainerAsync(
                schemaVersion.Id.ToString("N", CultureInfo.InvariantCulture));

            byte[] buffer = Encoding.UTF8.GetBytes("SourceTextAbc");
            await container.CreateFileAsync("schema.graphql", buffer, 0, buffer.Length);

            // act
            IExecutionResult result = await Executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQuery(
                    @"query($ids: [ID!]!) {
                            schemaVersionsById(ids: $ids) {
                                id
                                sourceText
                            }
                        }")
                .SetVariableValue("ids", new[] { id })
                .Create());

            // assert
            result.MatchSnapshot();
        }