Esempio n. 1
0
        /**
         * Parse the ServerCertificate message.
         *
         * @param inStr The stream where to parse from.
         * @return A Certificate object with the certs, the server has sended.
         * @throws IOException If something goes wrong during parsing.
         */
        internal static Certificate Parse(
            Stream inStr)
        {
            int left = TlsUtilities.ReadUint24(inStr);

            if (left == 0)
            {
                return(EmptyChain);
            }
            IList tmp = Platform.CreateArrayList();

            while (left > 0)
            {
                int size = TlsUtilities.ReadUint24(inStr);
                left -= 3 + size;
                byte[] buf = new byte[size];
                TlsUtilities.ReadFully(buf, inStr);
                MemoryStream bis = new MemoryStream(buf, false);
                Asn1Object   o   = Asn1Object.FromStream(bis);
                tmp.Add(X509CertificateStructure.GetInstance(o));
                if (bis.Position < bis.Length)
                {
                    throw new ArgumentException("Sorry, there is garbage data left after the certificate");
                }
            }
            X509CertificateStructure[] certs = new X509CertificateStructure[tmp.Count];
            for (int i = 0; i < tmp.Count; ++i)
            {
                certs[i] = (X509CertificateStructure)tmp[i];
            }
            return(new Certificate(certs));
        }
        public static List <string> getHashPoliticaEspecifica(string PolicyUriSource, string PolicyIdentifier, string PolicyDigestAlgorithm, string FileName)
        {
            Stream St;

            try
            {
                St = Helper.FileHelper.MSReadFileURL(PolicyUriSource);
            }
            catch (Exception ex)
            {
                // FileStream File = Helper.FileHelper.FSReadFile(System.AppDomain.CurrentDomain.BaseDirectory + FileName);
                // St = File;
                St = new MemoryStream(Properties.Resources.PA_AD_RT_v2_3);
            }
            DerSequence privKeyObj = (DerSequence)Asn1Object.FromStream(St);

            var           objCollection = privKeyObj.GetEnumerator();
            List <String> oRetorno      = new List <string>();

            while (objCollection.MoveNext())
            {
                string texto = objCollection.Current.ToString();
                oRetorno.Add(texto);
            }
            St.Close();
            return(oRetorno);
        }
 public static AsymmetricKeyParameter CreateKey(
     Stream inStr)
 {
     return(CreateKey(
                SubjectPublicKeyInfo.GetInstance(
                    Asn1Object.FromStream(inStr))));
 }
 private static AttributeCertificate GetObject(Stream input)
 {
     try
     {
         return(AttributeCertificate.GetInstance(Asn1Object.FromStream(input)));
     }
     catch (IOException e)
     {
         throw e;
     }
     catch (Exception e)
     {
         throw new IOException("exception decoding certificate structure", e);
     }
 }
Esempio n. 5
0
        public static VipNetContainer LoadFromStream(Stream strm)
        {
            using (var reader = new BinaryReader(strm)) {
                var type = Encoding.ASCII.GetString(reader.ReadBytes(4));
                if (type != "ITCS" && type != "PKEY" && type != "_CCK" && type != "_LCK")
                {
                    throw new NotSupportedException($"Неподдерживаемый тип контейнера: {type}.");
                }

                var version = reader.ReadUInt32();
                if (LoWord(version) > 0xFF || HiWord(version) > 2)
                {
                    throw new NotSupportedException($"Неподдерживаемая версия контейнера: {version}.");
                }

                var headerSize = reader.ReadInt32();
                var header     = new byte[headerSize];
                if (headerSize > 0)
                {
                    header = reader.ReadBytes(headerSize);
                }

                var entries = new List <VipNetContainerEntry>();
                while (strm.Position < strm.Length)
                {
                    var entrySize     = reader.ReadInt32();
                    var entryStartPos = strm.Position;
                    var entrySeq      = (Asn1Sequence)Asn1Object.FromStream(strm);
                    var keySize       = reader.ReadInt32();
                    if (keySize < 0 || strm.Position + keySize - entryStartPos != entrySize)
                    {
                        throw new InvalidOperationException($"Некорректный размер блока с ключом: {keySize}.");
                    }
                    var key = reader.ReadBytes(keySize);
                    entries.Add(new VipNetContainerEntry(entrySeq, key));
                }

                if (entries.Count == 0)
                {
                    throw new InvalidOperationException("Контейнер не содержит записей.");
                }

                return(new VipNetContainer(type, version, headerSize, header, entries));
            }
        }
