コード例 #1
0
        public IAsymmetricKey GetEncryptedPrivateKey(byte[] keyContent)
        {
            var encrpytedPrivateKeyInfo = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(keyContent));
            var cipherType = cipherTypeMapper.MapOidToCipherType(encrpytedPrivateKeyInfo.EncryptionAlgorithm.Algorithm.Id);

            return(new EncryptedKey(keyContent, cipherType));
        }
コード例 #2
0
        public object GetBagValue()
        {
            if (Type.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
            {
                return(new Pkcs8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.GetInstance(safeBag.BagValue)));
            }
            if (Type.Equals(PkcsObjectIdentifiers.CertBag))
            {
                CertBag certBag = CertBag.GetInstance(safeBag.BagValue);

                return(new X509Certificate(X509CertificateStructure.GetInstance(Asn1OctetString.GetInstance(certBag.CertValue).GetOctets())));
            }
            if (Type.Equals(PkcsObjectIdentifiers.KeyBag))
            {
                return(PrivateKeyInfo.GetInstance(safeBag.BagValue));
            }
            if (Type.Equals(PkcsObjectIdentifiers.CrlBag))
            {
                CrlBag crlBag = CrlBag.GetInstance(safeBag.BagValue);

                return(new X509Crl(CertificateList.GetInstance(Asn1OctetString.GetInstance(crlBag.CrlValue).GetOctets())));
            }

            return(safeBag.BagValue);
        }
コード例 #3
0
        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);

                    cipher.Init(false, cipherParameters);

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

                    return(PrivateKeyFactory.CreateKey(keyInfo));
                }
            }
        }
コード例 #4
0
 /**
  * Reads in an EncryptedPrivateKeyInfo
  *
  * @return the X509Certificate
  */
 public Object ParseObject(PemObject obj)
 {
     try
     {
         return(new Pkcs8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.GetInstance(obj.GetContent())));
     }
     catch (Exception e)
     {
         throw new OpenSslPemParsingException("problem parsing ENCRYPTED PRIVATE KEY: " + e.ToString(), e);
     }
 }
コード例 #5
0
ファイル: KeypairHelper.cs プロジェクト: bfchain/tokenid
        /// <summary>
        /// 获取私钥对象
        /// </summary>
        /// <param name="s">待解密字符串</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static AsymmetricKeyParameter GetPrivateKeyParameter(string encryptKey, string pwd)
        {
            byte[]     privateKeyByte     = Convert.FromBase64String(encryptKey);
            Asn1Object aobj               = Asn1Object.FromByteArray(privateKeyByte);
            EncryptedPrivateKeyInfo enpri = EncryptedPrivateKeyInfo.GetInstance(aobj);

            char[] password = pwd.ToCharArray();

            PrivateKeyInfo         priKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enpri);
            AsymmetricKeyParameter result = PrivateKeyFactory.CreateKey(priKey);

            return(result);
        }
コード例 #6
0
        private static EncryptedPrivateKeyInfo parseBytes(byte[] pkcs8Encoding)
        {
            try
            {
                return(EncryptedPrivateKeyInfo.GetInstance(pkcs8Encoding));
            }

            catch (ArgumentException e)
            {
                throw new PkcsIOException("malformed data: " + e.Message, e);
            }
            catch (Exception e)
            {
                throw new PkcsIOException("malformed data: " + e.Message, e);
            }
        }
