Ejemplo n.º 1
0
        public static AsymmetricKeyParameter CreateKey(
            PrivateKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.PrivateKeyAlgorithm;
            DerObjectIdentifier algOid = algID.Algorithm;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());

                return(new RsaPrivateCrtKeyParameters(
                           keyStructure.Modulus,
                           keyStructure.PublicExponent,
                           keyStructure.PrivateExponent,
                           keyStructure.Prime1,
                           keyStructure.Prime2,
                           keyStructure.Exponent1,
                           keyStructure.Exponent2,
                           keyStructure.Coefficient));
            }
            // TODO?
            //			else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                BigInteger   lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                return(new ElGamalPrivateKeyParameters(
                           derX.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
            {
                DerInteger    derX = (DerInteger)keyInfo.ParsePrivateKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPrivateKeyParameters(derX.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = X962Parameters.GetInstance(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
                BigInteger            d  = ec.GetKey();

                if (para.IsNamedCurve)
                {
                    return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPrivateKeyParameters(d, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(
                    algID.Parameters.ToAsn1Object());

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key");
                }

                Asn1Object            privKey = keyInfo.ParsePrivateKey();
                ECPrivateKeyStructure ec;

                if (privKey is DerInteger)
                {
                    ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue);
                }
                else
                {
                    ec = ECPrivateKeyStructure.GetInstance(privKey);
                }

                return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);

                Asn1Object privKey = keyInfo.ParsePrivateKey();
                BigInteger x;

                if (privKey is DerInteger)
                {
                    x = DerInteger.GetInstance(privKey).PositiveValue;
                }
                else
                {
                    x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets()));
                }

                return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
            {
                return(new X25519PrivateKeyParameters(GetRawKey(keyInfo, X25519PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
            {
                return(new X448PrivateKeyParameters(GetRawKey(keyInfo, X448PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
            {
                return(new Ed25519PrivateKeyParameters(GetRawKey(keyInfo, Ed25519PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
            {
                return(new Ed448PrivateKeyParameters(GetRawKey(keyInfo, Ed448PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) ||
                     algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters);
                ECGost3410Parameters           ecSpec     = null;
                BigInteger d = null;
                Asn1Object p = keyInfo.PrivateKeyAlgorithm.Parameters.ToAsn1Object();
                if (p is Asn1Sequence && (Asn1Sequence.GetInstance(p).Count == 2 || Asn1Sequence.GetInstance(p).Count == 3))
                {
                    ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                    ecSpec = new ECGost3410Parameters(
                        new ECNamedDomainParameters(
                            gostParams.PublicKeyParamSet, ecP),
                        gostParams.PublicKeyParamSet,
                        gostParams.DigestParamSet,
                        gostParams.EncryptionParamSet);

                    Asn1OctetString privEnc = keyInfo.PrivateKeyData;
                    if (privEnc.GetOctets().Length == 32 || privEnc.GetOctets().Length == 64)
                    {
                        byte[] dVal = Arrays.Reverse(privEnc.GetOctets());
                        d = new BigInteger(1, dVal);
                    }
                    else
                    {
                        Asn1Encodable privKey = keyInfo.ParsePrivateKey();
                        if (privKey is DerInteger)
                        {
                            d = DerInteger.GetInstance(privKey).PositiveValue;
                        }
                        else
                        {
                            byte[] dVal = Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets());
                            d = new BigInteger(1, dVal);
                        }
                    }
                }
                else
                {
                    X962Parameters parameters = X962Parameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters);

                    if (parameters.IsNamedCurve)
                    {
                        DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(parameters.Parameters);
                        X9ECParameters      ecP = ECNamedCurveTable.GetByOid(oid);
                        if (ecP == null)
                        {
                            ECDomainParameters gParam = ECGost3410NamedCurves.GetByOid(oid);
                            ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(
                                                                  oid,
                                                                  gParam.Curve,
                                                                  gParam.G,
                                                                  gParam.N,
                                                                  gParam.H,
                                                                  gParam.GetSeed()), gostParams.PublicKeyParamSet, gostParams.DigestParamSet,
                                                              gostParams.EncryptionParamSet);
                        }
                        else
                        {
                            ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(
                                                                  oid,
                                                                  ecP.Curve,
                                                                  ecP.G,
                                                                  ecP.N,
                                                                  ecP.H,
                                                                  ecP.GetSeed()), gostParams.PublicKeyParamSet, gostParams.DigestParamSet,
                                                              gostParams.EncryptionParamSet);
                        }
                    }
                    else if (parameters.IsImplicitlyCA)
                    {
                        ecSpec = null;
                    }
                    else
                    {
                        X9ECParameters ecP = X9ECParameters.GetInstance(parameters.Parameters);
                        ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(
                                                              algOid,
                                                              ecP.Curve,
                                                              ecP.G,
                                                              ecP.N,
                                                              ecP.H,
                                                              ecP.GetSeed()),
                                                          gostParams.PublicKeyParamSet,
                                                          gostParams.DigestParamSet,
                                                          gostParams.EncryptionParamSet);
                    }

                    Asn1Encodable privKey = keyInfo.ParsePrivateKey();
                    if (privKey is DerInteger)
                    {
                        DerInteger derD = DerInteger.GetInstance(privKey);
                        d = derD.Value;
                    }
                    else
                    {
                        ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(privKey);
                        d = ec.GetKey();
                    }
                }

                return(new ECPrivateKeyParameters(
                           d,
                           new ECGost3410Parameters(
                               ecSpec,
                               gostParams.PublicKeyParamSet,
                               gostParams.DigestParamSet,
                               gostParams.EncryptionParamSet)));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in private key not recognised");
            }
        }
Ejemplo n.º 2
0
        public X9Curve(
            X9FieldID fieldID,
            BigInteger order,
            BigInteger cofactor,
            Asn1Sequence seq)
        {
            if (fieldID == null)
            {
                throw new ArgumentNullException("fieldID");
            }
            if (seq == null)
            {
                throw new ArgumentNullException("seq");
            }

            this.fieldIdentifier = fieldID.Identifier;

            if (fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
            {
                BigInteger p = ((DerInteger)fieldID.Parameters).Value;
                BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets());
                BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets());
                curve = new FpCurve(p, A, B, order, cofactor);
            }
            else if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
            {
                // Characteristic two field
                DerSequence         parameters     = (DerSequence)fieldID.Parameters;
                int                 m              = ((DerInteger)parameters[0]).IntValueExact;
                DerObjectIdentifier representation = (DerObjectIdentifier)parameters[1];

                int k1 = 0;
                int k2 = 0;
                int k3 = 0;
                if (representation.Equals(X9ObjectIdentifiers.TPBasis))
                {
                    // Trinomial basis representation
                    k1 = ((DerInteger)parameters[2]).IntValueExact;
                }
                else
                {
                    // Pentanomial basis representation
                    DerSequence pentanomial = (DerSequence)parameters[2];
                    k1 = ((DerInteger)pentanomial[0]).IntValueExact;
                    k2 = ((DerInteger)pentanomial[1]).IntValueExact;
                    k3 = ((DerInteger)pentanomial[2]).IntValueExact;
                }
                BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets());
                BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets());
                curve = new F2mCurve(m, k1, k2, k3, A, B, order, cofactor);
            }
            else
            {
                throw new ArgumentException("This type of ECCurve is not implemented");
            }

            if (seq.Count == 3)
            {
                seed = ((DerBitString)seq[2]).GetBytes();
            }
        }
Ejemplo n.º 3
0
        public static AsymmetricKeyParameter CreateKey(
            PrivateKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.PrivateKeyAlgorithm;
            DerObjectIdentifier algOid = algID.Algorithm;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());

                return(new RsaPrivateCrtKeyParameters(
                           keyStructure.Modulus,
                           keyStructure.PublicExponent,
                           keyStructure.PrivateExponent,
                           keyStructure.Prime1,
                           keyStructure.Prime2,
                           keyStructure.Exponent1,
                           keyStructure.Exponent2,
                           keyStructure.Coefficient));
            }
            // TODO?
//			else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                BigInteger   lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                return(new ElGamalPrivateKeyParameters(
                           derX.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
            {
                DerInteger    derX = (DerInteger)keyInfo.ParsePrivateKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPrivateKeyParameters(derX.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
                BigInteger            d  = ec.GetKey();

                if (para.IsNamedCurve)
                {
                    return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPrivateKeyParameters(d, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key");
                }

                Asn1Object            privKey = keyInfo.ParsePrivateKey();
                ECPrivateKeyStructure ec;

                if (privKey is DerInteger)
                {
                    ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue);
                }
                else
                {
                    ec = ECPrivateKeyStructure.GetInstance(privKey);
                }

                return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);

                Asn1Object privKey = keyInfo.ParsePrivateKey();
                BigInteger x;

                if (privKey is DerInteger)
                {
                    x = DerInteger.GetInstance(privKey).PositiveValue;
                }
                else
                {
                    x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets()));
                }

                return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised");
            }
        }