Esempio n. 6
0
 private static AttributeCertificate GetObject(Stream input)
 {
     //IL_000f: Expected O, but got Unknown
     //IL_0018: Unknown result type (might be due to invalid IL or missing references)
     try
     {
         return(AttributeCertificate.GetInstance(Asn1Object.FromStream(input)));
     }
     catch (IOException val)
     {
         IOException val2 = val;
         throw val2;
     }
     catch (global::System.Exception ex)
     {
         throw new IOException("exception decoding certificate structure", ex);
     }
 }
        private static AttributeCertificate GetObject(Stream input)
        {
            AttributeCertificate instance;

            try
            {
                instance = AttributeCertificate.GetInstance(Asn1Object.FromStream(input));
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (Exception innerException)
            {
                throw new IOException("exception decoding certificate structure", innerException);
            }
            return(instance);
        }
        static void Main(string[] args)
        {
            const string pubkey = @"...";
            const string prikey = @"...";

            var publickey  = Convert.FromBase64String(pubkey);
            var privatekey = Convert.FromBase64String(prikey);

            var asnprivate = Asn1Object.FromStream(new MemoryStream(privatekey));
            var privStruct = new RsaPrivateKeyStructure((Asn1Sequence)asnprivate);

            RsaKeyParameters privateAsymmetricKey = new RsaKeyParameters(true, privStruct.Modulus, privStruct.PrivateExponent);
            RsaKeyParameters publicAsymmetricKey  = (RsaKeyParameters)PublicKeyFactory.CreateKey(publickey);

            var inputBytes = Encoding.UTF8.GetBytes("the message");

            Console.WriteLine("--- Message: ----");
            Console.WriteLine(Encoding.UTF8.GetString(inputBytes));

            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(true, publicAsymmetricKey);
            var cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputBytes.Length);

            Console.WriteLine("--- Enc utf8: ----");
            Console.WriteLine(Encoding.UTF8.GetString(cipheredBytes));

            Console.WriteLine("--- Enc Base64: ----");
            Console.WriteLine(Convert.ToBase64String(cipheredBytes));

            cipher.Init(false, privateAsymmetricKey);
            var deciphered = cipher.ProcessBlock(cipheredBytes, 0, cipheredBytes.Length);

            Console.WriteLine("--- Dec: ----");
            Console.WriteLine(Encoding.UTF8.GetString(deciphered));
            Console.ReadLine();
        }
Esempio n. 9
0
        /**
         * Parse the ServerCertificate message.
         *
         * @param inStr The stream where to parse from.
         * @return A Certificate object with the certs, the server has sended.
         * @throws IOException If something goes wrong during parsing.
         */
        internal static Certificate Parse(
            Stream inStr)
        {
            X509CertificateStructure[] certs;
            int       left = TlsUtilities.ReadUint24(inStr);
            ArrayList tmp  = new ArrayList();

            while (left > 0)
            {
                int size = TlsUtilities.ReadUint24(inStr);
                left -= 3 + size;
                byte[] buf = new byte[size];
                TlsUtilities.ReadFully(buf, inStr);
                MemoryStream bis = new MemoryStream(buf, false);
                Asn1Object   o   = Asn1Object.FromStream(bis);
                tmp.Add(X509CertificateStructure.GetInstance(o));
                if (bis.Position < bis.Length)
                {
                    throw new ArgumentException("Sorry, there is garbage data left after the certificate");
                }
            }
            certs = (X509CertificateStructure[])tmp.ToArray(typeof(X509CertificateStructure));
            return(new Certificate(certs));
        }
Esempio n. 10
0
        public void Load(
            Stream input,
            char[]      password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         wrongPkcs12Zero = false;

            if (password != null && bag.MacData != null) // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();
            unmarkedKeyEntry = null;

            IList certBags = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    byte[] octets = null;
                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        octets = ((Asn1OctetString)ci.Content).GetOctets();
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        if (password != null)
                        {
                            EncryptedData d = EncryptedData.GetInstance(ci.Content);
                            octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                  password, wrongPkcs12Zero, d.Content.GetOctets());
                        }
                    }
                    else
                    {
                        // TODO Other data types
                    }

                    if (octets != null)
                    {
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                certBags.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue),
                                                        b.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes);
                            }
                            else
                            {
                                // TODO Other bag types
                            }
                        }
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in certBags)
            {
                CertBag         certBag = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets  = ((Asn1OctetString)certBag.CertValue).GetOctets();
                X509Certificate cert    = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                        Asn1Set             attrSet = Asn1Set.GetInstance(sq[1]);

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = certEntry;

                if (unmarkedKeyEntry != null)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = certEntry;
                        keys[name]     = unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = certEntry;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = certEntry;
                    }
                }
            }
        }
Esempio n. 11
0
 public static AsymmetricKeyParameter CreateKey(Stream inStr)
 {
     return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(Asn1Object.FromStream(inStr))));
 }