コード例 #7
0
        private ITestResult DoTest(
            int id,
            byte[]      sample)
        {
            EncryptedPrivateKeyInfo info;

            try
            {
                info = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(sample));
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": test " + id + " failed construction - exception "
                                            + e.ToString()));
            }

            byte[] bytes;
            try
            {
                bytes = info.GetDerEncoded();
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false,
                                            Name + ": test " + id + " failed writing - exception " + e.ToString()));
            }

            if (!Arrays.AreEqual(bytes, sample))
            {
                try
                {
                    Asn1Object obj = Asn1Object.FromByteArray(bytes);

                    return(new SimpleTestResult(false, Name + ": test " + id
                                                + " length mismatch - expected " + sample.Length + SimpleTest.NewLine
                                                + Asn1Dump.DumpAsString(info) + " got " + bytes.Length + SimpleTest.NewLine
                                                + Asn1Dump.DumpAsString(obj)));
                }
                catch (Exception e)
                {
                    return(new SimpleTestResult(false, Name + ": test " + id + " data mismatch - exception " + e.ToString()));
                }
            }

            return(new SimpleTestResult(true, Name + ": test " + id + " Okay"));
        }
コード例 #8
0
ファイル: Pkcs5Test.cs プロジェクト: twistys01/ripple-cs
            public override void PerformTest()
            {
                char[] password = "******".ToCharArray();
                PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator();

                EncryptedPrivateKeyInfo info = null;

                try
                {
                    info = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(sample));
                }
                catch (System.Exception e)
                {
                    Fail("failed construction - exception " + e.ToString(), e);
                }

                PbeS2Parameters  alg    = PbeS2Parameters.GetInstance(info.EncryptionAlgorithm.Parameters);
                Pbkdf2Params     func   = Pbkdf2Params.GetInstance(alg.KeyDerivationFunc.Parameters);
                EncryptionScheme scheme = alg.EncryptionScheme;

                if (func.KeyLength != null)
                {
                    keySize = func.KeyLength.IntValue * 8;
                }

                int iterationCount = func.IterationCount.IntValue;

                byte[] salt = func.GetSalt();

                generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iterationCount);

                DerObjectIdentifier algOid = scheme.ObjectID;

                byte[] iv;
                if (algOid.Equals(PkcsObjectIdentifiers.RC2Cbc))
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(scheme.Asn1Object);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = ((Asn1OctetString)scheme.Asn1Object).GetOctets();
                }

                ICipherParameters param = new ParametersWithIV(
                    generator.GenerateDerivedParameters(algOid.Id, keySize), iv);

                cipher.Init(false, param);

                byte[] data     = info.GetEncryptedData();
                byte[] outBytes = new byte[cipher.GetOutputSize(data.Length)];
                int    len      = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0);

                try
                {
                    len += cipher.DoFinal(outBytes, len);
                }
                catch (Exception e)
                {
                    Fail("failed DoFinal - exception " + e.ToString());
                }

                if (result.Length != len)
                {
                    Fail("failed length");
                }

                for (int i = 0; i != len; i++)
                {
                    if (outBytes[i] != result[i])
                    {
                        Fail("failed comparison");
                    }
                }
            }
コード例 #9
0
 private static AsymmetricKeyParameter DecryptKey(
     char[] passPhrase,
     Asn1Object asn1Object)
 {
     return(DecryptKey(passPhrase, EncryptedPrivateKeyInfo.GetInstance(asn1Object)));
 }
コード例 #10
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;
                    }
                }
            }
        }
コード例 #11
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;
                    }
                }
            }
        }
