Как решить ошибку «Фатальный сигнал 6 (SIGABRT)» на Xamarin? - PullRequest
0 голосов
/ 13 сентября 2018

Прежде всего, мой родной язык - испанский, поэтому я хотел бы извиниться, если напишу некоторые (или все) предложения.

Я занимаюсь разработкой приложения на Xamarin.android, которое использует цифровую подписьв документе PDF и в последнее время у класса, который я использую для печати подписи, было много проблем.Это проблема, с которой я сталкиваюсь сейчас:

Фатальный сигнал 6 (SIGABRT), код -6 в тид 30481 (al.FirmaDigital)

Я симпатичнаяЯ новичок в Xamarin, и я понятия не имею, почему это происходит.Я занимался расследованием и обнаружил, что эта ошибка возникает, когда программа посылает сигнал на прерывание процесса.Но я не знаю, что вызывает эту ошибку.

Я только знаю, что эта ошибка появляется, когда она запускает строку 175 кода: objSignedCms.ComputeSignature(objCmsSigner, false); (я использовал try / catch, но он не выбрасываетлюбое исключение. Приложение просто закрывается, и logcat отправляет эту ошибку).

Я предоставил вам класс, который я использую для подписи документа, чтобы вы могли увидеть, можете ли вы мне помочь.

Заранее спасибо!

using System;
using System.Collections.Generic;
using System.Linq;


using System.Collections;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Org.BouncyCastle.X509;
using SysX509 = System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;

namespace FirmaDigital.FirmaDigital
{
    public static class PDF
    {
        /// <summary>
        /// Firma un documento
        /// </summary>
        /// <param name="Source">Documento origen</param>
        /// <param name="Target">Documento destino</param>
        /// <param name="Certificate">Certificado a utilizar</param>
        /// <param name="Reason">Razón de la firma</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param>
        /// FormatPlace. Posibles valores para Lugar de la firma:
        /// A4TL: A4 normal, arriba a la izquierda
        /// A4TR: A4 normal, arriba a la derecha
        /// A4BL: A4 normal, abajo a la izquierda
        /// A4BR: A4 normal, abajo a la derecha
        /// A4aTL: A4 apaisado, arriba a la izquierda
        /// A4aTR: A4 apaisado, arriba a la derecha
        /// A4aBL: A4 apaisado, abajo a la izquierda
        /// A4aBR: A4 apaisado, abajo a la derecha

        public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, string FormatPlace, string TSA)
        {
            X509CertificateParser objCP = new X509CertificateParser();
            X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

            PdfReader objReader = new PdfReader(Source);
            PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0');
            PdfSignatureAppearance objSA = objStamper.SignatureAppearance;

            int LastPage = objReader.NumberOfPages;

            if (AddVisibleSign)
            {
                switch (FormatPlace)
                {
                    case "A4TL":
                        objSA.SetVisibleSignature(new Rectangle(50, 750, 300, 780), LastPage, null);
                        break;
                    case "A4TR":
                        objSA.SetVisibleSignature(new Rectangle(350, 750, 600, 780), LastPage, null);
                        break;
                    case "A4BL":
                        objSA.SetVisibleSignature(new Rectangle(50, 50, 300, 80), LastPage, null);
                        break;
                    case "A4BR":
                        objSA.SetVisibleSignature(new Rectangle(350, 50, 600, 80), LastPage, null);
                        break;
                    case "A4aTL":
                        objSA.SetVisibleSignature(new Rectangle(50, 570, 300, 600), LastPage, null);
                        break;
                    case "A4aTR":
                        objSA.SetVisibleSignature(new Rectangle(530, 570, 780, 600), LastPage, null);
                        break;
                    case "A4aBL":
                        objSA.SetVisibleSignature(new Rectangle(50, 20, 300, 50), LastPage, null);
                        break;
                    case "A4aBR":
                        objSA.SetVisibleSignature(new Rectangle(530, 20, 780, 50), LastPage, null);
                        break;
                }
            }

            objSA.SignDate = DateTime.Now;
            objSA.Certificate = objChain[0];
            objSA.Reason = Reason;
            objSA.Location = Location;
            objSA.Acro6Layers = true;
            objSA.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
            objSignature.Date = new PdfDate(objSA.SignDate);
            objSignature.Name = "Nombre de Prueba";
            if (objSA.Reason != null)
                objSignature.Reason = objSA.Reason;
            if (objSA.Location != null)
                objSignature.Location = objSA.Location;
            objSA.CryptoDictionary = objSignature;
            int intCSize = 4000;
            Hashtable objTable = new Hashtable();
            objTable[PdfName.CONTENTS] = intCSize * 2 + 2;

            var dict = HashtableToDictionary<PdfName, int>(objTable);

            objSA.PreClose(dict);

            HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

            Stream objStream = objSA.GetRangeStream();
            int intRead = 0;
            byte[] bytBuffer = new byte[8192];
            while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
                objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
            objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

            byte[] bytPK = SignMsg(objSHA1.Hash, Certificate, false, Source, TSA);
            byte[] bytOut = new byte[intCSize];

            PdfDictionary objDict = new PdfDictionary();

            Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

            objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
            objSA.Close(objDict);
        }

