Esempio n. 1
0
        private static byte[] CryptPbeData(
            bool forEncryption,
            AlgorithmIdentifier algId,
            char[]                              password,
            bool wrongPkcs12Zero,
            byte[]                              data)
        {
            IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.Algorithm) as IBufferedCipher;

            if (cipher == null)
            {
                throw new Exception("Unknown encryption algorithm: " + algId.Algorithm);
            }

            Pkcs12PbeParams   pbeParameters = Pkcs12PbeParams.GetInstance(algId.Parameters);
            ICipherParameters cipherParams  = PbeUtilities.GenerateCipherParameters(
                algId.Algorithm, password, wrongPkcs12Zero, pbeParameters);

            cipher.Init(forEncryption, cipherParams);
            return(cipher.DoFinal(data));
        }
Esempio n. 2
0
        public static PrivateKeyInfo CreatePrivateKeyInfo(
            char[]                                      passPhrase,
            bool wrongPkcs12Zero,
            EncryptedPrivateKeyInfo encInfo)
        {
            AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm;

            IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher;

            if (cipher == null)
            {
                throw new Exception("Unknown encryption algorithm: " + algID.Algorithm);
            }

            ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
                algID, passPhrase, wrongPkcs12Zero);

            cipher.Init(false, cipherParameters);
            byte[] keyBytes = cipher.DoFinal(encInfo.GetEncryptedData());

            return(PrivateKeyInfo.GetInstance(keyBytes));
        }
Esempio n. 3
0
        // NB: These two makePbeCipher... methods are same in .NET
        private IBufferedCipher makePbeCipherWithoutParam(
            string algorithm,
            bool forEncryption,
            char[]  password,
            byte[]  salt,
            int iterationCount)
        {
//			PBEKeySpec pbeSpec = new PBEKeySpec(password, salt, iterationCount);
//			SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm);

            Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
                algorithm, salt, iterationCount);
            ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
                algorithm, password, algParams);

            IBufferedCipher cipher = CipherUtilities.GetCipher(algorithm);

//			cipher.Init(forEncryption, keyFact.generateSecret(pbeSpec));
            cipher.Init(forEncryption, cipherParams);

            return(cipher);
        }
Esempio n. 4
0
        internal Asn1Sequence DecryptData(
            AlgorithmIdentifier algId,
            byte[]                              data,
            char[]                              password,
            bool wrongPkcs12Zero)
        {
            Pkcs12PbeParams   pbeParams     = Pkcs12PbeParams.GetInstance(algId.Parameters);
            ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
                algId.ObjectID, password, wrongPkcs12Zero, pbeParams);

            IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher;

            if (cipher == null)
            {
                // TODO Throw exception?
            }

            cipher.Init(false, keyParameters);

            byte[] encoding = cipher.DoFinal(data);

            return((Asn1Sequence)Asn1Object.FromByteArray(encoding));
        }
        AsymmetricKeyParameter DecryptAsymmetricKeyParameter(byte[] buffer, int length)
        {
            using (var memory = new MemoryStream(buffer, 0, length, false)) {
                using (var asn1 = new Asn1InputStream(memory)) {
                    var sequence = asn1.ReadObject() as Asn1Sequence;
                    if (sequence == null)
                    {
                        return(null);
                    }

                    var encrypted = EncryptedPrivateKeyInfo.GetInstance(sequence);
                    var algorithm = encrypted.EncryptionAlgorithm;
                    var encoded   = encrypted.GetEncryptedData();

                    var cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher;
                    if (cipher == null)
                    {
                        return(null);
                    }

                    var cipherParameters = PbeUtilities.GenerateCipherParameters(algorithm, passwd);

                    if (cipherParameters == null)
                    {
                        throw new Exception("BouncyCastle bug detected: Failed to generate cipher parameters.");
                    }

                    cipher.Init(false, cipherParameters);

                    var decrypted = cipher.DoFinal(encoded);
                    var keyInfo   = PrivateKeyInfo.GetInstance(decrypted);

                    return(PrivateKeyFactory.CreateKey(keyInfo));
                }
            }
        }
        public static PrivateKeyInfo CreatePrivateKeyInfo(
            char[]                                  passPhrase,
            bool wrongPkcs12Zero,
            EncryptedPrivateKeyInfo encInfo)
        {
            AlgorithmIdentifier algID  = encInfo.EncryptionAlgorithm;
            IBufferedCipher     cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher;

            if (cipher == null)
            {
                // TODO Throw exception?
            }

            ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
                algID, passPhrase, wrongPkcs12Zero);

            cipher.Init(false, keyParameters);

            byte[]     keyBytes = encInfo.GetEncryptedData();
            byte[]     encoding = cipher.DoFinal(keyBytes);
            Asn1Object asn1Data = Asn1Object.FromByteArray(encoding);

            return(PrivateKeyInfo.GetInstance(asn1Data));
        }