Esempio n. 12
0
 public Pkcs10CertificationRequest(
     Stream input)
     : base((Asn1Sequence)Asn1Object.FromStream(input))
 {
 }
        static void Main(string[] args)
        {
            const string pubkey = @"MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAuQhcZKNnIC2bvJhI5Yzq
    oH9uGAHuiAt9bOXdIrsaeEwsIUMuyNfXkLozwlcJb0YLgqhpP3gNLb58WCb1AvkV
    ZHgzLQbay93HwmBiEPW6LZIKGsHwh1awBmJpeWhU8h3oNP+KpNq44H+jAeM9G9En
    W0y7+AUbe3pnisOWVZHmM72A2mLq1piCOjmvjegzgB8/rU7ZkRrNadeFO7DBP0Ew
    6eElS3iXfFHJmbK+L5lL0pFxvUMRfGVC33NQkuSoWiQJZsYyUgIk6WSOQm3t5fw6
    VESMTfd1xKlaBGp7IrWksthEF+XAu5ziAcSdjBwJLEFzJ2830cQ4GhFS3JtU/Iao
    6MbJkUuaHoI3Xx9C7d6RiKbK1uZrOHjyVsUhqpYwyAUdrViraj0pybxbE2GwbRC4
    /NyHuPKG3gBULiGYbl8wwlhl71nRVdkPQtGw36kmGWHRk3ERM6JgLWsDZjED4ak2
    Na6VzIvnqVs0HROl/4Rd4rHZvl9t39tfVBtofEkD4C0B5BdgW/B2XQM7Fd4celn3
    q/+FKmvaVydoFGG0s4YZL6hsqOISfhdT10jGrwNKe+zupnrXZO66mtX8rvPtY4x2
    WXcHrbp1cgSr+2r8Mteh8Eff+6rqArU1i1ezDm3SrKs1WMFKu1hRKDYudfOaB/L7
    gvEvD+lUE9qnjlYUBGSXKMUCAwEAAQ==";
            const string prikey = @"MIIJKQIBAAKCAgEAuQhcZKNnIC2bvJhI5YzqoH9uGAHuiAt9bOXdIrsaeEwsIUMu
    yNfXkLozwlcJb0YLgqhpP3gNLb58WCb1AvkVZHgzLQbay93HwmBiEPW6LZIKGsHw
    h1awBmJpeWhU8h3oNP+KpNq44H+jAeM9G9EnW0y7+AUbe3pnisOWVZHmM72A2mLq
    1piCOjmvjegzgB8/rU7ZkRrNadeFO7DBP0Ew6eElS3iXfFHJmbK+L5lL0pFxvUMR
    fGVC33NQkuSoWiQJZsYyUgIk6WSOQm3t5fw6VESMTfd1xKlaBGp7IrWksthEF+XA
    u5ziAcSdjBwJLEFzJ2830cQ4GhFS3JtU/Iao6MbJkUuaHoI3Xx9C7d6RiKbK1uZr
    OHjyVsUhqpYwyAUdrViraj0pybxbE2GwbRC4/NyHuPKG3gBULiGYbl8wwlhl71nR
    VdkPQtGw36kmGWHRk3ERM6JgLWsDZjED4ak2Na6VzIvnqVs0HROl/4Rd4rHZvl9t
    39tfVBtofEkD4C0B5BdgW/B2XQM7Fd4celn3q/+FKmvaVydoFGG0s4YZL6hsqOIS
    fhdT10jGrwNKe+zupnrXZO66mtX8rvPtY4x2WXcHrbp1cgSr+2r8Mteh8Eff+6rq
    ArU1i1ezDm3SrKs1WMFKu1hRKDYudfOaB/L7gvEvD+lUE9qnjlYUBGSXKMUCAwEA
    AQKCAgBdi6GSa54egZBjx6XLD/Qq0mHpl0ht1UlC/e9PuMJIIVKKOnnzplPgYpL6
    ZKBrdkEpfFVBdkNLZitdMczbBOzQz4gn8ng5a1WrqqjJpEHM+jFLl9MvyR7TC3wB
    mkKf6YjVCoCgmcewEDdsI+NoJdS87s11NbfQNHEWkY12k32LmPoE7s+FULM+Fp3v
    o34t/x5lUyDhoGhLY1+Dbvg0L5Q4GdCOGFiVzI+cueY3EExqF4gmRDsZ5ePqLlWE
    /j8y21c5c2hLV7Qrnt/hK8yDYoJmygUZAcuzcl8FLoQ0ZxruJDJA1rIa59THSgzQ
    offtPOWoAS16SraGT03SJGHSDY5kzCZkEx7MJv8dn5hydLzJ5bzbiJ1rheNdZNzp
    yjT/X61jtjQnX2gmev/bN4Q54qqc2YbVfh7BwvyBAL2c7oHxFP3xmJgCZt6OS6S1
    HUR8/QDrcLJVwNNsTL7uvToSiRBrTWjFUuc0k6m2h8takD9sONHH7+hZu9TEL2a9
    /bjowuPIrmrrYbgYN9DospmJZrDfEby79+t8aDsycAzK3uHIn1GfdhDVNFayJjPR
    VP593GRhY/B6CwM7lCFxzTqOU4e9ITLpkLV//CpK77g9xGVUGQk1X0NieBbzUtHY
    DzSnsC2k9dOwootlrMvJYTUv3+BdzG3jEleCP6qoYxd43iKtAQKCAQEA61HUaI9v
    dlxIK/oG5RWYSFZHCc0oOeTMw1MJ+rOQ5c3RUbIrn/fj+i2zGknt5b+5LH6i5jXw
    YEY4o1bJJCjT51AhdV6HxlljAfUeX98T2uaVVZxQJio/uqJg9N63s9bIhdq94NJg
    MWIRKsip76gV76qXhFRyRXfEjQvy9PZHC/A2Qs+azrcD97jnzf/XzOpnot+W8Ul1
    b2fOHk0RqdQs2ZJ/ajZrVnK40WX3AZlSVYZuwPKaW90BtifxjZUESGAIsAzh7Eve
    tX3lgpsDP7JaBZZYdP6AzDEkjPKDFH4P/KmEHl9eWHfcuVu+T+Er3xFe94PUbW9P
    f52XbXox4OrYQQKCAQEAyUsvez7ri7/bXcUcrfjHHQuSs5Mw+R0yyg77yT8o6nkB
    6cDWT4BmIc/+IoTIAXySOczftVxjL1bXrsYQSYLkoTKOuYAQRi0zN3/alTFW2A3P
    7ec8hANTuxAXCwuNd1jjEtVaOEuNdVYg4gsEmHEvejJsBIDJkT/VzbYJVB+Y1k3J
    Sd0R6h0KAROsJ4lefK9kh7MzN8B/SUDeuiaPkxBzrMzGFeDifieWiyxWTqoGPHUV
    eO5NfJSYHfn7VmEvB3cNmqcc56i9Thie6a0iDUbKmkwPfDmEABu3ex9HctpnYOCk
    gzR/huwPiWP1IGYznilwIOvt/mdyiAPmGQn6xakPhQKCAQEAlDfLgTxvKW8Aqmpm
    c16Bt3ZYckz9fFGnw5OHIph9uLFFmZ6OqciamNa2C+Xq6R40hVkSQ8xPpmQ0gnVE
    ZfktV3H6URIElSNyICaDRkGdIPDBuNWnChLsZyKlzTaHIMg1L1JS7Mu1eQVa6MbR
    erk1b+rUWq5R931zmJ+hHTgOEe/wTW60BGX0ItEdeHwgMdqnAkiwqzPouw34Hs/O
    Q1j4EuaaSI0UWLQTwxjlVuV6nZH6Kp/kJ95xmIlaNSJaOzf54OGMX6h+E3TD3drD
    VhiBaSmEd9RhzbtaWUja1Up9yVgAdpz9MN32ce3eVjPuzScE2QP5BiDpQulBGtyv
    lAp3wQKCAQAyf2sc9w7uUyY8Iuvr9QI2liWqaR2bESkhqZqexPqFv++r7ZWWAjcc
    +mndzQPD47VnTK8+dzvmr1mSXdvOJUkn62AEx0zN3h8AKFH0pZkMwIJOQ3laAN+r
    iQDO44oMy77DhcSJZOLK8d1z96GigJqRhD627nwitSn03lr+wKJ9+KurnQsWeUx+
    Mqo4jOyoSPPmWx1ZOjB0dxKpDm1sTm9GhWSYLn+DeHj61xebymmgFxtY6CeGPlzf
    AEx+QgkjTUmbZ5sHvrwm8GRFaQqm3ACNrtEfr+oegNWJzLIG7SWMFy8OP0hS17ua
    Evp2s0z1u52GlMlyzg7ccmXyGB/SIHRlAoIBAQCqF/P8D+T8uEiiQron39NAGgSM
    FFyi1uj3IeDrDPgdsLT5TtpFOnHpUMjhxVEhdIQm2K4MH44/aBW40CgS+OGHclay
    SzwdtfHyPuK1H8TwaJqgA5NYu/xTyiR8QqRE+qwwh5wMH4f4ErhKglnQJVNxHeo7
    ZlRul6vFgS3uaaEyaPXrG5pFRPeLlqllJxQ5Z1mQtqaK9U0dSCykxW6zaz3d8YXE
    BIe/0Vc1/0d80lkJk/3SnLGIAiC2C9dpmA6RmgkGa0cyD5QPmXmYXHFT+tA7S/lV
    W+5C6ZO0aaOmO+F+W82ZJ92FRd8CITasoPO9zxalJBEGD/s5ehnRhhizLqjY";

            var publickey  = Convert.FromBase64String(pubkey);
            var privatekey = Convert.FromBase64String(prikey);

            var asnprivate = Asn1Object.FromStream(new MemoryStream(privatekey));
            var privStruct = new RsaPrivateKeyStructure((Asn1Sequence)asnprivate);

            RsaKeyParameters privateAsymmetricKey = new RsaKeyParameters(true, privStruct.Modulus, privStruct.PrivateExponent);
            RsaKeyParameters publicAsymmetricKey  = (RsaKeyParameters)PublicKeyFactory.CreateKey(publickey);

            var inputBytes = Encoding.UTF8.GetBytes("the message");

            Console.WriteLine("--- Message: ----");
            Console.WriteLine(Encoding.UTF8.GetString(inputBytes));

            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(true, publicAsymmetricKey);
            var cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputBytes.Length);

            Console.WriteLine("--- Enc utf8: ----");
            Console.WriteLine(Encoding.UTF8.GetString(cipheredBytes));

            Console.WriteLine("--- Enc Base64: ----");
            Console.WriteLine(Convert.ToBase64String(cipheredBytes));

            cipher.Init(false, privateAsymmetricKey);
            var deciphered = cipher.ProcessBlock(cipheredBytes, 0, cipheredBytes.Length);

            Console.WriteLine("--- Dec: ----");
            Console.WriteLine(Encoding.UTF8.GetString(deciphered));
            Console.ReadLine();
        }
