public static CieStudentIdentity Decode(byte[] encodedAttribute)
        {
            try {
                // decodifica o atributo como string
                var content = Asn1Util.DecodePrintableString(encodedAttribute);
                var cieId   = new CieStudentIdentity();

                // nas primeiras 8 (oito) posições, a data de nascimento do titular, no formato ddmmaaaa;
                cieId.DataNascimento = DateTime.ParseExact(content.Substring(0, 8), "ddMMyyyy", null);

                // nas 11 (onze) posições subsequentes, o Cadastro de Pessoa Física (CPF) do titular;
                cieId.Cpf = content.Substring(8, 11);

                // nas 15 (quinze) posições subsequentes, o número da matrícula do estudante;
                cieId.Matricula = content.Substring(19, 15).TrimStart('0');

                // nas 15(quinze) posições subsequentes, o número do Registro Geral-RG do titular do atributo;
                // nas 10(dez) posições subsequentes, as siglas do órgão expedidor do RG e respectiva UF.
                cieId.RG = content.Substring(34, 15).TrimStart('0');
                if (!string.IsNullOrEmpty(cieId.RG))
                {
                    cieId.RGEmissor   = content.Substring(49, content.Length - 49 - 2).Trim();
                    cieId.RGEmissorUF = content.Substring(content.Length - 2, 2);
                }

                return(cieId);
            } catch (Exception ex) {
                throw new FormatException("Error while decoding CIE student identity fields. Invalid format.", ex);
            }
        }