Esempio n. 7
0
        private const string alg = "1.2.840.113549.1.12.1.3";         // 3 key triple DES with SHA-1

        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");

            fact.Init(new KeyGenerationParameters(new SecureRandom(), 512));

            AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            AsymmetricKeyParameter priKey = keyPair.Private;
            AsymmetricKeyParameter pubKey = keyPair.Public;

            //
            // set up the parameters
            //
            byte[]        salt           = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int           iterationCount = 100;
            Asn1Encodable defParams      = PbeUtilities.GenerateAlgorithmParameters(alg, salt, iterationCount);

            char[] password1 = { 'h', 'e', 'l', 'l', 'o' };

//				AlgorithmParameters parameters = AlgorithmParameters.getInstance(alg);
//
//				parameters.init(defParams);

            //
            // set up the key
            //
//				PBEKeySpec pbeSpec = new PBEKeySpec(password1);
//				SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg);

//				IBufferedCipher cipher = CipherUtilities.GetCipher(alg);
            IWrapper wrapper = WrapperUtilities.GetWrapper(alg);

            ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(
                alg, password1, defParams);

//				cipher.Init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters);
            wrapper.Init(true, parameters);

//				byte[] wrappedKey = cipher.Wrap(priKey);
            byte[] pkb        = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey).GetDerEncoded();
            byte[] wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length);

            //
            // create encrypted object
            //

            // TODO Figure out what this was supposed to do
//				EncryptedPrivateKeyInfo pInfo = new EncryptedPrivateKeyInfo(parameters, wrappedKey);
            PrivateKeyInfo          plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey);
            EncryptedPrivateKeyInfo pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg, password1, salt, iterationCount, plain);


            //
            // decryption step
            //
            char[] password2 = { 'h', 'e', 'l', 'l', 'o' };

//				pbeSpec = new PBEKeySpec(password2);
//
//				cipher = CipherUtilities.GetCipher(pInfo.EncryptionAlgorithm);
//
//				cipher.Init(false, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
//
//				PKCS8EncodedKeySpec keySpec = pInfo.getKeySpec(cipher);
            PrivateKeyInfo decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo);

//				if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded()))
            if (!decrypted.Equals(plain))
            {
                Fail("Private key does not match");
            }

            //
            // using ICipherParameters test
            //
//			pbeSpec = new PBEKeySpec(password1);
//			keyFact = SecretKeyFactory.getInstance(alg);
//			cipher = CipherUtilities.GetCipher(alg);
            wrapper = WrapperUtilities.GetWrapper(alg);

//			cipher.init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters);
            wrapper.Init(true, parameters);

//			wrappedKey = cipher.wrap(priKey);
            wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length);

            //
            // create encrypted object
            //

            // TODO Figure out what this was supposed to do
//			pInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(), wrappedKey);
            plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey);
            pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg, password1, salt, iterationCount, plain);

            //
            // decryption step
            //
//			pbeSpec = new PBEKeySpec(password2);
//
//			cipher = CipherUtilities.GetCipher(pInfo.getAlgName());
//
//			cipher.init(IBufferedCipher.DECRYPT_MODE, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters());
//
//			keySpec = pInfo.getKeySpec(cipher);
            decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo);

//			if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded()))
            if (!decrypted.Equals(plain))
            {
                Fail("Private key does not match");
            }
        }