Esempio n. 14
0
 public static AsymmetricKeyParameter DecryptKey(
     char[] passPhrase,
     Stream encryptedPrivateKeyInfoStream)
 {
     return(DecryptKey(passPhrase, Asn1Object.FromStream(encryptedPrivateKeyInfoStream)));
 }
        public static MyPolicy getHashPolitica(string PolicyUriSource, string PolicyIdentifier = "2.16.76.1.7.1.2.2.3", string PolicyDigestAlgorithm = "SHA-256", string FileName = "LPA_CAdES.der")
        {
            MyPolicy Retorno = new MyPolicy();

            Retorno.PolicyIdentifier      = PolicyIdentifier;
            Retorno.PolicyDigestAlgorithm = PolicyDigestAlgorithm;
            Retorno.URLPolicy             = PolicyUriSource;

            Stream St;

            try
            {
                St = Helper.FileHelper.MSReadFileURL(PolicyUriSource);
            }
            catch (Exception ex)
            {
                //FileStream File = Helper.FileHelper.FSReadFile(System.AppDomain.CurrentDomain.BaseDirectory + FileName);
                //St = File;
                St = new MemoryStream(Properties.Resources.LPA_CAdES);
            }
            DerSequence privKeyObj = (DerSequence)Asn1Object.FromStream(St);

            var objCollection = privKeyObj.GetEnumerator();

            objCollection.MoveNext();


            Org.BouncyCastle.Asn1.Asn1Sequence objPrincipal = (Org.BouncyCastle.Asn1.Asn1Sequence)objCollection.Current;
            var Politicas = objPrincipal.GetObjects();



            while (Politicas.MoveNext())
            {
                Org.BouncyCastle.Asn1.Asn1Sequence Politica = (Org.BouncyCastle.Asn1.Asn1Sequence)Politicas.Current;
                var Itens = Politica.GetObjects();
                Itens.MoveNext();
                string item1 = Itens.Current.ToString();
                Itens.MoveNext();
                string item2 = Itens.Current.ToString();
                if (item2.Contains(PolicyIdentifier))
                {
                    Itens.MoveNext();
                    string item3 = Itens.Current.ToString();
                    Retorno.SubURLPolicy = item3.Replace("[", "").Replace("]", "");

                    Itens.MoveNext();
                    Org.BouncyCastle.Asn1.Asn1Sequence item4 = (Org.BouncyCastle.Asn1.Asn1Sequence)Itens.Current;

                    var Item4d = item4.GetObjects();
                    Item4d.MoveNext();
                    Retorno.SubPolicyIdentifier = Item4d.Current.ToString().Replace("[", "").Replace("]", "");


                    Item4d.MoveNext();
                    Retorno.Hash = Item4d.Current.ToString();
                }
            }
            St.Close();
            return(Retorno);
        }