コード例 #12
0
ファイル: PemReader.cs プロジェクト: UnforeseenOcean/Warmode
        private object ReadPrivateKey(PemObject pemObject)
        {
            string text = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();

            byte[]      array      = pemObject.Content;
            IDictionary dictionary = Platform.CreateHashtable();

            foreach (PemHeader pemHeader in pemObject.Headers)
            {
                dictionary[pemHeader.Name] = pemHeader.Value;
            }
            string a = (string)dictionary["Proc-Type"];

            if (a == "4,ENCRYPTED")
            {
                if (this.pFinder == null)
                {
                    throw new PasswordException("No password finder specified, but a password is required");
                }
                char[] password = this.pFinder.GetPassword();
                if (password == null)
                {
                    throw new PasswordException("Password is null, but a password is required");
                }
                string   text2  = (string)dictionary["DEK-Info"];
                string[] array2 = text2.Split(new char[]
                {
                    ','
                });
                string dekAlgName = array2[0].Trim();
                byte[] iv         = Hex.Decode(array2[1].Trim());
                array = PemUtilities.Crypt(false, array, password, dekAlgName, iv);
            }
            object result;

            try
            {
                Asn1Sequence instance = Asn1Sequence.GetInstance(array);
                string       a2;
                if ((a2 = text) != null)
                {
                    AsymmetricKeyParameter asymmetricKeyParameter;
                    AsymmetricKeyParameter publicParameter;
                    if (!(a2 == "RSA"))
                    {
                        if (!(a2 == "DSA"))
                        {
                            if (!(a2 == "EC"))
                            {
                                if (!(a2 == "ENCRYPTED"))
                                {
                                    if (!(a2 == ""))
                                    {
                                        goto IL_356;
                                    }
                                    result = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(instance));
                                    return(result);
                                }
                                else
                                {
                                    char[] password2 = this.pFinder.GetPassword();
                                    if (password2 == null)
                                    {
                                        throw new PasswordException("Password is null, but a password is required");
                                    }
                                    result = PrivateKeyFactory.DecryptKey(password2, EncryptedPrivateKeyInfo.GetInstance(instance));
                                    return(result);
                                }
                            }
                            else
                            {
                                ECPrivateKeyStructure eCPrivateKeyStructure = new ECPrivateKeyStructure(instance);
                                AlgorithmIdentifier   algID   = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, eCPrivateKeyStructure.GetParameters());
                                PrivateKeyInfo        keyInfo = new PrivateKeyInfo(algID, eCPrivateKeyStructure.ToAsn1Object());
                                asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyInfo);
                                DerBitString publicKey = eCPrivateKeyStructure.GetPublicKey();
                                if (publicKey != null)
                                {
                                    SubjectPublicKeyInfo keyInfo2 = new SubjectPublicKeyInfo(algID, publicKey.GetBytes());
                                    publicParameter = PublicKeyFactory.CreateKey(keyInfo2);
                                }
                                else
                                {
                                    publicParameter = ECKeyPairGenerator.GetCorrespondingPublicKey((ECPrivateKeyParameters)asymmetricKeyParameter);
                                }
                            }
                        }
                        else
                        {
                            if (instance.Count != 6)
                            {
                                throw new PemException("malformed sequence in DSA private key");
                            }
                            DerInteger    derInteger  = (DerInteger)instance[1];
                            DerInteger    derInteger2 = (DerInteger)instance[2];
                            DerInteger    derInteger3 = (DerInteger)instance[3];
                            DerInteger    derInteger4 = (DerInteger)instance[4];
                            DerInteger    derInteger5 = (DerInteger)instance[5];
                            DsaParameters parameters  = new DsaParameters(derInteger.Value, derInteger2.Value, derInteger3.Value);
                            asymmetricKeyParameter = new DsaPrivateKeyParameters(derInteger5.Value, parameters);
                            publicParameter        = new DsaPublicKeyParameters(derInteger4.Value, parameters);
                        }
                    }
                    else
                    {
                        if (instance.Count != 9)
                        {
                            throw new PemException("malformed sequence in RSA private key");
                        }
                        RsaPrivateKeyStructure instance2 = RsaPrivateKeyStructure.GetInstance(instance);
                        publicParameter        = new RsaKeyParameters(false, instance2.Modulus, instance2.PublicExponent);
                        asymmetricKeyParameter = new RsaPrivateCrtKeyParameters(instance2.Modulus, instance2.PublicExponent, instance2.PrivateExponent, instance2.Prime1, instance2.Prime2, instance2.Exponent1, instance2.Exponent2, instance2.Coefficient);
                    }
                    result = new AsymmetricCipherKeyPair(publicParameter, asymmetricKeyParameter);
                    return(result);
                }