Esempio n. 8
0
        public void Save(
            Stream stream,
            char[]                  password,
            SecureRandom random)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }

            ContentInfo[] c = new ContentInfo[2];

            //
            // handle the key
            //
            Asn1EncodableVector keyS = new Asn1EncodableVector();

            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[saltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry      privKey = (AsymmetricKeyEntry)keys[name];
                EncryptedPrivateKeyInfo kInfo   =
                    EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                        keyAlgorithm, password, kSalt, minIterations, privKey.Key);

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(privKey[oid])));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry ct = GetCertificate(name);

                    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                        ct.Certificate.GetPublicKey());

                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(new SubjectKeyIdentifier(info))));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString)privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(name))
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName));
                keyS.Add(kBag);
            }

            byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded();

            BerOctetString keyString = new BerOctetString(derEncodedBytes);

            //
            // certificate processing
            //
            byte[] cSalt = new byte[saltSize];

            random.NextBytes(cSalt);

            Asn1EncodableVector certSeq   = new Asn1EncodableVector();
            Pkcs12PbeParams     cParams   = new Pkcs12PbeParams(cSalt, minIterations);
            AlgorithmIdentifier cAlgId    = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            Hashtable           doneCerts = new Hashtable();

            foreach (string name in keys.Keys)
            {
                X509CertificateEntry certEntry = GetCertificate(name);
                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509CertType,
                    new DerOctetString(certEntry.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(certEntry[oid])));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString)certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(name))
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                        certEntry.Certificate.GetPublicKey());

                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(new SubjectKeyIdentifier(info))));
                }

                SafeBag sBag = new SafeBag(
                    PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

                doneCerts.Add(certEntry.Certificate, certEntry.Certificate);
            }

            foreach (string certId in certs.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                if (keys[certId] != null)
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509CertType,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString)cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(certId))
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag,
                                           cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

                doneCerts.Add(cert, cert);
            }

            foreach (CertId certId in chainCerts.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];

                if (doneCerts[cert] != null)
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509CertType,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(cert[oid])));
                }

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);
            }

            derEncodedBytes = new DerSequence(certSeq).GetDerEncoded();

            byte[]        certBytes = EncryptData(new AlgorithmIdentifier(certAlgorithm, cParams), derEncodedBytes, password);
            EncryptedData cInfo     = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));

            c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, keyString);
            c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());

            AuthenticatedSafe auth = new AuthenticatedSafe(c);

            byte[] pkg = auth.GetEncoded();

            ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(pkg));

            //
            // create the mac
            //
            byte[] mSalt   = new byte[20];
            int    itCount = minIterations;

            random.NextBytes(mSalt);

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

            MacData mData = null;

            Asn1Encodable     parameters    = PbeUtilities.GenerateAlgorithmParameters(OiwObjectIdentifiers.IdSha1, mSalt, itCount);
            ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
                OiwObjectIdentifiers.IdSha1, password, parameters);
            IMac mac = (IMac)PbeUtilities.CreateEngine(OiwObjectIdentifiers.IdSha1);

            mac.Init(keyParameters);

            mac.BlockUpdate(data, 0, data.Length);

            byte[] res = new byte[mac.GetMacSize()];

            mac.DoFinal(res, 0);

            AlgorithmIdentifier algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);
            DigestInfo          dInfo = new DigestInfo(algId, res);

            mData = new MacData(dInfo, mSalt, itCount);

            //
            // output the Pfx
            //
            Pfx pfx = new Pfx(mainInfo, mData);

            BerOutputStream berOut = new BerOutputStream(stream);

            berOut.WriteObject(pfx);
        }
Esempio n. 9
0
        public Pkcs12Store(
            Stream input,
            char[]      password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            Asn1InputStream bIn             = new Asn1InputStream(input);
            Asn1Sequence    obj             = (Asn1Sequence)bIn.ReadObject();
            Pfx             bag             = new Pfx(obj);
            ContentInfo     info            = bag.AuthSafe;
            ArrayList       chain           = new ArrayList();
            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();

                Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters(
                    algId.ObjectID, salt, itCount);
                ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
                    algId.ObjectID, password, parameters);
                IMac mac = (IMac)PbeUtilities.CreateEngine(algId.ObjectID);

                mac.Init(keyParameters);

                mac.BlockUpdate(data, 0, data.Length);

                byte[] res = new byte[mac.GetMacSize()];
                mac.DoFinal(res, 0);

                byte[] dig = dInfo.GetDigest();

                if (!Arrays.AreEqual(res, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new Exception("Pkcs12 key store mac invalid - wrong password or corrupted file.");
                    }

                    //
                    // may be incorrect zero length password
                    //
                    keyParameters = PbeUtilities.GenerateCipherParameters(
                        algId.ObjectID, password, true, parameters);

                    mac.Init(keyParameters);

                    mac.BlockUpdate(data, 0, data.Length);

                    res = new byte[mac.GetMacSize()];
                    mac.DoFinal(res, 0);

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

                    wrongPkcs12Zero = true;
                }
            }

            keys     = new Hashtable();
            localIds = new Hashtable();

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

                for (int i = 0; i != c.Length; i++)
                {
                    if (c[i].ContentType.Equals(PkcsObjectIdentifiers.Data))
                    {
                        byte[]       octets = ((Asn1OctetString)c[i].Content).GetOctets();
                        Asn1Sequence seq    = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        for (int j = 0; j != seq.Count; j++)
                        {
                            SafeBag b = new SafeBag((Asn1Sequence)seq[j]);
                            if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                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)
                                        {
                                            attr = attrSet[0];

                                            attributes.Add(aOid.Id, attr);
                                        }

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

                                if (localId != null)
                                {
                                    string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets()));

                                    if (alias == null)
                                    {
                                        keys[name] = pkcs12Key;
                                    }
                                    else
                                    {
                                        localIds[alias] = name;
                                    }
                                }
                                else
                                {
                                    unmarkedKey      = true;
                                    keys["unmarked"] = pkcs12Key;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else if (c[i].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        EncryptedData d   = EncryptedData.GetInstance(c[i].Content);
                        Asn1Sequence  seq = DecryptData(d.EncryptionAlgorithm, d.Content.GetOctets(), password, wrongPkcs12Zero);

                        for (int j = 0; j != seq.Count; j++)
                        {
                            SafeBag b = new SafeBag((Asn1Sequence)seq[j]);

                            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);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                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)
                                    {
                                        attr = attrSet[0];

                                        attributes.Add(aOid.Id, attr);
                                    }

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

                                string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets()));

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    localIds[alias] = name;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                PrivateKeyInfo         privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue);
                                AsymmetricKeyParameter privKey     = PrivateKeyFactory.CreateKey(privKeyInfo);

                                //
                                // set the attributes on the key
                                //
                                string             alias      = null;
                                Asn1OctetString    localId    = null;
                                Hashtable          attributes = new Hashtable();
                                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)
                                    {
                                        attr = attrSet[0];

                                        attributes.Add(aOid.Id, attr);
                                    }

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

                                string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets()));

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    localIds[alias] = name;
                                }
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("extra " + c[i].ContentType.Id);
                        Console.WriteLine("extra " + Asn1Dump.DumpAsString(c[i].Content));
                    }
                }
            }

            certs      = new Hashtable();
            chainCerts = new Hashtable();
            keyCerts   = new Hashtable();

            for (int i = 0; i < chain.Count; ++i)
            {
                SafeBag         b      = (SafeBag)chain[i];
                CertBag         cb     = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets = ((Asn1OctetString)cb.CertValue).GetOctets();
                X509Certificate cert   = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                Hashtable            attributes = new Hashtable();
                X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes);
                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)
                        {
                            Asn1Encodable attr = attrSet[0];

                            attributes.Add(aOid.Id, attr);

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

                AsymmetricKeyParameter publicKey = cert.GetPublicKey();
                chainCerts[new CertId(publicKey)] = pkcs12Cert;

                if (unmarkedKey)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Encoding.ASCII.GetString(
                            Hex.Encode(
                                new SubjectKeyIdentifier(
                                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)).GetKeyIdentifier()));

                        keyCerts[name] = pkcs12Cert;

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

                        keyCerts[name] = pkcs12Cert;
                    }

                    if (alias != null)
                    {
                        certs[alias] = pkcs12Cert;
                    }
                }
            }
        }
