byte[] EncryptAsymmetricKeyParameter(AsymmetricKeyParameter key)
        {
            var cipher  = PbeUtilities.CreateEngine(EncryptionAlgorithm.Id) as IBufferedCipher;
            var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);
            var random  = new SecureRandom();
            var salt    = new byte[SaltSize];

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

            random.NextBytes(salt);

            var pbeParameters    = PbeUtilities.GenerateAlgorithmParameters(EncryptionAlgorithm.Id, salt, MinIterations);
            var algorithm        = new AlgorithmIdentifier(EncryptionAlgorithm, pbeParameters);
            var cipherParameters = PbeUtilities.GenerateCipherParameters(algorithm, passwd);

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

            cipher.Init(true, cipherParameters);

            var encoded = cipher.DoFinal(keyInfo.GetEncoded());

            var encrypted = new EncryptedPrivateKeyInfo(algorithm, encoded);

            return(encrypted.GetEncoded());
        }
Ejemplo n.º 2
0
        public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
            string algorithm,
            char[]                      passPhrase,
            byte[]                      salt,
            int iterationCount,
            PrivateKeyInfo keyInfo)
        {
            if (!PbeUtilities.IsPbeAlgorithm(algorithm))
            {
                throw new ArgumentException("attempt to use non-PBE algorithm with PBE EncryptedPrivateKeyInfo generation");
            }

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

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

            Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters(
                algorithm, salt, iterationCount);

            ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
                algorithm, passPhrase, parameters);

            cipher.Init(true, keyParameters);

            byte[] keyBytes = keyInfo.GetEncoded();
            byte[] encoding = cipher.DoFinal(keyBytes);

            DerObjectIdentifier oid   = PbeUtilities.GetObjectIdentifier(algorithm);
            AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, parameters);

            return(new EncryptedPrivateKeyInfo(algID, encoding));
        }
        public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
            string algorithm,
            char[]                      passPhrase,
            byte[]                      salt,
            int iterationCount,
            PrivateKeyInfo keyInfo)
        {
            IBufferedCipher cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher;

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

            Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters(
                algorithm, salt, iterationCount);
            ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
                algorithm, passPhrase, pbeParameters);

            cipher.Init(true, cipherParameters);
            byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded());

            DerObjectIdentifier oid   = PbeUtilities.GetObjectIdentifier(algorithm);
            AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, pbeParameters);

            return(new EncryptedPrivateKeyInfo(algID, encoding));
        }
        public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
            DerObjectIdentifier cipherAlgorithm,
            DerObjectIdentifier prfAlgorithm,
            char[] passPhrase,
            byte[] salt,
            int iterationCount,
            SecureRandom random,
            PrivateKeyInfo keyInfo)
        {
            IBufferedCipher cipher = CipherUtilities.GetCipher(cipherAlgorithm) as IBufferedCipher;

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

            Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters(
                cipherAlgorithm, prfAlgorithm, salt, iterationCount, random);
            ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
                PkcsObjectIdentifiers.IdPbeS2, passPhrase, pbeParameters);

            cipher.Init(true, cipherParameters);
            byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded());

            AlgorithmIdentifier algID = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbeS2, pbeParameters);

            return(new EncryptedPrivateKeyInfo(algID, encoding));
        }