Esempio n. 16
0
        public void Load(
            Stream input,
            char[] password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         unmarkedKey     = false;
            bool         wrongPkcs12Zero = false;

            if (bag.MacData != null) // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();

            IList chain = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        byte[]       octets = ((Asn1OctetString)ci.Content).GetOctets();
                        Asn1Sequence seq    = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                if (b.BagAttributes != null)
                                {
                                    foreach (Asn1Sequence sq in b.BagAttributes)
                                    {
                                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                        Asn1Set             attrSet = (Asn1Set)sq[1];
                                        Asn1Encodable       attr    = null;

                                        if (attrSet.Count > 0)
                                        {
                                            // TODO We should be adding all attributes in the set
                                            attr = attrSet[0];

                                            // TODO We might want to "merge" attribute sets with
                                            // the same OID - currently, differing values give an error
                                            if (attributes.Contains(aOid.Id))
                                            {
                                                // OK, but the value has to be the same
                                                if (!attributes[aOid.Id].Equals(attr))
                                                {
                                                    throw new IOException("attempt to add existing attribute with different value");
                                                }
                                            }
                                            else
                                            {
                                                attributes.Add(aOid.Id, attr);
                                            }

                                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                            {
                                                alias = ((DerBmpString)attr).GetString();
                                                // TODO Do these in a separate loop, just collect aliases here
                                                keys[alias] = pkcs12Key;
                                            }
                                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                            {
                                                localId = (Asn1OctetString)attr;
                                            }
                                        }
                                    }
                                }

                                if (localId != null)
                                {
                                    string name = Hex.ToHexString(localId.GetOctets());

                                    if (alias == null)
                                    {
                                        keys[name] = pkcs12Key;
                                    }
                                    else
                                    {
                                        // TODO There may have been more than one alias
                                        localIds[alias] = name;
                                    }
                                }
                                else
                                {
                                    unmarkedKey      = true;
                                    keys["unmarked"] = pkcs12Key;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else
                            {
#if !NETFX_CORE
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
#endif
                            }
                        }
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        EncryptedData d      = EncryptedData.GetInstance(ci.Content);
                        byte[]        octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                            password, wrongPkcs12Zero, d.Content.GetOctets());
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.Contains(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                string name = Hex.ToHexString(localId.GetOctets());

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                PrivateKeyInfo          privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue);
                                IAsymmetricKeyParameter privKey     = PrivateKeyFactory.CreateKey(privKeyInfo);

                                //
                                // set the attributes on the key
                                //
                                string             alias      = null;
                                Asn1OctetString    localId    = null;
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.Contains(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                string name = Hex.ToHexString(localId.GetOctets());

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else
                            {
#if !NETFX_CORE
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
#endif
                            }
                        }
                    }
                    else
                    {
#if !NETFX_CORE
                        Console.WriteLine("extra " + oid);
                        Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content));
#endif
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in chain)
            {
                CertBag         cb     = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets = ((Asn1OctetString)cb.CertValue).GetOctets();
                X509Certificate cert   = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                        Asn1Set             attrSet = (Asn1Set)sq[1];

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = pkcs12Cert;

                if (unmarkedKey)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = pkcs12Cert;

                        object temp = keys["unmarked"];
                        keys.Remove("unmarked");
                        keys[name] = temp;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = pkcs12Cert;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = pkcs12Cert;
                    }
                }
            }
        }