IL_356:
                throw new ArgumentException("Unknown key type: " + text, "type");
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (Exception ex2)
            {
                throw new PemException("problem creating " + text + " private key: " + ex2.ToString());
            }
            return(result);
        }
コード例 #13
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();
        }
コード例 #14
0
        internal static Dictionary <X509Certificate2, EncryptedPrivateKeyInfo> GetListFromDisk(IEnumerable <string> oids)
        {
            string[] paths;

            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Win32NT:
                paths = NpkiDiskPathOnWindows;
                break;

            case PlatformID.Unix:
                paths = NpkiDiskPathOnLinux;
                break;

            case PlatformID.MacOSX:
                paths = NpkiDiskPathOnMac;
                break;

            default:
                paths = new string[0];
                break;
            }

            var collection = new X509Certificate2Collection();
            var pathMap    = new Dictionary <X509Certificate2, DirectoryInfo>();

            foreach (var directoryPath in paths)
            {
                var directoryInfo = new DirectoryInfo(Environment.ExpandEnvironmentVariables(directoryPath));
                if (!directoryInfo.Exists)
                {
                    continue;
                }

                foreach (var fileInfo in directoryInfo.EnumerateFiles("*.der", SearchOption.AllDirectories))
                {
                    var certificate = new X509Certificate2(fileInfo.FullName);
                    pathMap[certificate] = fileInfo.Directory;
                    collection.Add(certificate);
                }
            }

            collection = collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);

            var certificates = new X509Certificate2Collection();

            foreach (var oid in oids)
            {
                certificates.AddRange(collection.Find(X509FindType.FindByCertificatePolicy, oid, false));
            }

            var list = new Dictionary <X509Certificate2, EncryptedPrivateKeyInfo>();

            foreach (var certificate in certificates)
            {
                foreach (var fileInfo in pathMap[certificate].EnumerateFiles("*.key", SearchOption.TopDirectoryOnly))
                {
                    var data = File.ReadAllBytes(fileInfo.FullName);
                    list[certificate] = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(data));
                    break;
                }
            }

            return(list);
        }
コード例 #15
0
        public override void PerformTest()
        {
            Pfx                 bag   = Pfx.GetInstance(pkcs12);
            ContentInfo         info  = bag.AuthSafe;
            MacData             mData = bag.MacData;
            DigestInfo          dInfo = mData.Mac;
            AlgorithmIdentifier algId = dInfo.AlgorithmID;

            byte[] salt    = mData.GetSalt();
            int    itCount = mData.IterationCount.IntValue;

            Asn1OctetString   content  = Asn1OctetString.GetInstance(info.Content);
            AuthenticatedSafe authSafe = AuthenticatedSafe.GetInstance(content.GetOctets());

            ContentInfo[] c = authSafe.GetContentInfo();

            //
            // private key section
            //
            if (!c[0].ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                Fail("Failed comparison data test");
            }

            Asn1OctetString authSafeContent = Asn1OctetString.GetInstance(c[0].Content);
            Asn1Sequence    seq             = Asn1Sequence.GetInstance(authSafeContent.GetOctets());

            SafeBag b = SafeBag.GetInstance(seq[0]);

            if (!b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
            {
                Fail("Failed comparison shroudedKeyBag test");
            }

            EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);

            encInfo = new EncryptedPrivateKeyInfo(encInfo.EncryptionAlgorithm, encInfo.GetEncryptedData());

            b = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, encInfo.ToAsn1Object(), b.BagAttributes);

            byte[] contentOctets = new DerSequence(b).GetEncoded();

            c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(contentOctets));

            //
            // certificates
            //
            if (!c[1].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData))
            {
                Fail("Failed comparison encryptedData test");
            }

            EncryptedData eData = EncryptedData.GetInstance(c[1].Content);

            c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, eData);

            //
            // create an octet stream to represent the BER encoding of authSafe
            //
            authSafe = new AuthenticatedSafe(c);

            contentOctets = authSafe.GetEncoded();

            info = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(contentOctets));

            mData = new MacData(new DigestInfo(algId, dInfo.GetDigest()), salt, itCount);

            bag = new Pfx(info, mData);

            //
            // comparison test
            //
            byte[] pfxEncoding = bag.GetEncoded();
            if (!Arrays.AreEqual(pfxEncoding, pkcs12))
            {
                Fail("Failed comparison test");
            }
        }