Esempio n. 10
0
            public override void PerformTest()
            {
                int iCount = 100;

                byte[] salt = DigestUtilities.DoFinal(digest);

                PbeParametersGenerator pGen = new Pkcs12ParametersGenerator(digest);

                pGen.Init(
                    PbeParametersGenerator.Pkcs12PasswordToBytes(password),
                    salt,
                    iCount);

                ParametersWithIV parameters = (ParametersWithIV)
                                              pGen.GenerateDerivedParameters(baseAlgorithm, keySize, ivSize);

                KeyParameter encKey = (KeyParameter)parameters.Parameters;

                IBufferedCipher c;

                if (baseAlgorithm.Equals("RC4"))
                {
                    c = CipherUtilities.GetCipher(baseAlgorithm);

                    c.Init(true, encKey);
                }
                else
                {
                    c = CipherUtilities.GetCipher(baseAlgorithm + "/CBC/PKCS7Padding");

                    c.Init(true, parameters);
                }

                byte[] enc = c.DoFinal(salt);

                c = CipherUtilities.GetCipher(algorithm);

//					PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount);
//					SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm);
//
//					c.Init(false, fact.generateSecret(keySpec));

                Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
                    algorithm, salt, iCount);
                ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
                    algorithm, password, algParams);

                c.Init(false, cipherParams);

                byte[] dec = c.DoFinal(enc);

                if (!AreEqual(salt, dec))
                {
                    Fail("" + algorithm + "failed encryption/decryption test");
                }

                // NB: We don't support retrieving parameters from cipher
//				//
//				// get the parameters
//				//
//				AlgorithmParameters param = c.getParameters();
//				PBEParameterSpec spec = (PBEParameterSpec)param.getParameterSpec(PBEParameterSpec.class);
//
//				if (!AreEqual(salt, spec.getSalt()))
//				{
//					Fail("" + algorithm + "failed salt test");
//				}
//
//				if (iCount != spec.getIterationCount())
//				{
//					Fail("" + algorithm + "failed count test");
//				}

                // NB: This section just repeats earlier test passing 'param' separately
//				//
//				// try using parameters
//				//
//				keySpec = new PBEKeySpec(password);
//
//				c.Init(false, fact.generateSecret(keySpec), param);
//
//				dec = c.DoFinal(enc);
//
//				if (!AreEqual(salt, dec))
//				{
//					Fail("" + algorithm + "failed encryption/decryption test");
//				}
            }