Ejemplo n.º 5
0
            public override void PerformTest()
            {
                byte[] salt   = new byte[16];
                int    iCount = 100;

                for (int i = 0; i != salt.Length; i++)
                {
                    salt[i] = (byte)i;
                }

                PbeParametersGenerator pGen = new OpenSslPbeParametersGenerator();

                pGen.Init(
                    PbeParametersGenerator.Pkcs5PasswordToBytes(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");
                }
            }
Ejemplo n.º 6
0
        internal static byte[] CalculatePbeMac(DerObjectIdentifier oid, byte[] salt, int itCount, char[] password, bool wrongPkcs12Zero, byte[] data)
        {
            Asn1Encodable     pbeParameters = PbeUtilities.GenerateAlgorithmParameters(oid, salt, itCount);
            ICipherParameters parameters    = PbeUtilities.GenerateCipherParameters(oid, password, wrongPkcs12Zero, pbeParameters);
            IMac mac = (IMac)PbeUtilities.CreateEngine(oid);

            mac.Init(parameters);
            return(MacUtilities.DoFinal(mac, data));
        }
Ejemplo n.º 7
0
        internal static byte[] CalculatePbeMac(DerObjectIdentifier oid, byte[] salt, int itCount, char[] password, bool wrongPkcs12Zero, byte[] data)
        {
            Asn1Encodable     asn1Params   = PbeUtilities.GenerateAlgorithmParameters(oid, salt, itCount);
            ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(oid, password, wrongPkcs12Zero, asn1Params);

            var mac = (IMac)PbeUtilities.CreateEngine(oid);

            mac.Init(cipherParams);
            mac.BlockUpdate(data, 0, data.Length);
            return(MacUtilities.DoFinal(mac));
        }
Ejemplo n.º 8
0
        private void doTestPbeHMac(
            string hmacName,
            byte[]  output)
        {
            ICipherParameters key = null;

            byte[] outBytes;
            IMac   mac = null;

            try
            {
//				SecretKeyFactory fact = SecretKeyFactory.getInstance(hmacName);
//
//				key = fact.generateSecret(new PBEKeySpec("hello".ToCharArray()));

                Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
                    hmacName, new byte[20], 100);
                key = PbeUtilities.GenerateCipherParameters(
                    hmacName, "hello".ToCharArray(), algParams);
                mac = MacUtilities.GetMac(hmacName);
            }
            catch (Exception e)
            {
                Fail("Failed - exception " + e.ToString(), e);
            }

            try
            {
//				mac.Init(key, new PBEParameterSpec(new byte[20], 100));
                mac.Init(key);
            }
            catch (Exception e)
            {
                Fail("Failed - exception " + e.ToString(), e);
            }

            mac.Reset();

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

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

            if (!AreEqual(outBytes, output))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(outBytes));
            }
        }
Ejemplo n.º 9
0
        //public static byte[] Decrypt2(this byte[] cmessage,string password, byte[] salt)
        //{
        //    int KEY_SIZE = 256;
        //    int iterations = 100;
        //    //byte[] salt = new byte[KEY_SIZE >> 3];

        //    IBufferedCipher decCipher = BuildDecryptionCipher(password, iterations, salt);
        //    return DecryptTemp(decCipher, cmessage);
        //}

        private static IBufferedCipher BuildDecryptionCipher(string password, int iterations, byte[] salt)
        {
            string DECRYPTION_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";

            // get the password bytes
            char[] passwordChars = password.ToCharArray();

            IBufferedCipher cipher = CipherUtilities.GetCipher(DECRYPTION_ALGORITHM);

            Org.BouncyCastle.Asn1.Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(DECRYPTION_ALGORITHM, salt, iterations);
            ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(DECRYPTION_ALGORITHM, passwordChars, algParams);

            cipher.Init(false, cipherParams);

            return(cipher);
        }
Ejemplo n.º 10
0
        public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo)
        {
            IBufferedCipher bufferedCipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher;

            if (bufferedCipher == null)
            {
                throw new global::System.Exception("Unknown encryption algorithm: " + algorithm);
            }
            Asn1Encodable     asn1Encodable = PbeUtilities.GenerateAlgorithmParameters(algorithm, salt, iterationCount);
            ICipherParameters parameters    = PbeUtilities.GenerateCipherParameters(algorithm, passPhrase, asn1Encodable);

            bufferedCipher.Init(forEncryption: true, parameters);
            byte[] encoding = bufferedCipher.DoFinal(keyInfo.GetEncoded());
            DerObjectIdentifier objectIdentifier = PbeUtilities.GetObjectIdentifier(algorithm);
            AlgorithmIdentifier algId            = new AlgorithmIdentifier(objectIdentifier, asn1Encodable);

            return(new EncryptedPrivateKeyInfo(algId, encoding));
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
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");
            }
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
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;
                    }
                }
            }
        }
Ejemplo n.º 15
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");
//				}
            }