        public static Dictionary<K, V> HashtableToDictionary<K, V>(Hashtable table)
        {
            return table
              .Cast<DictionaryEntry>()
              .ToDictionary(kvp => (K)kvp.Key, kvp => (V)kvp.Value);
        }

        /// <summary>
        /// Crea la firma CMS/PKCS #7
        /// </summary>
        private static byte[] SignMsg(byte[] Message, SysX509.X509Certificate2 SignerCertificate, bool Detached, string Source, string TSA)
        {
            try
            {
                //Creamos el contenedor
                ContentInfo contentInfo = new ContentInfo(Message);

                //Instanciamos el objeto SignedCms con el contenedor
                SignedCms objSignedCms = new SignedCms(contentInfo, Detached);

                //Creamos el "firmante"
                CmsSigner objCmsSigner = new CmsSigner(SignerCertificate);

                // Include the following line if the top certificate in the
                // smartcard is not in the trusted list.
                objCmsSigner.IncludeOption = SysX509.X509IncludeOption.EndCertOnly;
                if (TSA != "S/TSA"){
                    objCmsSigner.UnsignedAttributes.Add(timeData);
                }

                //  Sign the CMS/PKCS #7 message. The second argument is needed to ask for the pin.
                objSignedCms.ComputeSignature(objCmsSigner, false);

                //Encodeamos el mensaje CMS/PKCS #7
                return objSignedCms.Encode();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

[Редактировать]

Я приведу здесь последние 10 строк журнала:

09-13 13:54:55.788 D/Mono    (18211): Assembly Ref addref System.Security.Cryptography.Algorithms[0x9c119fa0] -> mscorlib[0xb46d4580]: 18
Loaded assembly: System.Security.Cryptography.Algorithms.dll [External]
09-13 13:54:55.864 D/Mono    (18211): Assembly Ref addref 
System.Security.Cryptography.Algorithms[0x9c119fa0] -> System.Core[0xb477c4c0]: 5
09-13 13:54:55.881 D/Mono    (18211): Assembly Ref addref System.Memory[0xb46d4b20] -> System.Runtime.CompilerServices.Unsafe[0xb46d4be0]: 2
09-13 13:54:55.882 D/Mono    (18211): Unloading image System.Runtime.dll [0x9e0e8300].
09-13 13:54:55.883 D/Mono    (18211): Image addref System.Runtime[0x9c119e80] -> System.Runtime.dll[0xb4447000]: 5
09-13 13:54:55.883 D/Mono    (18211): Config attempting to parse: 'System.Runtime.dll.config'.
09-13 13:54:55.883 D/Mono    (18211): Config attempting to parse: '/usr/local/etc/mono/assemblies/System.Runtime/System.Runtime.config'.
09-13 13:54:55.883 D/Mono    (18211): Assembly Ref addref System.Runtime.CompilerServices.Unsafe[0xb46d4be0] -> System.Runtime[0xb46d4dc0]: 3
09-13 13:54:55.887 F/        (18211): * Assertion at /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mono/mini/method-to-ir.c:13643, condition `ins->opcode >= MONO_CEE_LAST' not met
09-13 13:54:55.887 F/libc    (18211): Fatal signal 6 (SIGABRT), code -6 in tid 18211 (al.FirmaDigital)

[Редактировать 2]

Это logcat после выполнения того, что @SushiHangover сказал мне сделать:

09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE not know revents:0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE p 0 poll events 1 revents 0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE p 1 poll events 1 revents 0
09-14 11:33:04.450  Hipstreet 7DTB40    Error   23079   libc    Fatal signal 6 (SIGABRT), code -6 in tid 23079 (al.FirmaDigital)
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE aed_main_fork_worker: generator 0xb6437148, worker 0xbec4c928, recv_fd 0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE not know revents:0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE $===AEE===AEE===AEE===$
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE p 2 poll events 1 revents 1
09-14 11:33:04.449  Hipstreet 7DTB40    Error   23079       * Assertion at /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mono/mini/method-to-ir.c:13643, condition `ins->opcode >= MONO_CEE_LAST' not met
09-14 11:33:04.443  Hipstreet 7DTB40    Debug   23079   Mono    Assembly Ref addref System.Runtime.CompilerServices.Unsafe[0xb46d4be0] -> System.Runtime[0xb46d4dc0]: 3
09-14 11:33:04.443  Hipstreet 7DTB40    Debug   23079   Mono    Config attempting to parse: '/usr/local/etc/mono/assemblies/System.Runtime/System.Runtime.config'.
09-14 11:33:04.442  Hipstreet 7DTB40    Debug   23079   Mono    Config attempting to parse: 'System.Runtime.dll.config'.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...