コード例 #16
0
 public void ShouldReturnValidResult()
 {
     Assert.DoesNotThrow(() => { EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(encryptedKey)); });
 }
コード例 #17
0
ファイル: PEMReader.cs プロジェクト: Arsslensoft/ALFX
        /**
         * Read a Key Pair
         */
        private object ReadPrivateKey(PemObject pemObject)
        {
            //
            // extract the key
            //
            Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY"));

            string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();

            byte[] keyBytes = pemObject.Content;

            IDictionary fields = Platform.CreateHashtable();

            foreach (PemHeader header in pemObject.Headers)
            {
                fields[header.Name] = header.Value;
            }

            string procType = (string)fields["Proc-Type"];

            if (procType == "4,ENCRYPTED")
            {
                if (pFinder == null)
                {
                    throw new PasswordException("No password finder specified, but a password is required");
                }

                char[] password = pFinder.GetPassword();

                if (password == null)
                {
                    throw new PasswordException("Password is null, but a password is required");
                }

                string   dekInfo = (string)fields["DEK-Info"];
                string[] tknz    = dekInfo.Split(',');

                string dekAlgName = tknz[0].Trim();
                byte[] iv         = Hex.Decode(tknz[1].Trim());

                keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
            }

            try
            {
                AsymmetricKeyParameter pubSpec, privSpec;
                Asn1Sequence           seq = (Asn1Sequence)Asn1Object.FromByteArray(keyBytes);

                switch (type)
                {
                case "RSA":
                {
                    if (seq.Count != 9)
                    {
                        throw new PemException("malformed sequence in RSA private key");
                    }

                    RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);

                    pubSpec  = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
                    privSpec = new RsaPrivateCrtKeyParameters(
                        rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                        rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                        rsa.Coefficient);

                    break;
                }

                case "DSA":
                {
                    if (seq.Count != 6)
                    {
                        throw new PemException("malformed sequence in DSA private key");
                    }

                    // TODO Create an ASN1 object somewhere for this?
                    //DerInteger v = (DerInteger)seq[0];
                    DerInteger p = (DerInteger)seq[1];
                    DerInteger q = (DerInteger)seq[2];
                    DerInteger g = (DerInteger)seq[3];
                    DerInteger y = (DerInteger)seq[4];
                    DerInteger x = (DerInteger)seq[5];

                    DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);

                    privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
                    pubSpec  = new DsaPublicKeyParameters(y.Value, parameters);

                    break;
                }

                case "EC":
                {
                    ECPrivateKeyStructure pKey  = new ECPrivateKeyStructure(seq);
                    AlgorithmIdentifier   algId = new AlgorithmIdentifier(
                        X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

                    PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());

                    // TODO Are the keys returned here ECDSA, as Java version forces?
                    privSpec = PrivateKeyFactory.CreateKey(privInfo);

                    DerBitString pubKey = pKey.GetPublicKey();
                    if (pubKey != null)
                    {
                        SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());

                        // TODO Are the keys returned here ECDSA, as Java version forces?
                        pubSpec = PublicKeyFactory.CreateKey(pubInfo);
                    }
                    else
                    {
                        pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey(
                            (ECPrivateKeyParameters)privSpec);
                    }

                    break;
                }

                case "ENCRYPTED":
                {
                    char[] password = pFinder.GetPassword();

                    if (password == null)
                    {
                        throw new PasswordException("Password is null, but a password is required");
                    }

                    return(PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq)));
                }

                case "":
                {
                    return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq)));
                }

                default:
                    throw new ArgumentException("Unknown key type: " + type, "type");
                }

                return(new AsymmetricCipherKeyPair(pubSpec, privSpec));
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new PemException(
                          "problem creating " + type + " private key: " + e.ToString());
            }
        }