Ejemplo n.º 4
0
        /**
         * Gets a String from an ASN1Primitive
         * @param names the ASN1Primitive
         * @return  a human-readable String
         * @throws IOException
         */
        private static String GetStringFromGeneralName(Asn1Object names)
        {
            Asn1TaggedObject taggedObject = (Asn1TaggedObject)names;

            return(Encoding.GetEncoding(1252).GetString(Asn1OctetString.GetInstance(taggedObject, false).GetOctets()));
        }
 public static SubjectKeyIdentifier GetInstance(
     Asn1TaggedObject obj,
     bool explicitly)
 {
     return(GetInstance(Asn1OctetString.GetInstance(obj, explicitly)));
 }
Ejemplo n.º 6
0
        private static global::System.Collections.ICollection GetAlternativeName(Asn1OctetString extVal)
        {
            //IL_010c: Unknown result type (might be due to invalid IL or missing references)
            global::System.Collections.IList list = Platform.CreateArrayList();
            if (extVal != null)
            {
                try
                {
                    Asn1Sequence instance = Asn1Sequence.GetInstance(FromExtensionValue(extVal));
                    global::System.Collections.IEnumerator enumerator = instance.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            GeneralName generalName = (GeneralName)enumerator.get_Current();
                            global::System.Collections.IList list2 = Platform.CreateArrayList();
                            list2.Add((object)generalName.TagNo);
                            switch (generalName.TagNo)
                            {
                            case 0:
                            case 3:
                            case 5:
                                list2.Add((object)generalName.Name.ToAsn1Object());
                                break;

                            case 4:
                                list2.Add((object)X509Name.GetInstance(generalName.Name).ToString());
                                break;

                            case 1:
                            case 2:
                            case 6:
                                list2.Add((object)((IAsn1String)generalName.Name).GetString());
                                break;

                            case 8:
                                list2.Add((object)DerObjectIdentifier.GetInstance(generalName.Name).Id);
                                break;

                            case 7:
                                list2.Add((object)Asn1OctetString.GetInstance(generalName.Name).GetOctets());
                                break;

                            default:
                                throw new IOException(string.Concat((object)"Bad tag number: ", (object)generalName.TagNo));
                            }
                            list.Add((object)list2);
                        }
                        return((global::System.Collections.ICollection)list);
                    }
                    finally
                    {
                        global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                catch (global::System.Exception ex)
                {
                    throw new CertificateParsingException(ex.get_Message());
                }
            }
            return((global::System.Collections.ICollection)list);
        }
 public static byte[] ExtractSignerId(this SignerID selector)
 {
     //In case of SignerID it seems to be the encoded Octet String (bug?)
     return(Asn1OctetString.GetInstance(DerOctetString.FromByteArray(selector.SubjectKeyIdentifier)).GetOctets());
 }