Exemplo n.º 2
0
        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (saveFileDialog.FilterIndex == 2)
                {
                    byte[] data = ChangeDataFormat(currentFormat);
                    if (data != null)
                    {
                        Stream fs = saveFileDialog.OpenFile();
                        fs.Write(data, 0, data.Length);
                        currentFileName = saveFileDialog.FileName;
                        currentFileSize = fs.Length;
                        fs.Close();
                    }
                }
                else
                {
                    ChangeDataFormat(DataFormat.PEM);
                    byte[] data = Asn1Util.StringToBytes(dataStr);
                    Stream fs   = saveFileDialog.OpenFile();
                    fs.Write(data, 0, data.Length);
                    currentFileName = saveFileDialog.FileName;
                    currentFileSize = fs.Length;
                    fs.Close();
                }

                openFileDialog.FilterIndex      = saveFileDialog.FilterIndex;
                openFileDialog.FileName         = saveFileDialog.FileName;
                openFileDialog.InitialDirectory = saveFileDialog.InitialDirectory;
                ShowFileName();
            }
        }
    private static string getStringFromSubNode(Asn1Node nn)
    {
        string dataStr = null;

        if ((nn.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING && nn.ChildNodeCount > 0)
        {
            Asn1Node n = nn.GetChildNode(0);
            switch (n.Tag & Asn1Tag.TAG_MASK)
            {
            case Asn1Tag.PRINTABLE_STRING:
            case Asn1Tag.IA5_STRING:
            case Asn1Tag.UNIVERSAL_STRING:
            case Asn1Tag.VISIBLE_STRING:
            case Asn1Tag.NUMERIC_STRING:
            case Asn1Tag.UTC_TIME:
            case Asn1Tag.UTF8_STRING:
            case Asn1Tag.BMPSTRING:
            case Asn1Tag.GENERAL_STRING:
            case Asn1Tag.GENERALIZED_TIME:
            {
                if ((n.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.UTF8_STRING)
                {
                    UTF8Encoding unicode = new UTF8Encoding();
                    dataStr = unicode.GetString(n.Data);
                }
                else
                {
                    dataStr = Asn1Util.BytesToString(n.Data);
                }
            }
            break;
            }
        }
        return(dataStr);
    }
Exemplo n.º 4
0
 private void OpenFile()
 {
     pemHeader = System.IO.Path.GetFileName(openFileDialog.FileName).Replace("-", "");
     if (openFileDialog.FilterIndex == 2) // Binary file
     {
         OpenBinaryFile();
     }
     else if (openFileDialog.FilterIndex == 1) // PEM File
     {
         OpenPemFile();
     }
     else
     {
         if (Asn1Util.IsPemFormatedFile(openFileDialog.FileName))
         {
             OpenPemFile();
             openFileDialog.FilterIndex = 1;
         }
         else
         {
             OpenBinaryFile();
             openFileDialog.FilterIndex = 2;
         }
     }
     saveFileDialog.FilterIndex      = openFileDialog.FilterIndex;
     saveFileDialog.FileName         = openFileDialog.FileName;
     saveFileDialog.InitialDirectory = openFileDialog.InitialDirectory;
 }
        public static CieStudentData Decode(byte[] encodedAttribute)
        {
            try {
                // decodifica o atributo como string
                var content = Asn1Util.DecodePrintableString(encodedAttribute);
                var cieData = new CieStudentData();

                // nas primeiras 40(quarenta) posições, o nome da instituição de ensino;
                cieData.InstituicaoEnsino = content.Substring(0, 40).Trim();

                // nas 15 (quinze) posições subsequentes, o grau de escolaridade;
                cieData.GrauEscolaridade = content.Substring(40, 15).Trim();

                // nas 30 (trinta) posições subsequentes, o nome do curso
                cieData.Curso = content.Substring(55, 30).Trim();

                // nas 20 (vinte) posições subsequentes, o município da instituição
                cieData.InstituicaoEnsinoCidade = content.Substring(85, content.Length - 85 - 2).Trim();

                // nas 2 (duas) posições subsequentes, a UF domunicípio.
                cieData.InstituicaoEnsinoUF = content.Substring(content.Length - 2, 2).Trim();

                return(cieData);
            } catch (Exception ex) {
                throw new FormatException("Error while decoding CIE student data fields. Invalid format.", ex);
            }
        }
Exemplo n.º 6
0
 private void menuItemOpen_Click(object sender, System.EventArgs e)
 {
     if (openFileDialog.ShowDialog() == DialogResult.OK)
     {
         if (openFileDialog.FilterIndex == 2)
         {
             Stream stream = openFileDialog.OpenFile();
             byte[] data   = new byte[stream.Length];
             stream.Read(data, 0, data.Length);
             stream.Close();
             string hexStr = Asn1Util.ToHexString(data);
             hexStr           = Asn1Util.FormatString(hexStr, hexLineLen, 2);
             richTextBox.Text = hexStr;
             currentFormat    = DataFormat.HEX;
             SetButtons();
         }
         else
         {
             Stream stream = openFileDialog.OpenFile();
             byte[] data   = new byte[stream.Length];
             stream.Read(data, 0, data.Length);
             stream.Close();
             string dataStr = Asn1Util.BytesToString(data);
             richTextBox.Text = dataStr;
         }
     }
 }
Exemplo n.º 7
0
 public static int IntTrailingZerosCnt(int w)
 {
     return(0x20 -
            (((w & 0xffff) != 0)
                                         ? (((w & 0xff) != 0) ? ((((w & 15) != 0) ? (((w & 3) != 0) ? (((w & 1) != 0) ? 8 : 7) : (((w & 4) != 0) ? 6 : 5)) : (((w & 0x30) != 0) ? (((w & 0x10) != 0) ? 4 : 3) : (((w & 0x40) != 0) ? 2 : (((w & 0x80) != 0) ? 1 : 0)))) + 0x18) : (((((w = Asn1Util.UrShift(w, 8)) & 15) != 0) ? (((w & 3) != 0) ? (((w & 1) != 0) ? 8 : 7) : (((w & 4) != 0) ? 6 : 5)) : (((w & 0x30) != 0) ? (((w & 0x10) != 0) ? 4 : 3) : (((w & 0x40) != 0) ? 2 : (((w & 0x80) != 0) ? 1 : 0)))) + 0x10))
                                         : ((((w = Asn1Util.UrShift(w, 0x10)) & 0xff) != 0) ? ((((w & 15) != 0) ? (((w & 3) != 0) ? (((w & 1) != 0) ? 8 : 7) : (((w & 4) != 0) ? 6 : 5)) : (((w & 0x30) != 0) ? (((w & 0x10) != 0) ? 4 : 3) : (((w & 0x40) != 0) ? 2 : (((w & 0x80) != 0) ? 1 : 0)))) + 8) : ((((w = Asn1Util.UrShift(w, 8)) & 15) != 0) ? (((w & 3) != 0) ? (((w & 1) != 0) ? 8 : 7) : (((w & 4) != 0) ? 6 : 5)) : (((w & 0x30) != 0) ? (((w & 0x10) != 0) ? 4 : 3) : (((w & 0x40) != 0) ? 2 : (((w & 0x80) != 0) ? 1 : 0)))))));
 }
Exemplo n.º 8
0
        private void OpenPemFile()
        {
            Stream stream = openFileDialog.OpenFile();

            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);
            currentFileName = openFileDialog.FileName;
            currentFileSize = stream.Length;
            stream.Close();
            string dataStr = Asn1Util.BytesToString(data);

            if (Asn1Util.IsPemFormated(dataStr))
            {
                currentFormat = DataFormat.PEM;
                pemHeader     = Asn1Util.GetPemHeader(dataStr);
            }
            else if (Asn1Util.IsHexStr(dataStr))
            {
                currentFormat = DataFormat.HEX;
            }
            else
            {
                currentFormat = DataFormat.BASE64;
            }
            richTextBox.Text = dataStr;
            SetButtons();
            currentFileName = openFileDialog.FileName;
            ShowFileName();
        }
Exemplo n.º 9
0
        private static void BuildTicket(Ticket ticket, Asn1Node asn1Node)
        {
            Asn1Node childNode1 = asn1Node.GetChildNode(0).GetChildNode(0);

            for (int index = 0; (long)index < childNode1.ChildNodeCount; ++index)
            {
                Asn1Node childNode2 = childNode1.GetChildNode(index);
                switch (KerberosAuthorizeMessageBuilder.GetContextNumber(childNode2))
                {
                case 0:
                    ticket.TicketVersionNumber = (int)Asn1Util.BytesToLong(childNode2.GetChildNode(0).Data);
                    break;

                case 1:
                    ticket.Realm = childNode2.GetChildNode(0).GetDataStr(false);
                    break;

                case 2:
                    ticket.ServiceName = new PrincipalName();
                    KerberosAuthorizeMessageBuilder.BuildPrincipleName(ticket.ServiceName, childNode2);
                    break;

                case 3:
                    ticket.EncPart = new EncryptedData();
                    KerberosAuthorizeMessageBuilder.BuildEncryptedData(ticket.EncPart, childNode2);
                    break;
                }
            }
        }
Exemplo n.º 10
0
        private void CheckAlg(bool decode)
        {
            AlgorithmId algorithmId = null;

            foreach (var alg in PkiConstants.SupportedAlgorithms)
            {
                if (alg.Id.Equals(Algorithm))
                {
                    algorithmId = alg;
                    break;
                }
            }

            if ((algorithmId != null) && ((decode && (Parameters != null)) && (algorithmId.Type != null)))
            {
                try
                {
                    var buffer = new Asn1BerDecodeBuffer(((Asn1OpenType)Parameters).Value);
                    Parameters = (Asn1Type)Activator.CreateInstance(algorithmId.Type.GetType());
                    Parameters.Decode(buffer, true, 0);
                    buffer.InvokeEndElement("parameters", -1);
                }
                catch (Exception exception)
                {
                    Asn1Util.WriteStackTrace(exception, Console.Error);
                    throw ExceptionUtility.CryptographicException(Resources.Asn1TableConstraint);
                }
            }
        }
Exemplo n.º 11
0
        private static void BuildKrbApReq(KrbApReq krbApReq, Asn1Node asn1Node)
        {
            Asn1Node childNode1 = asn1Node.GetChildNode(0);

            for (int index = 0; (long)index < childNode1.ChildNodeCount; ++index)
            {
                Asn1Node childNode2 = childNode1.GetChildNode(index);
                switch (KerberosAuthorizeMessageBuilder.GetContextNumber(childNode2))
                {
                case 0:
                    krbApReq.ProtocolVersionNumber = (int)Asn1Util.BytesToLong(childNode2.GetChildNode(0).Data);
                    break;

                case 1:
                    krbApReq.MessageType = (MessageType)Asn1Util.BytesToLong(childNode2.GetChildNode(0).Data);
                    break;

                case 2:
                    krbApReq.APOptions = (APOptions)Asn1Util.BytesToLong(childNode2.GetChildNode(0).Data);
                    break;

                case 3:
                    krbApReq.Ticket = new Ticket();
                    KerberosAuthorizeMessageBuilder.BuildTicket(krbApReq.Ticket, childNode2);
                    break;

                case 4:
                    krbApReq.Authenticator = new EncryptedData();
                    KerberosAuthorizeMessageBuilder.BuildEncryptedData(krbApReq.Authenticator, childNode2);
                    break;
                }
            }
        }
Exemplo n.º 12
0
        public byte[] Encode()
        {
            // Normalize (trim, remove punctuations and diacritics (accents), pad or crop if needed)

            var normInstituicaoEnsino       = normalizeText(InstituicaoEnsino, 40);
            var normGrauEscolaridade        = normalizeText(GrauEscolaridade, 15);
            var normCurso                   = normalizeText(Curso, 30);
            var normInstituicaoEnsinoCidade = normalizeText(InstituicaoEnsinoCidade, 20);
            var normInstituicaoEnsinoUF     = normalizeText(InstituicaoEnsinoUF, 2);

            // Encode string

            var content = new StringBuilder();

            content.Append(normInstituicaoEnsino);
            content.Append(normGrauEscolaridade);
            content.Append(normCurso);

            /*
             * "As 10 (dez) posições das informações sobre órgão emissor do RG e UF referem-se
             * ao tamanho máximo, devendo ser utilizadas apenas as posições necessárias
             * ao seu armazenamento, da esquerda para a direita. O mesmo se aplica às 22
             * (vinte e duas) posições das informações sobre município e UF da instituição de
             * ensino;"
             */
            content.Append(normInstituicaoEnsinoCidade.Trim());
            content.Append(normInstituicaoEnsinoUF.Trim());

            // Encode string as PrintableString

            return(Asn1Util.DerEncodePrintableString(content.ToString()));
        }
Exemplo n.º 13
0
        public static bool IsCertInCRL(byte[] crl, X509Certificate2 cert)
        {
            var asnParser = new Asn1Parser();
            var strCRL    = Asn1Util.BytesToString(crl);

            if (Asn1Util.IsPemFormated(strCRL))
            {
                asnParser.LoadData(Asn1Util.PemToStream(strCRL));
            }
            else
            {
                asnParser.LoadData(new MemoryStream(crl));
            }

            if (7 > asnParser.RootNode.GetChildNode(0).ChildNodeCount)
            {
                return(false); // empty CRL
            }
            var revokedCertificates = asnParser.RootNode.GetChildNode(0).GetChildNode(5);

            // throw revoked certs into a list so someday we eventually cache CRLs
            var revoked = new List <long>();

            for (var i = 0; i < revokedCertificates.ChildNodeCount; i++)
            {
                revoked.Add(Asn1Util.BytesToLong(revokedCertificates.GetChildNode(i)
                                                 .GetChildNode(0)
                                                 .Data
                                                 .Reverse()
                                                 .ToArray()));
            }

            return(revoked.Contains(Asn1Util.BytesToLong(cert.GetSerialNumber())));
        }
        private AppleReceipt ParseReceipt(Asn1Node data)
        {
            if (data == null || data.ChildNodeCount != 1)
            {
                throw new InvalidPKCS7Data();
            }

            Asn1Node set = GetSetNode(data);

            var result = new AppleReceipt();
            var inApps = new List <AppleInAppPurchaseReceipt> ();

            for (int t = 0; t < set.ChildNodeCount; t++)
            {
                var node = set.GetChildNode(t);
                // Each node should contain three children.

                if (node.ChildNodeCount == 3)
                {
                    var type  = Asn1Util.BytesToLong(node.GetChildNode(0).Data);
                    var value = node.GetChildNode(2);
                    // See https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1
                    switch (type)
                    {
                    case 2:
                        result.bundleID = Encoding.UTF8.GetString(value.GetChildNode(0).Data);
                        break;

                    case 3:
                        result.appVersion = Encoding.UTF8.GetString(value.GetChildNode(0).Data);
                        break;

                    case 4:
                        result.opaque = value.Data;
                        break;

                    case 5:
                        result.hash = value.Data;
                        break;

                    case 12:
                        var dateString = Encoding.UTF8.GetString(value.GetChildNode(0).Data);
                        result.receiptCreationDate = DateTime.Parse(dateString).ToUniversalTime();
                        break;

                    case 17:
                        inApps.Add(ParseInAppReceipt(value.GetChildNode(0)));
                        break;

                    case 19:
                        result.originalApplicationVersion = Encoding.UTF8.GetString(value.GetChildNode(0).Data);
                        break;
                    }
                }
            }

            result.inAppPurchaseReceipts = inApps.ToArray();
            return(result);
        }
Exemplo n.º 15
0
        public static bool IsHexStr(string inStr)
        {
            bool retval = false;

            byte[] hex = Asn1Util.HexStrToBytes(inStr);
            retval = true;
            return(retval);
        }
Exemplo n.º 16
0
        public byte[] ChangeDataFormat(DataFormat dataFormat)
        {
            byte[] data = null;
            dataStr = richTextBox.Text;
            string msg = "";

            try
            {
                switch (currentFormat)
                {
                case DataFormat.BASE64:
                    msg  = "BASE64";
                    data = Convert.FromBase64String(dataStr);
                    break;

                case DataFormat.HEX:
                    msg  = "Hex";
                    data = Asn1Util.HexStrToBytes(dataStr);
                    break;

                case DataFormat.PEM:
                    msg       = "PEM";
                    data      = Asn1Util.PemToBytes(dataStr);
                    pemHeader = Asn1Util.GetPemHeader(dataStr);
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid " + msg + " data: " + ex.Message);
                return(data);
            }
            switch (dataFormat)
            {
            case DataFormat.BASE64:
                dataStr = Convert.ToBase64String(data);
                dataStr = Asn1Util.FormatString(dataStr, base64LineLen, 0);
                break;

            case DataFormat.HEX:
                dataStr = Asn1Util.ToHexString(data);
                dataStr = Asn1Util.FormatString(dataStr, hexLineLen, 2);
                break;

            case DataFormat.PEM:
                dataStr = Asn1Util.BytesToPem(data, pemHeader);
                break;
            }
            currentFormat    = dataFormat;
            richTextBox.Text = dataStr;
            SetButtons();
            richTextBox.Focus();
            return(data);
        }
Exemplo n.º 17
0
        private void buttonOK_Click(object sender, System.EventArgs e)
        {
            string msg     = "";
            string heading = "";

            try
            {
                switch (checker)
                {
                case DataChecker.Hex:
                    heading = "Verify Hex String";
                    isOK    = IsHexStr(textBoxNodeContent.Text);
                    break;

                case DataChecker.Oid:
                    heading = "Verify OID String";
                    isOK    = IsOidStr(textBoxNodeContent.Text);
                    break;

                case DataChecker.Roid:
                    heading = "Verify RELATIVE-OID String";
                    isOK    = IsRoidStr(textBoxNodeContent.Text);
                    break;

                default:
                    isOK = true;
                    break;
                }
                ;
                if (!textBoxTag.ReadOnly)
                {
                    isOK = IsHexStr(textBoxTag.Text);
                    byte[] xb = Asn1Util.HexStrToBytes(textBoxTag.Text);
                    if (xb.Length > 0)
                    {
                        aNode.Tag = xb[0];
                    }
                }
                int unusedBits = Convert.ToInt16(textBoxUnusedBits.Text);
            }
            catch (Exception ex)
            {
                msg += ex.Message;
                isOK = false;
            }
            if (!isOK)
            {
                MessageBox.Show(this, msg, heading);
            }
            else
            {
                this.Close();
            }
        }
        private void ParseNode(Asn1Node root)
        {
            if ((root.Tag & Asn1Tag.TAG_MASK) != Asn1Tag.SEQUENCE || root.ChildNodeCount != 3)
            {
                throw new InvalidX509Data();
            }



            // TBS cert
            TbsCertificate = root.GetChildNode(0);
            if (TbsCertificate.ChildNodeCount < 7)
            {
                throw new InvalidX509Data();
            }

            rawTBSCertificate = new byte[TbsCertificate.DataLength + 4];
            Array.Copy(root.Data, 0, rawTBSCertificate, 0, rawTBSCertificate.Length);

            // get the serial number
            Asn1Node sn = TbsCertificate.GetChildNode(1);

            if ((sn.Tag & Asn1Tag.TAG_MASK) != Asn1Tag.INTEGER)
            {
                throw new InvalidX509Data();
            }
            SerialNumber = Asn1Util.ToHexString(sn.Data);

            // get the issuer
            Issuer = new DistinguishedName(TbsCertificate.GetChildNode(3));

            // get the subject
            Subject = new DistinguishedName(TbsCertificate.GetChildNode(5));

            // get the dates
            Asn1Node validTimes = TbsCertificate.GetChildNode(4);

            if ((validTimes.Tag & Asn1Tag.TAG_MASK) != Asn1Tag.SEQUENCE || validTimes.ChildNodeCount != 2)
            {
                throw new InvalidX509Data();
            }
            ValidAfter  = ParseTime(validTimes.GetChildNode(0));
            ValidBefore = ParseTime(validTimes.GetChildNode(1));

            // is this self signed?
            SelfSigned = Subject.Equals(Issuer);

            // get the pub key
            PubKey = new RSAKey(TbsCertificate.GetChildNode(6));

            // set the tbs cert & signature data for signature verification
            Signature = root.GetChildNode(2);
        }
Exemplo n.º 19
0
        public static int GetUlongBytesCount(long value)
        {
            var number = -72057594037927936L;
            var num2   = 8;

            while ((num2 > 1) && ((value & number) == 0L))
            {
                number = Asn1Util.UrShift(number, 8);
                num2--;
            }

            return(num2);
        }
    private static int getIntegerFromSubNode(Asn1Node nn)
    {
        int retval = -1;

        if ((nn.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING && nn.ChildNodeCount > 0)
        {
            Asn1Node n = nn.GetChildNode(0);
            if ((n.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER)
            {
                retval = (int)Asn1Util.BytesToLong(n.Data);
            }
        }
        return(retval);
    }
Exemplo n.º 21
0
        private void OpenBinaryFile()
        {
            Stream stream = openFileDialog.OpenFile();

            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);
            currentFileName = openFileDialog.FileName;
            currentFileSize = stream.Length;
            stream.Close();
            string hexStr = Asn1Util.ToHexString(data);

            hexStr           = Asn1Util.FormatString(hexStr, hexLineLen, 2);
            richTextBox.Text = hexStr;
            currentFormat    = DataFormat.HEX;
            SetButtons();
            ShowFileName();
        }
Exemplo n.º 22
0
        private static void BuildPrincipleName(PrincipalName principalName, Asn1Node asn1Node)
        {
            Asn1Node childNode1 = asn1Node.GetChildNode(0);

            for (int index = 0; (long)index < childNode1.ChildNodeCount; ++index)
            {
                Asn1Node childNode2 = childNode1.GetChildNode(index);
                switch (KerberosAuthorizeMessageBuilder.GetContextNumber(childNode2))
                {
                case 0:
                    principalName.NameType = (PrincipalNameType)Asn1Util.BytesToLong(childNode2.GetChildNode(0).Data);
                    break;

                case 1:
                    principalName.NameString = new List <string>();
                    KerberosAuthorizeMessageBuilder.BuildPrincipleNameList(principalName.NameString, childNode2);
                    break;
                }
            }
        }
Exemplo n.º 23
0
        public SignerInfo(Asn1Node n)
        {
            if (n.ChildNodeCount != 5)
            {
                throw new InvalidPKCS7Data();
            }
            Asn1Node tt;

            // version
            tt = n.GetChildNode(0);
            if ((tt.Tag & Asn1Tag.TAG_MASK) != Asn1Tag.INTEGER)
            {
                throw new InvalidPKCS7Data();
            }
            Version = tt.Data[0];
            if (Version != 1 || tt.Data.Length != 1)
            {
                throw new UnsupportedSignerInfoVersion();
            }

            // get the issuer SN
            tt = n.GetChildNode(1);
            if ((tt.Tag & Asn1Tag.TAG_MASK) != Asn1Tag.SEQUENCE || tt.ChildNodeCount != 2)
            {
                throw new InvalidPKCS7Data();
            }
            tt = tt.GetChildNode(1);
            if ((tt.Tag & Asn1Tag.TAG_MASK) != Asn1Tag.INTEGER)
            {
                throw new InvalidPKCS7Data();
            }
            IssuerSerialNumber = Asn1Util.ToHexString(tt.Data);

            // get the data
            tt = n.GetChildNode(4);
            if ((tt.Tag & Asn1Tag.TAG_MASK) != Asn1Tag.OCTET_STRING)
            {
                throw new InvalidPKCS7Data();
            }
            EncryptedDigest = tt.Data;
        }
        public byte[] Encode()
        {
            // Normalize (trim, remove punctuations and diacritics (accents), pad or crop if needed)

            var normCpf         = normalizeNumber(Cpf, 11);
            var normMatricula   = normalizeNumber(Matricula, 15);
            var normRG          = normalizeNumber(RG, 15);
            var normRGEmissor   = normalizeText(RGEmissor, 8);
            var normRGEmissorUF = normalizeText(RGEmissorUF, 2);

            // Encode string

            var content = new StringBuilder();

            content.Append(DataNascimento.ToString("ddMMyyyy"));
            content.Append(normCpf);
            content.Append(normMatricula);
            content.Append(normRG);

            /**
             * "Se o número do RG não estiver disponível, não se deve preencher o campo de
             * órgão emissor e UF;"
             *
             * "As 10 (dez) posições das informações sobre órgão emissor do RG e UF referem-se
             * ao tamanho máximo, devendo ser utilizadas apenas as posições necessárias
             * ao seu armazenamento, da esquerda para a direita. O mesmo se aplica às 22
             * (vinte e duas) posições das informações sobre município e UF da instituição de
             * ensino;
             */
            if (normRG != "000000000000000")
            {
                content.Append(normRGEmissor.Trim());
                content.Append(normRGEmissorUF.Trim());
            }

            // Encode string as PrintableString

            return(Asn1Util.DerEncodePrintableString(content.ToString()));
        }
Exemplo n.º 25
0
        private void FormNodeContentEditor_Load(object sender, System.EventArgs e)
        {
            textBoxTag.Text         = String.Format("{0:X2}", aNode.Tag);
            textBoxNodeContent.Text = aNode.GetDataStr(pureHexMode);
            string msg = "";

            msg = String.Format("Tag:{0} (0x{0:X2}) : {1} \r\n"
                                + "Offset:{2,4} (0x{2:X8})\r\n"
                                + "Length:{3,4} (0x{3:X8})\r\n"
                                + "Deepness: {4}\r\n"
                                ,
                                aNode.Tag,
                                Asn1Util.GetTagName(aNode.Tag),
                                aNode.DataOffset,
                                aNode.DataLength,
                                aNode.Deepness
                                );
            if ((aNode.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.BIT_STRING)
            {
                msg += "Unused Bits: " + aNode.UnusedBits.ToString() + "\r\n";
            }
            msg          += "Path: " + aNode.Path + "\r\n";
            textBox1.Text = msg;
            if (aNode.ChildNodeCount > 0)
            {
                textBoxNodeContent.Enabled = false;
                buttonOK.Enabled           = false;
            }
            else
            {
                textBoxNodeContent.Enabled = true;
                buttonOK.Enabled           = true;
            }
            textBoxTag.ReadOnly = !enableTagEdit;
            if (textBoxNodeContent.Enabled)
            {
                textBoxNodeContent.Enabled = !enableTagEdit;
            }
        }
Exemplo n.º 26
0
        public static string CDPFromCertificateExts(X509ExtensionCollection exts)
        {
            var cdp = "";

            foreach (var ext in exts)
            {
                if (ext.Oid.Value.Equals("2.5.29.31")) // id-ce-CRLDistributionPoints
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        var asnData = new AsnEncodedData(ext.Oid, ext.RawData);
                        cdp += asnData.Format(false).Split('=')[1];
                    }
                    else
                    {
                        var strCDP = Asn1Util.BytesToString(ext.RawData);
                        strCDP = strCDP.Replace("\u0086.", "=");
                        cdp   += strCDP.Split('=')[1];
                    }
                }
            }
            return(cdp);
        }
Exemplo n.º 27
0
 private void buttonSave_Click(object sender, System.EventArgs e)
 {
     if (saveFileDialog.ShowDialog() == DialogResult.OK)
     {
         if (saveFileDialog.FilterIndex == 2)
         {
             byte[] data = ChangeDataFormat(currentFormat);
             if (data != null)
             {
                 Stream fs = saveFileDialog.OpenFile();
                 fs.Write(data, 0, data.Length);
                 fs.Close();
             }
         }
         else
         {
             string dataStr = richTextBox.Text;
             byte[] data    = Asn1Util.StringToBytes(dataStr);
             Stream fs      = saveFileDialog.OpenFile();
             fs.Write(data, 0, data.Length);
             fs.Close();
         }
     }
 }
Exemplo n.º 28
0
        private static void BuildEncryptedData(EncryptedData encryptedData, Asn1Node asn1Node)
        {
            Asn1Node childNode1 = asn1Node.GetChildNode(0);

            for (int index = 0; (long)index < childNode1.ChildNodeCount; ++index)
            {
                Asn1Node childNode2 = childNode1.GetChildNode(index);
                switch (KerberosAuthorizeMessageBuilder.GetContextNumber(childNode2))
                {
                case 0:
                    encryptedData.EncryptionType = (EncryptionType)Asn1Util.BytesToLong(childNode2.GetChildNode(0).Data);
                    break;

                case 1:
                    encryptedData.KeyVersionNumber = new uint?((uint)Asn1Util.BytesToLong(childNode2.GetChildNode(0).Data));
                    break;

                case 2:
                    encryptedData.Cipher = new byte[childNode2.GetChildNode(0).DataLength];
                    Buffer.BlockCopy((Array)childNode2.GetChildNode(0).Data, 0, (Array)encryptedData.Cipher, 0, encryptedData.Cipher.Length);
                    break;
                }
            }
        }
        public DistinguishedName(Asn1Node n)
        {
            /* Name:
             * SET
             *   SEQ (attr)
             *     Object Identifier
             *     Printable String || UTF8String
             */
            if (n.MaskedTag == Asn1Tag.SEQUENCE)
            {
                for (int i = 0; i < n.ChildNodeCount; i++)
                {
                    Asn1Node tt = n.GetChildNode(i);
                    if (tt.MaskedTag != Asn1Tag.SET || tt.ChildNodeCount != 1)
                    {
                        throw new InvalidX509Data();
                    }

                    tt = tt.GetChildNode(0);
                    if (tt.MaskedTag != Asn1Tag.SEQUENCE || tt.ChildNodeCount != 2)
                    {
                        throw new InvalidX509Data();
                    }

                    Asn1Node oi  = tt.GetChildNode(0);
                    Asn1Node txt = tt.GetChildNode(1);

                    if (oi.MaskedTag != Asn1Tag.OBJECT_IDENTIFIER ||
                        !(
                            (txt.MaskedTag == Asn1Tag.PRINTABLE_STRING) ||
                            (txt.MaskedTag == Asn1Tag.UTF8_STRING) ||
                            (txt.MaskedTag == Asn1Tag.IA5_STRING)))
                    {
                        throw new InvalidX509Data();
                    }
                    var    xoid   = new LipingShare.LCLib.Asn1Processor.Oid();
                    string oiName = xoid.Decode(oi.Data);
                    var    enc    = new System.Text.UTF8Encoding();

                    switch (oiName)
                    {
                    case "2.5.4.6":                     // countryName
                        Country = enc.GetString(txt.Data);
                        break;

                    case "2.5.4.10":                     // organizationName
                        Organization = enc.GetString(txt.Data);
                        break;

                    case "2.5.4.11":                     // organizationalUnit
                        OrganizationalUnit = enc.GetString(txt.Data);
                        break;

                    case "2.5.4.3":                     // commonName
                        CommonName = enc.GetString(txt.Data);
                        break;

                    case "2.5.4.5":                     // serial number
                        SerialNumber = Asn1Util.ToHexString(txt.Data);
                        break;

                    case "2.5.4.46":                     // dnq
                        Dnq = enc.GetString(txt.Data);
                        break;

                    case "2.5.4.8":                     // state
                        State = enc.GetString(txt.Data);
                        break;
                    }
                }
            }
        }
Exemplo n.º 30
0
        static public bool EditNode(IWin32Window parent, Asn1Node aNode, bool enableTagEdit, bool pureHexMode)
        {
            byte[] val;
            byte[] data;
            FormNodeContentEditor ed = new FormNodeContentEditor();

            ed.aNode = aNode;
            MemoryStream ms = new MemoryStream();

            ed.checker       = FormNodeContentEditor.DataChecker.None;
            ed.enableTagEdit = enableTagEdit;
            ed.pureHexMode   = pureHexMode;
            if (
                ((aNode.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.BIT_STRING) &&
                (aNode.ChildNodeCount < 1))
            {
                ed.panelUnusedBits.Visible = true;
                ed.textBoxUnusedBits.Text  = aNode.UnusedBits.ToString();
            }
            else
            {
                ed.panelUnusedBits.Visible = false;
            }
            if (pureHexMode)
            {
                ed.checker = DataChecker.Hex;
                ed.ShowDialog(parent);
                if (!ed.isOK)
                {
                    return(false);
                }
                data       = Asn1Util.HexStrToBytes(ed.GetValueStr());
                aNode.Data = data;
            }
            else
            {
                byte[] oidVal;
                switch (aNode.Tag)
                {
                case Asn1Tag.OBJECT_IDENTIFIER:
                    ed.checker = DataChecker.Oid;
                    ed.ShowDialog(parent);
                    if (!ed.isOK)
                    {
                        return(false);
                    }
                    Oid xoid = new Oid();
                    xoid.Encode(ms, ed.GetValueStr());
                    ms.Position = 0;
                    oidVal      = new byte[ms.Length];
                    ms.Read(oidVal, 0, (int)ms.Length);
                    ms.Close();
                    aNode.Data = oidVal;
                    break;

                case Asn1Tag.RELATIVE_OID:
                    ed.checker = DataChecker.Roid;
                    ed.ShowDialog(parent);
                    if (!ed.isOK)
                    {
                        return(false);
                    }
                    RelativeOid roid = new RelativeOid();
                    roid.Encode(ms, ed.GetValueStr());
                    ms.Position = 0;
                    oidVal      = new byte[ms.Length];
                    ms.Read(oidVal, 0, (int)ms.Length);
                    ms.Close();
                    aNode.Data = oidVal;
                    break;

                case Asn1Tag.PRINTABLE_STRING:
                case Asn1Tag.IA5_STRING:
                case Asn1Tag.UNIVERSAL_STRING:
                case Asn1Tag.VISIBLE_STRING:
                case Asn1Tag.NUMERIC_STRING:
                case Asn1Tag.UTC_TIME:
                case Asn1Tag.GENERAL_STRING:
                case Asn1Tag.GENERALIZED_TIME:
                    ed.ShowDialog(parent);
                    if (!ed.isOK)
                    {
                        return(false);
                    }
                    val        = Asn1Util.StringToBytes(ed.GetValueStr());
                    aNode.Data = val;
                    break;

                case Asn1Tag.UTF8_STRING:
                    ed.ShowDialog(parent);
                    if (!ed.isOK)
                    {
                        return(false);
                    }
                    UTF8Encoding u8 = new UTF8Encoding(false);
                    val        = u8.GetBytes(ed.GetValueStr());
                    aNode.Data = val;
                    break;

                case Asn1Tag.BMPSTRING:
                    ed.ShowDialog(parent);
                    if (!ed.isOK)
                    {
                        return(false);
                    }
                    //byte[] tmpval = Asn1Util.StringToBytes(ed.GetValueStr());
                    byte[] tmpval = Encoding.BigEndianUnicode.GetBytes(ed.GetValueStr());
                    val = new byte[tmpval.Length * 2];
                    for (int i = 0; i < tmpval.Length; i++)
                    {
                        val[i * 2]     = 0;
                        val[i * 2 + 1] = tmpval[i];
                    }
                    aNode.Data = val;
                    break;

                case Asn1Tag.INTEGER:
                case Asn1Tag.BIT_STRING:
                    ed.checker = DataChecker.Hex;
                    ed.ShowDialog(parent);
                    if (!ed.isOK)
                    {
                        return(false);
                    }
                    aNode.UnusedBits = (byte)(Convert.ToUInt16(ed.textBoxUnusedBits.Text) % 8);
                    data             = Asn1Util.HexStrToBytes(ed.GetValueStr());
                    aNode.Data       = data;
                    break;

                default:
                    if ((aNode.Tag & Asn1Tag.TAG_MASK) == 6)     // Visible string for certificate
                    {
                        ed.ShowDialog(parent);
                        if (!ed.isOK)
                        {
                            return(false);
                        }
                        val        = Asn1Util.StringToBytes(ed.GetValueStr());
                        aNode.Data = val;
                    }
                    else
                    {
                        ed.checker = DataChecker.Hex;
                        ed.ShowDialog(parent);
                        if (!ed.isOK)
                        {
                            return(false);
                        }
                        data       = Asn1Util.HexStrToBytes(ed.GetValueStr());
                        aNode.Data = data;
                    }
                    break;
                }
                ;
            }
            return(true);
        }