Esempio n. 17
0
        private static void RsaKeyGeneratorTest()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);

            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和私钥
            AsymmetricKeyParameter publicKey  = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
            {
                Console.WriteLine("failed key generation (1024) length test");
            }
            savetheKey(publicKey, privateKey);



            //一个测试……………………
            //输入,十六进制的字符串,解码为byte[]
            //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
            //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input);
            string input = "popozh RSA test";

            byte[] testData = Encoding.UTF8.GetBytes(input);
            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();
            //公钥加密
            //从保存在本地的磁盘文件中读取公钥
            Asn1Object             aobject       = Asn1Object.FromStream(new FileStream(pubKeyFile, FileMode.Open, FileAccess.Read)); //a.puk??
            SubjectPublicKeyInfo   pubInfo       = SubjectPublicKeyInfo.GetInstance(aobject);
            AsymmetricKeyParameter testpublicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
            FileStream             fs;

            engine.Init(true, testpublicKey);
            try
            {
                //Console.WriteLine("加密前:" + Convert.ToBase64String(testData) + Environment.NewLine);
                testData = engine.ProcessBlock(testData, 0, testData.Length);
                Console.WriteLine("加密完成!" + Environment.NewLine);
                fs = new FileStream(ecyFile, FileMode.Create, FileAccess.Write);
                fs.Write(testData, 0, testData.Length);
                fs.Close();
                Console.WriteLine("保存密文成功" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString());
            }
            //私钥解密
            //获取加密的私钥,进行解密,获得私钥
            fs = new FileStream(ecyFile, FileMode.Open, FileAccess.Read);
            byte[] anothertestdata = new byte[1024];
            fs.Read(anothertestdata, 0, anothertestdata.Length);
            fs.Close();
            Asn1Object aobj = Asn1Object.FromStream(new FileStream(priKeyFile, FileMode.Open, FileAccess.Read));   //a.pvk??
            EncryptedPrivateKeyInfo enpri = EncryptedPrivateKeyInfo.GetInstance(aobj);

            char[]                 password          = "******".ToCharArray();
            PrivateKeyInfo         priKey            = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enpri); //解密
            AsymmetricKeyParameter anotherprivateKey = PrivateKeyFactory.CreateKey(priKey);                         //私钥

            engine.Init(false, anotherprivateKey);
            try
            {
                anothertestdata = engine.ProcessBlock(anothertestdata, 0, testData.Length);
                Console.WriteLine("解密后密文为:" + Encoding.UTF8.GetString(anothertestdata) + Environment.NewLine);
            }
            catch (Exception e)
            {
                Console.WriteLine("failed - exception " + e.ToString());
            }

            Console.Read();
        }
        public static List <CertSimples> ListaCertificado(X509Certificate2Collection Certificados)
        {
            List <CertSimples> oLista = new List <CertSimples>();

            for (int i = 0; i < Certificados.Count; i++)
            {
                X509Certificate2 oCertificado = Certificados[i];

                CertSimples oCert = new CertSimples();
                oCert.SerialNumber = oCertificado.SerialNumber;
                oCert.Subject      = oCertificado.Subject;

                try
                {
                    string[] DadosSubject = oCertificado.Subject.Split(',');
                    if (DadosSubject[0].IndexOf(":") > -1)
                    {
                        oCert.Nome = DadosSubject[0].Substring(3, DadosSubject[0].IndexOf(":") - 3);
                    }
                    else
                    {
                        oCert.Nome = DadosSubject[0].Substring(3);
                    }
                }
                catch (Exception ex)
                {
                    oCert.Nome = oCert.Subject;
                }



                foreach (var obj in oCertificado.Extensions)
                {
                    if (obj.Oid.Value == "2.5.29.17") //otherName
                    {
                        byte[] Dados = obj.RawData;
                        Stream sm    = new MemoryStream(Dados);
                        // StreamReader oSr = new StreamReader(sm);

                        //string teste = System.Text.Encoding.ASCII.GetString(Dados);
                        DerSequence otherName     = (DerSequence)Asn1Object.FromStream(sm);
                        var         objCollection = otherName.GetEnumerator();
                        while (objCollection.MoveNext())
                        {
                            Org.BouncyCastle.Asn1.DerTaggedObject iSub = (Org.BouncyCastle.Asn1.DerTaggedObject)objCollection.Current;
                            Asn1Object derObject = iSub.GetObject();
                            if (derObject.GetType().Name.Contains("DerSequence"))
                            {
                                var            objSubCollection = ((DerSequence)derObject).GetEnumerator();
                                byte           count            = 0;
                                string         strOID           = "";
                                DerOctetString strOctet;// = (DerOctetString)derObject;
                                string         strTexto = "";

                                while (objSubCollection.MoveNext())
                                {
                                    var Conteudo = objSubCollection.Current;
                                    if (count == 0)
                                    {
                                        strOID = Conteudo.ToString();
                                    }
                                    else
                                    {
                                        Org.BouncyCastle.Asn1.DerTaggedObject subCampos = (Org.BouncyCastle.Asn1.DerTaggedObject)Conteudo;
                                        Asn1Object derSub = subCampos.GetObject();
                                        try
                                        {
                                            if (derSub.GetType().Name.Contains("DerOctetString"))
                                            {
                                                strOctet = (DerOctetString)derSub;
                                                byte[] Texto = strOctet.GetOctets();
                                                strTexto = System.Text.Encoding.ASCII.GetString(Texto);
                                            }
                                            else
                                            {
                                                DerPrintableString strPtrString = (DerPrintableString)derSub;
                                                strTexto = strPtrString.GetString();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            strTexto = derSub.ToString();
                                        }
                                    }
                                    count++;
                                }


                                if (strOID == "2.16.76.1.3.1") //PESSOA FÍSICA
                                {
                                    //i· OID = 2.16.76.1.3.1 e conteúdo = nas primeiras 8(oito) posições, a data de nascimento do titular, no formato ddmmaaaa; nas 11(onze) posições subseqüentes, o Cadastro de Pessoa Física(CPF) do titular; nas 11(onze) posições subseqüentes, o Número de Identificação Social – NIS(PIS, PASEP ou CI); nas 15(quinze) posições subseqüentes, o número do Registro Geral(RG) do titular; nas 10(dez) posições subseqüentes, as siglas do órgão expedidor do RG e respectiva unidade da federação;
                                    try
                                    {
                                        oCert.DataNascimento = strTexto.Substring(0, 8);
                                        oCert.CPF            = strTexto.Substring(8, 11);
                                        oCert.NIS            = strTexto.Substring(19, 11);
                                        oCert.RG             = strTexto.Substring(30, 15);
                                        oCert.OrgaoExpedidor = strTexto.Substring(45);
                                        oCert.Tipo           = "F";
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.1:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.6") //PESSOA FÍSICA
                                {
                                    //ii· OID = 2.16.76.1.3.6 e conteúdo = nas 12 (doze) posições o número do Cadastro Específico do INSS (CEI) da pessoa física titular do certificado;
                                }
                                else if (strOID == "2.16.76.1.3.6") //PESSOA FÍSICA
                                {
                                    try
                                    {
                                        //iii· OID = 2.16.76.1.3.5 e conteúdo nas primeiras 12(doze) posições, o número de inscrição do Título de Eleitor; nas 3(três) posições subseqüentes, a Zona Eleitoral; nas 4(quatro) posições seguintes, a Seção; nas 22(vinte e duas) posições subseqüentes, o município e a UF do Título de Eleitor.
                                        oCert.TituloEleitor      = strTexto.Substring(0, 12);
                                        oCert.ZonaEleitoral      = strTexto.Substring(12, 3);
                                        oCert.SecaoEleitoral     = strTexto.Substring(15, 4);
                                        oCert.MunicipioEleitoral = strTexto.Substring(19, 22);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.6:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.4.2.1.1")
                                {
                                    try
                                    {
                                        oCert.OAB = strTexto;
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.4.2.1.1:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.4")    //PESSOA JURÍDICA
                                {
                                    try
                                    {
                                        oCert.Tipo = "J";
                                        //i· OID = 2.16.76.1.3.4 e conteúdo = nas primeiras 8(oito) posições, a data de nascimento do responsável pelo certificado, no formato ddmmaaaa; nas 11(onze) posições subseqüentes, o Cadastro de Pessoa Física(CPF) do responsável; nas 11(onze) posições subseqüentes, o Número de Identificação Social – NIS(PIS, PASEP ou CI); nas 15(quinze) posições subseqüentes, o número do Registro Geral(RG) do responsável; nas 10(dez) posições subseqüentes, as siglas do órgão expedidor do RG e respectiva Unidade da Federação;
                                        oCert.DataNascimento = strTexto.Substring(0, 8);
                                        oCert.CPF            = strTexto.Substring(8, 11);
                                        try
                                        {
                                            oCert.NIS            = strTexto.Substring(19, 11);
                                            oCert.RG             = strTexto.Substring(30, 15);
                                            oCert.OrgaoExpedidor = strTexto.Substring(45, 10);
                                        }
                                        catch (Exception ex)
                                        { }
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.4:" + strTexto + "." + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.2")    //PESSOA JURÍDICA
                                {
                                    //ii· OID = 2.16.76.1.3.2 e conteúdo = nome do responsável pelo certificado;
                                    try
                                    {
                                        oCert.NomeResponsavel = strTexto;
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.2:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.3")    //PESSOA JURÍDICA
                                {
                                    //iii· OID = 2.16.76.1.3.3 e conteúdo = nas 14(quatorze) posições o número do Cadastro Nacional de Pessoa Jurídica(CNPJ) da pessoa jurídica titular do certificado;
                                    try
                                    {
                                        oCert.CNPJ = strTexto;
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.3:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.7")    //PESSOA JURÍDICA
                                {
                                    //iv. OID = 2.16.76.1.3.7 e conteúdo = nas 12 (doze) posições o número do Cadastro Específico do INSS (CEI) da pessoa jurídica titular do certificado.
                                }

                                count = 0;
                            }
                            else
                            {
                                //i. rfc822Name contendo o endereço e-mail do titular do certificado.
                                if (derObject.GetType().Name == "DerOctetString")
                                {
                                    DerOctetString strOctet = (DerOctetString)derObject;
                                    byte[]         Texto    = strOctet.GetOctets();
                                    string         strTexto = System.Text.Encoding.ASCII.GetString(Texto);
                                    oCert.Email = strTexto;
                                }
                                else
                                {
                                    string texto = derObject.GetType().Name;
                                }
                            }
                        }
                        sm.Close();
                    }
                }
                oCert.Certificado = oCertificado;
                oLista.Add(oCert);
            }

            return(oLista);
        }
Esempio n. 19
0
        public void Load(Stream input, char[] password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            Asn1Sequence seq             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          pfx             = new Pfx(seq);
            ContentInfo  authSafe        = pfx.AuthSafe;
            bool         wrongPkcs12Zero = false;

            if (password != null && pfx.MacData != null)
            {
                MacData             macData     = pfx.MacData;
                DigestInfo          mac         = macData.Mac;
                AlgorithmIdentifier algorithmID = mac.AlgorithmID;
                byte[] salt     = macData.GetSalt();
                int    intValue = macData.IterationCount.IntValue;
                byte[] octets   = ((Asn1OctetString)authSafe.Content).GetOctets();
                byte[] a        = Pkcs12Store.CalculatePbeMac(algorithmID.ObjectID, salt, intValue, password, false, octets);
                byte[] digest   = mac.GetDigest();
                if (!Arrays.ConstantTimeAreEqual(a, digest))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }
                    a = Pkcs12Store.CalculatePbeMac(algorithmID.ObjectID, salt, intValue, password, true, octets);
                    if (!Arrays.ConstantTimeAreEqual(a, digest))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }
                    wrongPkcs12Zero = true;
                }
            }
            this.keys.Clear();
            this.localIds.Clear();
            this.unmarkedKeyEntry = null;
            IList list = Platform.CreateArrayList();

            if (authSafe.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octets2           = ((Asn1OctetString)authSafe.Content).GetOctets();
                AuthenticatedSafe authenticatedSafe = new AuthenticatedSafe((Asn1Sequence)Asn1Object.FromByteArray(octets2));
                ContentInfo[]     contentInfo       = authenticatedSafe.GetContentInfo();
                ContentInfo[]     array             = contentInfo;
                for (int i = 0; i < array.Length; i++)
                {
                    ContentInfo         contentInfo2 = array[i];
                    DerObjectIdentifier contentType  = contentInfo2.ContentType;
                    byte[] array2 = null;
                    if (contentType.Equals(PkcsObjectIdentifiers.Data))
                    {
                        array2 = ((Asn1OctetString)contentInfo2.Content).GetOctets();
                    }
                    else if (contentType.Equals(PkcsObjectIdentifiers.EncryptedData) && password != null)
                    {
                        EncryptedData instance = EncryptedData.GetInstance(contentInfo2.Content);
                        array2 = Pkcs12Store.CryptPbeData(false, instance.EncryptionAlgorithm, password, wrongPkcs12Zero, instance.Content.GetOctets());
                    }
                    if (array2 != null)
                    {
                        Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(array2);
                        foreach (Asn1Sequence seq2 in asn1Sequence)
                        {
                            SafeBag safeBag = new SafeBag(seq2);
                            if (safeBag.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                list.Add(safeBag);
                            }
                            else if (safeBag.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                this.LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(safeBag.BagValue), safeBag.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (safeBag.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                this.LoadKeyBag(PrivateKeyInfo.GetInstance(safeBag.BagValue), safeBag.BagAttributes);
                            }
                        }
                    }
                }
            }
            this.certs.Clear();
            this.chainCerts.Clear();
            this.keyCerts.Clear();
            foreach (SafeBag safeBag2 in list)
            {
                CertBag         certBag         = new CertBag((Asn1Sequence)safeBag2.BagValue);
                byte[]          octets3         = ((Asn1OctetString)certBag.CertValue).GetOctets();
                X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(octets3);
                IDictionary     dictionary      = Platform.CreateHashtable();
                Asn1OctetString asn1OctetString = null;
                string          text            = null;
                if (safeBag2.BagAttributes != null)
                {
                    foreach (Asn1Sequence asn1Sequence2 in safeBag2.BagAttributes)
                    {
                        DerObjectIdentifier instance2 = DerObjectIdentifier.GetInstance(asn1Sequence2[0]);
                        Asn1Set             instance3 = Asn1Set.GetInstance(asn1Sequence2[1]);
                        if (instance3.Count > 0)
                        {
                            Asn1Encodable asn1Encodable = instance3[0];
                            if (dictionary.Contains(instance2.Id))
                            {
                                if (!dictionary[instance2.Id].Equals(asn1Encodable))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                dictionary.Add(instance2.Id, asn1Encodable);
                            }
                            if (instance2.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                text = ((DerBmpString)asn1Encodable).GetString();
                            }
                            else if (instance2.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                asn1OctetString = (Asn1OctetString)asn1Encodable;
                            }
                        }
                    }
                }
                Pkcs12Store.CertId   certId = new Pkcs12Store.CertId(x509Certificate.GetPublicKey());
                X509CertificateEntry value  = new X509CertificateEntry(x509Certificate, dictionary);
                this.chainCerts[certId] = value;
                if (this.unmarkedKeyEntry != null)
                {
                    if (this.keyCerts.Count == 0)
                    {
                        string text2 = Hex.ToHexString(certId.Id);
                        this.keyCerts[text2] = value;
                        this.keys[text2]     = this.unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (asn1OctetString != null)
                    {
                        string key = Hex.ToHexString(asn1OctetString.GetOctets());
                        this.keyCerts[key] = value;
                    }
                    if (text != null)
                    {
                        this.certs[text] = value;
                    }
                }
            }
        }