Ejemplo n.º 8
0
        public static ICipherParameters GenerateCipherParameters(string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters)
        {
            string text = (string)algorithms.get_Item((object)Platform.ToUpperInvariant(algorithm));

            byte[] array          = null;
            byte[] salt           = null;
            int    iterationCount = 0;

            if (IsPkcs12(text))
            {
                Pkcs12PbeParams instance = Pkcs12PbeParams.GetInstance(pbeParameters);
                salt           = instance.GetIV();
                iterationCount = instance.Iterations.IntValue;
                array          = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
            }
            else if (!IsPkcs5Scheme2(text))
            {
                PbeParameter instance2 = PbeParameter.GetInstance(pbeParameters);
                salt           = instance2.GetSalt();
                iterationCount = instance2.IterationCount.IntValue;
                array          = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }
            ICipherParameters parameters = null;

            if (IsPkcs5Scheme2(text))
            {
                PbeS2Parameters     instance3        = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
                AlgorithmIdentifier encryptionScheme = instance3.EncryptionScheme;
                DerObjectIdentifier algorithm2       = encryptionScheme.Algorithm;
                Asn1Object          obj       = encryptionScheme.Parameters.ToAsn1Object();
                Pbkdf2Params        instance4 = Pbkdf2Params.GetInstance(instance3.KeyDerivationFunc.Parameters.ToAsn1Object());
                byte[] array2;
                if (algorithm2.Equals(PkcsObjectIdentifiers.RC2Cbc))
                {
                    RC2CbcParameter instance5 = RC2CbcParameter.GetInstance(obj);
                    array2 = instance5.GetIV();
                }
                else
                {
                    array2 = Asn1OctetString.GetInstance(obj).GetOctets();
                }
                salt           = instance4.GetSalt();
                iterationCount = instance4.IterationCount.IntValue;
                array          = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
                int keySize = ((instance4.KeyLength != null) ? (instance4.KeyLength.IntValue * 8) : GeneratorUtilities.GetDefaultKeySize(algorithm2));
                PbeParametersGenerator pbeParametersGenerator = MakePbeGenerator((string)algorithmType.get_Item((object)text), null, array, salt, iterationCount);
                parameters = pbeParametersGenerator.GenerateDerivedParameters(algorithm2.Id, keySize);
                if (array2 != null && !Arrays.AreEqual(array2, new byte[array2.Length]))
                {
                    parameters = new ParametersWithIV(parameters, array2);
                }
            }
            else if (Platform.StartsWith(text, "PBEwithSHA-1"))
            {
                PbeParametersGenerator pbeParametersGenerator2 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new Sha1Digest(), array, salt, iterationCount);
                if (text.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (text.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (text.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 256, 128);
                }
                else if (text.Equals("PBEwithSHA-1and128bitRC4"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 128);
                }
                else if (text.Equals("PBEwithSHA-1and40bitRC4"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 40);
                }
                else if (text.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 192, 64);
                }
                else if (text.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 128, 64);
                }
                else if (text.Equals("PBEwithSHA-1and128bitRC2-CBC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 128, 64);
                }
                else if (text.Equals("PBEwithSHA-1and40bitRC2-CBC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 40, 64);
                }
                else if (text.Equals("PBEwithSHA-1andDES-CBC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (text.Equals("PBEwithSHA-1andRC2-CBC"))
                {
                    parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (Platform.StartsWith(text, "PBEwithSHA-256"))
            {
                PbeParametersGenerator pbeParametersGenerator3 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new Sha256Digest(), array, salt, iterationCount);
                if (text.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
                {
                    parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (text.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
                {
                    parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (text.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
                {
                    parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (Platform.StartsWith(text, "PBEwithMD5"))
            {
                PbeParametersGenerator pbeParametersGenerator4 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new MD5Digest(), array, salt, iterationCount);
                if (text.Equals("PBEwithMD5andDES-CBC"))
                {
                    parameters = pbeParametersGenerator4.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (text.Equals("PBEwithMD5andRC2-CBC"))
                {
                    parameters = pbeParametersGenerator4.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (text.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
                {
                    parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (text.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
                {
                    parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (text.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
                {
                    parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (Platform.StartsWith(text, "PBEwithMD2"))
            {
                PbeParametersGenerator pbeParametersGenerator5 = MakePbeGenerator((string)algorithmType.get_Item((object)text), new MD2Digest(), array, salt, iterationCount);
                if (text.Equals("PBEwithMD2andDES-CBC"))
                {
                    parameters = pbeParametersGenerator5.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (text.Equals("PBEwithMD2andRC2-CBC"))
                {
                    parameters = pbeParametersGenerator5.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (Platform.StartsWith(text, "PBEwithHmac"))
            {
                string  algorithm3 = text.Substring("PBEwithHmac".get_Length());
                IDigest digest     = DigestUtilities.GetDigest(algorithm3);
                PbeParametersGenerator pbeParametersGenerator6 = MakePbeGenerator((string)algorithmType.get_Item((object)text), digest, array, salt, iterationCount);
                int keySize2 = digest.GetDigestSize() * 8;
                parameters = pbeParametersGenerator6.GenerateDerivedMacParameters(keySize2);
            }
            global::System.Array.Clear((global::System.Array)array, 0, array.Length);
            return(FixDesParity(text, parameters));
        }
Ejemplo n.º 9
0
    private ProfessionInfo(Asn1Sequence seq)
    {
        if (seq.Count > 5)
        {
            throw new ArgumentException("Bad sequence size: " + seq.Count);
        }
        IEnumerator enumerator = seq.GetEnumerator();

        enumerator.MoveNext();
        Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.Current;

        if (asn1Encodable is Asn1TaggedObject)
        {
            Asn1TaggedObject asn1TaggedObject = (Asn1TaggedObject)asn1Encodable;
            if (asn1TaggedObject.TagNo != 0)
            {
                throw new ArgumentException("Bad tag number: " + asn1TaggedObject.TagNo);
            }
            namingAuthority = NamingAuthority.GetInstance(asn1TaggedObject, isExplicit: true);
            enumerator.MoveNext();
            asn1Encodable = (Asn1Encodable)enumerator.Current;
        }
        professionItems = Asn1Sequence.GetInstance(asn1Encodable);
        if (enumerator.MoveNext())
        {
            asn1Encodable = (Asn1Encodable)enumerator.Current;
            if (asn1Encodable is Asn1Sequence)
            {
                professionOids = Asn1Sequence.GetInstance(asn1Encodable);
            }
            else if (asn1Encodable is DerPrintableString)
            {
                registrationNumber = DerPrintableString.GetInstance(asn1Encodable).GetString();
            }
            else
            {
                if (!(asn1Encodable is Asn1OctetString))
                {
                    throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(asn1Encodable));
                }
                addProfessionInfo = Asn1OctetString.GetInstance(asn1Encodable);
            }
        }
        if (enumerator.MoveNext())
        {
            asn1Encodable = (Asn1Encodable)enumerator.Current;
            if (asn1Encodable is DerPrintableString)
            {
                registrationNumber = DerPrintableString.GetInstance(asn1Encodable).GetString();
            }
            else
            {
                if (!(asn1Encodable is DerOctetString))
                {
                    throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(asn1Encodable));
                }
                addProfessionInfo = (DerOctetString)asn1Encodable;
            }
        }
        if (enumerator.MoveNext())
        {
            asn1Encodable = (Asn1Encodable)enumerator.Current;
            if (!(asn1Encodable is DerOctetString))
            {
                throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(asn1Encodable));
            }
            addProfessionInfo = (DerOctetString)asn1Encodable;
        }
    }
Ejemplo n.º 10
0
 private static byte[] GetRawKey(PrivateKeyInfo keyInfo)
 {
     return(Asn1OctetString.GetInstance(keyInfo.ParsePrivateKey()).GetOctets());
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Constructor from an algorithm and a PrivateKeyInfo object containing a NewHope private key.
 /// </summary>
 /// <param name="algorithm">Algorithm marker to associate with the key.</param>
 /// <param name="privateKeyInfo">A PrivateKeyInfo object.</param>
 public AsymmetricNHPrivateKey(Algorithm algorithm, PrivateKeyInfo privateKeyInfo) : base(algorithm)
 {
     this.privateKeyData = Convert(Asn1OctetString.GetInstance(privateKeyInfo.ParsePrivateKey()).GetOctets());
 }
        /// <summary>
        /// Qualification of extension by type
        /// </summary>
        /// <param name="asn1Encodable"></param>
        /// <returns></returns>
        private System.Security.Cryptography.X509Certificates.X509Extension QualificationExtension(Asn1Encodable asn1Encodable)
        {
            Asn1Sequence s = Asn1Sequence.GetInstance(asn1Encodable.ToAsn1Object());

            if (s.Count < 2 || s.Count > 3)
            {
                throw new ArgumentException("Bad sequence size: " + s.Count);
            }

            DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object());

            bool isCritical = s.Count == 3 &&
                              DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue;

            Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object());

            var extension = new System.Security.Cryptography.X509Certificates.X509Extension(new Oid(oid.Id), octets.GetOctets(), isCritical);

            var value = Asn1Object.FromByteArray(octets.GetOctets());

            switch (extension.Oid.Value)
            {
            case OidExtensions.SubjectKeyIdentifier:
                var spki = Asn1OctetString.GetInstance(value).GetOctets();
                extension = new X509SubjectKeyIdentifierExtension(spki, isCritical);
                break;

            case OidExtensions.ExtKeyUsage:
                var bcEKU           = ExtendedKeyUsage.GetInstance(value);
                var collectionFlags = new OidCollection();
                foreach (DerObjectIdentifier item in bcEKU.GetAllUsages())
                {
                    collectionFlags.Add(new Oid(item.Id));
                }
                extension = new X509EnhancedKeyUsageExtension(collectionFlags, isCritical);
                break;

            case OidExtensions.KeyUsage:
                var    bitString = DerBitString.GetInstance(value);
                byte[] data      = bitString.GetBytes();
                var    keyUsage  = data.Length == 1
                        ? data[0] & 0xff
                        : (data[1] & 0xff) << 8 | (data[0] & 0xff);
                extension = new X509KeyUsageExtension((X509KeyUsageFlags)keyUsage, isCritical);
                break;

            case OidExtensions.BasicConstraints:
                var bcBC = BasicConstraints.GetInstance(value);
                extension = new X509BasicConstraintsExtension(bcBC.IsCA(), true, bcBC.PathLenConstraint.IntValue, isCritical);
                break;

            case OidExtensions.TemplateV2:
                extension = new X509TemplateExtensionV2(octets.GetOctets(), isCritical);
                break;

            case OidExtensions.TemplateV1:
                extension = new X509TemplateExtensionV1(octets.GetOctets(), isCritical);
                break;

            default:
                break;
            }
            return(extension);
        }
        private static ICollection GetAlternativeName(Asn1OctetString extVal)
        {
            IList list = Platform.CreateArrayList();

            if (extVal != null)
            {
                try
                {
                    IEnumerator enumerator = Asn1Sequence.GetInstance(FromExtensionValue(extVal)).GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            GeneralName current = (GeneralName)enumerator.Current;
                            IList       list2   = Platform.CreateArrayList();
                            list2.Add(current.TagNo);
                            switch (current.TagNo)
                            {
                            case 0:
                            case 3:
                            case 5:
                                list2.Add(current.Name.ToAsn1Object());
                                break;

                            case 1:
                            case 2:
                            case 6:
                                list2.Add(((IAsn1String)current.Name).GetString());
                                break;

                            case 4:
                                list2.Add(X509Name.GetInstance(current.Name).ToString());
                                break;

                            case 7:
                                list2.Add(Asn1OctetString.GetInstance(current.Name).GetOctets());
                                break;

                            case 8:
                                list2.Add(DerObjectIdentifier.GetInstance(current.Name).Id);
                                break;

                            default:
                                throw new IOException("Bad tag number: " + current.TagNo);
                            }
                            list.Add(list2);
                        }
                    }
                    finally
                    {
                        if (enumerator is IDisposable disposable)
                        {
                            IDisposable disposable;
                            disposable.Dispose();
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new CertificateParsingException(exception.Message);
                }
            }
            return(list);
        }
 /// <summary>
 /// Constructor from an algorithm and a PrivateKeyInfo object containing a SPHINCS private key.
 /// </summary>
 /// <param name="algorithm">Algorithm marker to associate with the key.</param>
 /// <param name="privateKeyInfo">A PrivateKeyInfo object.</param>
 public AsymmetricSphincsPrivateKey(Algorithm algorithm, PrivateKeyInfo privateKeyInfo)
     : base(algorithm, privateKeyInfo.PrivateKeyAlgorithm)
 {
     this.keyData = Arrays.Clone(Asn1OctetString.GetInstance(privateKeyInfo.ParsePrivateKey()).GetOctets());
 }
Ejemplo n.º 15
0
        public void Load(
            Stream input,
            char[]      password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

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

            if (bag.MacData != null) // check the mac code
            {
                if (password == null)
                {
                    throw new ArgumentNullException("password", "no password supplied when one expected");
                }

                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = Asn1OctetString.GetInstance(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;
                }
            }
            else if (password != null)
            {
                string ignoreProperty = Platform.GetEnvironmentVariable(IgnoreUselessPasswordProperty);
                bool   ignore         = ignoreProperty != null && Platform.EqualsIgnoreCase("true", ignoreProperty);

                if (!ignore)
                {
                    throw new IOException("password supplied for keystore that does not require one");
                }
            }

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

            IList certBags = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                Asn1OctetString   content  = Asn1OctetString.GetInstance(info.Content);
                AuthenticatedSafe authSafe = AuthenticatedSafe.GetInstance(content.GetOctets());
                ContentInfo[]     cis      = authSafe.GetContentInfo();

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

                    byte[] octets = null;
                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        octets = Asn1OctetString.GetInstance(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.GetInstance(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
                    {
                        keys["unmarked"] = 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;
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];

            byte[] keyBytes       = null;
            byte[] salt           = null;
            int    iterationCount = 0;

            if (IsPkcs12(mechanism))
            {
                Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters);
                salt           = pbeParams.GetIV();
                iterationCount = pbeParams.Iterations.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
            }
            else if (IsPkcs5Scheme2(mechanism))
            {
                // See below
            }
            else
            {
                PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters);
                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }

            ICipherParameters parameters = null;

            if (IsPkcs5Scheme2(mechanism))
            {
                PbeS2Parameters     s2p       = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
                AlgorithmIdentifier encScheme = s2p.EncryptionScheme;
                DerObjectIdentifier encOid    = encScheme.ObjectID;
                Asn1Object          encParams = encScheme.Parameters.ToAsn1Object();

                // TODO What about s2p.KeyDerivationFunc.ObjectID?
                Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object());

                byte[] iv;
                if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc))                 // PKCS5.B.2.3
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = Asn1OctetString.GetInstance(encParams).GetOctets();
                }

                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);

                int keyLength = pbeParams.KeyLength != null
                                        ?       pbeParams.KeyLength.IntValue * 8
                                        :       GeneratorUtilities.GetDefaultKeySize(encOid);

                PbeParametersGenerator gen = MakePbeGenerator(
                    (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount);

                parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength);

                if (iv != null)
                {
                    // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?)
                    if (Arrays.AreEqual(iv, new byte[iv.Length]))
                    {
                        //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****");
                    }
                    else
                    {
                        parameters = new ParametersWithIV(parameters, iv);
                    }
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-1"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-1and128bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 40);
                }
                else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 40, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-256"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD5"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithMD5andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD2"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount);
                if (mechanism.Equals("PBEwithMD2andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD2andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (mechanism.StartsWith("PBEwithHmac"))
            {
                string  digestName = mechanism.Substring("PBEwithHmac".Length);
                IDigest digest     = DigestUtilities.GetDigest(digestName);

                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount);

                int bitLen = digest.GetDigestSize() * 8;
                parameters = generator.GenerateDerivedMacParameters(bitLen);
            }

            Array.Clear(keyBytes, 0, keyBytes.Length);

            return(FixDesParity(mechanism, parameters));
        }
Ejemplo n.º 17
0
        public static object CreateContentCipher(bool forEncryption, ICipherParameters encKey,
                                                 AlgorithmIdentifier encryptionAlgID)
        {
            DerObjectIdentifier encAlg = encryptionAlgID.Algorithm;

            if (encAlg.Equals(PkcsObjectIdentifiers.rc4))
            {
                IStreamCipher cipher = new RC4Engine();
                cipher.Init(forEncryption, encKey);
                return(cipher);
            }
            else
            {
                BufferedBlockCipher cipher  = CreateCipher(encryptionAlgID.Algorithm);
                Asn1Object          sParams = encryptionAlgID.Parameters.ToAsn1Object();

                if (sParams != null && !(sParams is DerNull))
                {
                    if (encAlg.Equals(PkcsObjectIdentifiers.DesEde3Cbc) ||
                        encAlg.Equals(AlgorithmIdentifierFactory.IDEA_CBC) ||
                        encAlg.Equals(NistObjectIdentifiers.IdAes128Cbc) ||
                        encAlg.Equals(NistObjectIdentifiers.IdAes192Cbc) ||
                        encAlg.Equals(NistObjectIdentifiers.IdAes256Cbc) ||
                        encAlg.Equals(NttObjectIdentifiers.IdCamellia128Cbc) ||
                        encAlg.Equals(NttObjectIdentifiers.IdCamellia192Cbc) ||
                        encAlg.Equals(NttObjectIdentifiers.IdCamellia256Cbc) ||
                        encAlg.Equals(KisaObjectIdentifiers.IdSeedCbc) ||
                        encAlg.Equals(OiwObjectIdentifiers.DesCbc))
                    {
                        cipher.Init(forEncryption, new ParametersWithIV(encKey,
                                                                        Asn1OctetString.GetInstance(sParams).GetOctets()));
                    }
                    else if (encAlg.Equals(AlgorithmIdentifierFactory.CAST5_CBC))
                    {
                        Cast5CbcParameters cbcParams = Cast5CbcParameters.GetInstance(sParams);

                        cipher.Init(forEncryption, new ParametersWithIV(encKey, cbcParams.GetIV()));
                    }
                    else if (encAlg.Equals(PkcsObjectIdentifiers.RC2Cbc))
                    {
                        RC2CbcParameter cbcParams = RC2CbcParameter.GetInstance(sParams);

                        cipher.Init(forEncryption, new ParametersWithIV(new RC2Parameters(((KeyParameter)encKey).GetKey(), rc2Ekb[cbcParams.RC2ParameterVersion.IntValue]), cbcParams.GetIV()));
                    }
                    else
                    {
                        throw new InvalidOperationException("cannot match parameters");
                    }
                }
                else
                {
                    if (encAlg.Equals(PkcsObjectIdentifiers.DesEde3Cbc) ||
                        encAlg.Equals(AlgorithmIdentifierFactory.IDEA_CBC) ||
                        encAlg.Equals(AlgorithmIdentifierFactory.CAST5_CBC))
                    {
                        cipher.Init(forEncryption, new ParametersWithIV(encKey, new byte[8]));
                    }
                    else
                    {
                        cipher.Init(forEncryption, encKey);
                    }
                }

                return(cipher);
            }
        }
        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");
            }
        }
Ejemplo n.º 19
0
        internal static List <SignedCertificateTimestamp> GetSignedCertificateTimestamps(this X509Certificate2 certificate)
        {
            // https://letsencrypt.org/2018/04/04/sct-encoding.html

            var result = new List <SignedCertificateTimestamp>();

#if DEBUG
            var sctExtension = certificate is MoqX509Certificate2 moqCert
                ? moqCert.Extensions
                               .OfType <X509Extension>()
                               .FirstOrDefault(i => i.Oid.Value.Equals(Constants.SctCertificateOid))
                : certificate.GetExtension(Constants.SctCertificateOid);
#else
            var sctExtension = certificate.GetExtension(Constants.SctCertificateOid);
#endif
            if (sctExtension?.RawData?.Any() == true)
            {
                var octets = Asn1OctetString.GetInstance(sctExtension.RawData).GetOctets();
                // could be a nested OCTET string, check leading byte
                var derOctetString = octets[0] == 0x04
                    ? Asn1Object.FromByteArray(octets) as DerOctetString
                    : Asn1Object.FromByteArray(sctExtension.RawData) as DerOctetString;

                using var inputStream = derOctetString.GetOctetStream();

                TlsUtilities.ReadUint16(inputStream);

                while (inputStream.Length - inputStream.Position > 2)
                {
                    var sctBytes = TlsUtilities.ReadOpaque16(inputStream);

                    using var sctStream = new MemoryStream(sctBytes);

                    var version = (SctVersion)sctStream.ReadByte();
                    if (version != SctVersion.V1)
                    {
                        throw new NotSupportedException(UnknowError(nameof(SctVersion), version));
                    }

                    var keyId = new byte[Constants.KeyIdLength];
                    sctStream.Read(keyId, 0, keyId.Length);

                    var timestamp = sctStream.ReadLong(Constants.TimestampLength);

                    var extensions = sctStream.ReadVariableLength(Constants.ExtensionsMaxLength);

                    var hashAlgo = (CtHashAlgorithm)sctStream.ReadByte();
                    if (!Enum.IsDefined(typeof(CtHashAlgorithm), hashAlgo))
                    {
                        throw new NotSupportedException(UnknowError(nameof(CtHashAlgorithm), hashAlgo));
                    }

                    var signatureAlgo = (CtSignatureAlgorithm)sctStream.ReadByte();
                    if (!Enum.IsDefined(typeof(CtSignatureAlgorithm), signatureAlgo))
                    {
                        throw new NotSupportedException(UnknowError(nameof(CtSignatureAlgorithm), signatureAlgo));
                    }

                    var signature = sctStream.ReadVariableLength(Constants.SignatureMaxLength);

                    var digitallySigned = new DigitallySigned()
                    {
                        Hash          = hashAlgo,
                        Signature     = signatureAlgo,
                        SignatureData = signature
                    };

                    var sct = new SignedCertificateTimestamp()
                    {
                        SctVersion  = version,
                        LogId       = keyId,
                        TimestampMs = timestamp,
                        Extensions  = extensions,
                        Signature   = digitallySigned
                    };

                    result.Add(sct);
                }
            }

            return(result);
        }
Ejemplo n.º 20
0
        /**
         * Constructor from Asn1Sequence.
         * <p/>
         * <p/>
         * <pre>
         *               ProfessionInfo ::= SEQUENCE
         *               {
         *                 namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
         *                 professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
         *                 professionOids SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
         *                 registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
         *                 addProfessionInfo OCTET STRING OPTIONAL
         *               }
         * </pre>
         *
         * @param seq The ASN.1 sequence.
         */
        private ProfessionInfo(
            Asn1Sequence seq)
        {
            if (seq.Count > 5)
            {
                throw new ArgumentException("Bad sequence size: " + seq.Count);
            }

            IEnumerator e = seq.GetEnumerator();

            e.MoveNext();
            Asn1Encodable o = (Asn1Encodable)e.Current;

            if (o is Asn1TaggedObject)
            {
                Asn1TaggedObject ato = (Asn1TaggedObject)o;
                if (ato.TagNo != 0)
                {
                    throw new ArgumentException("Bad tag number: " + ato.TagNo);
                }

                namingAuthority = NamingAuthority.GetInstance(ato, true);
                e.MoveNext();
                o = (Asn1Encodable)e.Current;
            }

            professionItems = Asn1Sequence.GetInstance(o);

            if (e.MoveNext())
            {
                o = (Asn1Encodable)e.Current;
                if (o is Asn1Sequence)
                {
                    professionOids = Asn1Sequence.GetInstance(o);
                }
                else if (o is DerPrintableString)
                {
                    registrationNumber = DerPrintableString.GetInstance(o).GetString();
                }
                else if (o is Asn1OctetString)
                {
                    addProfessionInfo = Asn1OctetString.GetInstance(o);
                }
                else
                {
                    throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o));
                }
            }

            if (e.MoveNext())
            {
                o = (Asn1Encodable)e.Current;
                if (o is DerPrintableString)
                {
                    registrationNumber = DerPrintableString.GetInstance(o).GetString();
                }
                else if (o is DerOctetString)
                {
                    addProfessionInfo = (DerOctetString)o;
                }
                else
                {
                    throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o));
                }
            }

            if (e.MoveNext())
            {
                o = (Asn1Encodable)e.Current;
                if (o is DerOctetString)
                {
                    addProfessionInfo = (DerOctetString)o;
                }
                else
                {
                    throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o));
                }
            }
        }
Ejemplo n.º 21
0
        private ProfessionInfo(Asn1Sequence seq)
        {
            //IL_0024: Unknown result type (might be due to invalid IL or missing references)
            //IL_0070: Unknown result type (might be due to invalid IL or missing references)
            //IL_010d: Unknown result type (might be due to invalid IL or missing references)
            //IL_0168: Unknown result type (might be due to invalid IL or missing references)
            //IL_01a7: Unknown result type (might be due to invalid IL or missing references)
            if (seq.Count > 5)
            {
                throw new ArgumentException(string.Concat((object)"Bad sequence size: ", (object)seq.Count));
            }
            global::System.Collections.IEnumerator enumerator = seq.GetEnumerator();
            enumerator.MoveNext();
            Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.get_Current();

            if (asn1Encodable is Asn1TaggedObject)
            {
                Asn1TaggedObject asn1TaggedObject = (Asn1TaggedObject)asn1Encodable;
                if (asn1TaggedObject.TagNo != 0)
                {
                    throw new ArgumentException(string.Concat((object)"Bad tag number: ", (object)asn1TaggedObject.TagNo));
                }
                namingAuthority = NamingAuthority.GetInstance(asn1TaggedObject, isExplicit: true);
                enumerator.MoveNext();
                asn1Encodable = (Asn1Encodable)enumerator.get_Current();
            }
            professionItems = Asn1Sequence.GetInstance(asn1Encodable);
            if (enumerator.MoveNext())
            {
                asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                if (asn1Encodable is Asn1Sequence)
                {
                    professionOids = Asn1Sequence.GetInstance(asn1Encodable);
                }
                else if (asn1Encodable is DerPrintableString)
                {
                    registrationNumber = DerPrintableString.GetInstance(asn1Encodable).GetString();
                }
                else
                {
                    if (!(asn1Encodable is Asn1OctetString))
                    {
                        throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(asn1Encodable));
                    }
                    addProfessionInfo = Asn1OctetString.GetInstance(asn1Encodable);
                }
            }
            if (enumerator.MoveNext())
            {
                asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                if (asn1Encodable is DerPrintableString)
                {
                    registrationNumber = DerPrintableString.GetInstance(asn1Encodable).GetString();
                }
                else
                {
                    if (!(asn1Encodable is DerOctetString))
                    {
                        throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(asn1Encodable));
                    }
                    addProfessionInfo = (DerOctetString)asn1Encodable;
                }
            }
            if (enumerator.MoveNext())
            {
                asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                if (!(asn1Encodable is DerOctetString))
                {
                    throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(asn1Encodable));
                }
                addProfessionInfo = (DerOctetString)asn1Encodable;
            }
        }