コード例 #18
0
        public void ShouldEncryptUsingSha256WithAes256()
        {
            var encrpytedPrivateKeyInfo = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(encryptedKey));

            Assert.AreEqual(BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc.Id, encrpytedPrivateKeyInfo.EncryptionAlgorithm.Algorithm.Id);
        }
コード例 #19
0
        private void basicStoreTest(AsymmetricKeyEntry privKey, X509CertificateEntry[] chain,
                                    DerObjectIdentifier keyAlgorithm, DerObjectIdentifier certAlgorithm)
        {
            Pkcs12Store store = new Pkcs12StoreBuilder()
                                .SetKeyAlgorithm(keyAlgorithm)
                                .SetCertAlgorithm(certAlgorithm)
                                .Build();

            store.SetKeyEntry("key", privKey, chain);

            MemoryStream bOut = new MemoryStream();

            store.Save(bOut, passwd, new SecureRandom());

            store.Load(new MemoryStream(bOut.ToArray(), false), passwd);

            AsymmetricKeyEntry k = store.GetKey("key");

            if (!k.Equals(privKey))
            {
                Fail("private key didn't match");
            }

            X509CertificateEntry[] c = store.GetCertificateChain("key");

            if (c.Length != chain.Length || !c[0].Equals(chain[0]))
            {
                Fail("certificates didn't match");
            }

            // check attributes
            Pkcs12Entry b1 = k;
            Pkcs12Entry b2 = chain[0];

            if (b1[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] != null)
            {
                DerBmpString name = (DerBmpString)b1[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];

                if (!name.Equals(new DerBmpString("key")))
                {
                    Fail("friendly name wrong");
                }
            }
            else
            {
                Fail("no friendly name found on key");
            }

            if (b1[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] != null)
            {
                Asn1OctetString id = (Asn1OctetString)b1[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID];

                if (!id.Equals(b2[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID]))
                {
                    Fail("local key id mismatch");
                }
            }
            else
            {
                Fail("no local key id found");
            }

            //
            // check algorithm types.
            //
            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            Pfx pfx = new Pfx((Asn1Sequence)aIn.ReadObject());

            ContentInfo cInfo = pfx.AuthSafe;

            Asn1OctetString auth = (Asn1OctetString)cInfo.Content;

            aIn = new Asn1InputStream(auth.GetOctets());
            Asn1Sequence s1 = (Asn1Sequence)aIn.ReadObject();

            ContentInfo c1 = ContentInfo.GetInstance(s1[0]);
            ContentInfo c2 = ContentInfo.GetInstance(s1[1]);

            aIn = new Asn1InputStream(((Asn1OctetString)c1.Content).GetOctets());

            SafeBag sb = new SafeBag((Asn1Sequence)(((Asn1Sequence)aIn.ReadObject())[0]));

            EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(sb.BagValue);

            // check the key encryption
            if (!encInfo.EncryptionAlgorithm.Algorithm.Equals(keyAlgorithm))
            {
                Fail("key encryption algorithm wrong");
            }

            // check the certificate encryption
            EncryptedData cb = EncryptedData.GetInstance(c2.Content);

            if (!cb.EncryptionAlgorithm.Algorithm.Equals(certAlgorithm))
            {
                Fail("cert encryption algorithm wrong");
            }
        }
コード例 #20
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;
                    }
                }
            }
        }
コード例 #21
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;
                    }
                }
            }
        }
コード例 #22
0
        public void ShouldEncryptUsingPbe2ShaWith3Key3DesCbc()
        {
            var encrpytedPrivateKeyInfo = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(encryptedKey));

            Assert.AreEqual(PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc.Id, encrpytedPrivateKeyInfo.EncryptionAlgorithm.Algorithm.Id);
        }