Beispiel #1
0
        public void AddPasswordRecipient(
            CmsPbeKey pbeKey,
            string kekAlgorithmOid)
        {
            Pbkdf2Params p         = new Pbkdf2Params(pbeKey.Salt, pbeKey.IterationCount);
            KeyParameter secretKey = pbeKey.GetEncoded(kekAlgorithmOid);

            recipientInfs.Add(new RecipientInf(kekAlgorithmOid, secretKey, new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbkdf2, p)));
        }
Beispiel #2
0
    public void AddPasswordRecipient(CmsPbeKey pbeKey, string kekAlgorithmOid)
    {
        Pbkdf2Params parameters = new Pbkdf2Params(pbeKey.Salt, pbeKey.IterationCount);
        PasswordRecipientInfoGenerator passwordRecipientInfoGenerator = new PasswordRecipientInfoGenerator();

        passwordRecipientInfoGenerator.KeyDerivationAlgorithm = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbkdf2, parameters);
        passwordRecipientInfoGenerator.KeyEncryptionKeyOID    = kekAlgorithmOid;
        passwordRecipientInfoGenerator.KeyEncryptionKey       = pbeKey.GetEncoded(kekAlgorithmOid);
        recipientInfoGenerators.Add(passwordRecipientInfoGenerator);
    }
Beispiel #3
0
        public CmsPbeKey(char[] password, AlgorithmIdentifier keyDerivationAlgorithm)
        {
            if (!keyDerivationAlgorithm.ObjectID.Equals(PkcsObjectIdentifiers.IdPbkdf2))
            {
                throw new ArgumentException("Unsupported key derivation algorithm: " + keyDerivationAlgorithm.ObjectID);
            }
            Pbkdf2Params instance = Pbkdf2Params.GetInstance(keyDerivationAlgorithm.Parameters.ToAsn1Object());

            this.password       = (char[])password.Clone();
            this.salt           = instance.GetSalt();
            this.iterationCount = instance.IterationCount.IntValue;
        }
Beispiel #4
0
        public CmsPbeKey(char[] password, AlgorithmIdentifier keyDerivationAlgorithm)
        {
            //IL_0028: Unknown result type (might be due to invalid IL or missing references)
            if (!keyDerivationAlgorithm.Algorithm.Equals(PkcsObjectIdentifiers.IdPbkdf2))
            {
                throw new ArgumentException(string.Concat((object)"Unsupported key derivation algorithm: ", (object)keyDerivationAlgorithm.Algorithm));
            }
            Pbkdf2Params instance = Pbkdf2Params.GetInstance(keyDerivationAlgorithm.Parameters.ToAsn1Object());

            this.password  = (char[])((global::System.Array)password).Clone();
            salt           = instance.GetSalt();
            iterationCount = instance.IterationCount.IntValue;
        }
            public ICipherBuilder <AlgorithmIdentifier> CreateDecryptorBuilder(AlgorithmIdentifier algorithmDetails)
            {
                if (algorithmDetails.Algorithm.Equals(PkcsObjectIdentifiers.IdPbeS2))
                {
                    IPasswordBasedDeriverBuilder <FipsPbkd.Parameters> pbeDeriverBuilder = CryptoServicesRegistrar.CreateService(FipsPbkd.PbkdF2).From(converter.Convert(password));
                    PbeS2Parameters     pbeParams   = PbeS2Parameters.GetInstance(algorithmDetails.Parameters);
                    Pbkdf2Params        pbkdfParams = Pbkdf2Params.GetInstance(pbeParams.KeyDerivationFunc.Parameters);
                    AlgorithmIdentifier encScheme   = pbeParams.EncryptionScheme;
                    IPasswordBasedDeriver <FipsPbkd.Parameters> pbeDeriver = pbeDeriverBuilder
                                                                             .WithPrf((DigestAlgorithm)Utils.digestTable[pbkdfParams.Prf.Algorithm])
                                                                             .WithSalt(pbkdfParams.GetSalt())
                                                                             .WithIterationCount(pbkdfParams.IterationCount.IntValue)
                                                                             .Build();

                    byte[] keyEnc = pbeDeriver.DeriveKey(TargetKeyType.CIPHER, (pbkdfParams.KeyLength != null ? pbkdfParams.KeyLength.IntValue : (int)Utils.keySizesInBytes[encScheme.Algorithm]));
                    IParameters <Algorithm> cipherParams = Utils.GetCipherParameters(encScheme);

                    if (Utils.IsBlockMode(cipherParams.Algorithm))
                    {
                        return(new PbeBlockCipherBuilder(algorithmDetails, Utils.CreateBlockDecryptorBuilder(encScheme, keyEnc, cipherParams)));
                    }
                    else if (Utils.IsAeadMode(cipherParams.Algorithm))
                    {
                        return(new PkixAeadCipherBuilder(algorithmDetails, Utils.CreateAeadDecryptorBuilder(encScheme, keyEnc, cipherParams)));
                    }
                    else
                    {
                        return(new PkixCipherBuilder(algorithmDetails, Utils.CreateDecryptorBuilder(encScheme, keyEnc, cipherParams)));
                    }
                }
                else if (algorithmDetails.Algorithm.Equals(PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc) ||
                         algorithmDetails.Algorithm.Equals(PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc))
                {
                    int             keySize   = algorithmDetails.Algorithm.Equals(PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc) ? 16 : 24;
                    Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(algorithmDetails.Parameters);
                    // we ignore converter as it's specified by the algorithm
                    IPasswordBasedDeriverBuilder <Pbkd.PbkdParameters> pbeDeriverBuilder = CryptoServicesRegistrar.CreateService(Pbkd.Pkcs12).From(PasswordConverter.PKCS12, password);

                    IPasswordBasedDeriver <Pbkd.PbkdParameters> pbeDeriver = pbeDeriverBuilder
                                                                             .WithPrf(FipsShs.Sha1)
                                                                             .WithSalt(pbeParams.GetIV())
                                                                             .WithIterationCount(pbeParams.Iterations.IntValue)
                                                                             .Build();

                    byte[][] keyIV = pbeDeriver.DeriveKeyAndIV(TargetKeyType.CIPHER, keySize, 8);

                    return(new PbeBlockCipherBuilder(algorithmDetails, Utils.CreateDecryptorBuilder(algorithmDetails, keyIV[0], keyIV[1])));
                }

                throw new InvalidOperationException("cannot match algorithm: " + algorithmDetails.Algorithm);
            }
        private byte[] GetDecryptionKey(string pin, VipNetContainer defence)
        {
            var passwordData = Encoding.ASCII.GetBytes(pin ?? "");

            if (DefenceKeyInfo.KeyClass.Value.IntValue == 64 && DefenceKeyInfo.KeyType.Value.IntValue == 24622)
            {
                // Контейнер зашифрован ключом, лежащим в ещё одном контейнере
                if (defence == null)
                {
                    throw new CryptographicException("Закрытый ключ зашифрован секретным ключом, расположенным в отдельном вспомогательном контейнере. Используйте опцию --defence");
                }
                return(defence.Entries[0].GetProtectionKey(pin));
            }
            if (DefenceKeyInfo.Algorithm != null &&
                DefenceKeyInfo.Algorithm.Algorithm.Equals(PkcsObjectIdentifiers.IdPbkdf2))
            {
                // PBKDF2 используется в контейнерах ViPNet Jcrypto SDK
                // Самое смешное, что сам десктопный ViPNet CSP не понимает такие контейнеры
                // А мы понимаем!
                var p = Pbkdf2Params.GetInstance(DefenceKeyInfo.Algorithm.Parameters);
                return(PBKDF2(
                           MacUtilities.GetMac(p.Prf.Algorithm),
                           passwordData,
                           p.GetSalt(),
                           p.IterationCount.IntValue,
                           p.KeyLength.IntValue
                           ));
            }
            var digest        = new Gost3411Digest();
            var keyData       = new byte[digest.GetDigestSize()];
            var unwrappingKey = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(passwordData, 0, passwordData.Length);
            digest.DoFinal(keyData, 0);
            digest.Reset();

            var secodeData = passwordData.Concat(keyData).ToArray();

            digest.BlockUpdate(secodeData, 0, secodeData.Length);
            digest.DoFinal(unwrappingKey, 0);

            var tmp = new int[keyData.Length / 4];

            for (int i = 0; i < keyData.Length; i += 4)
            {
                tmp[i / 4] = BitConverter.ToInt32(keyData, i) - BitConverter.ToInt32(unwrappingKey, i);
            }

            return(tmp.SelectMany(x => BitConverter.GetBytes(x)).ToArray());
        }
        public void AddPasswordRecipient(
            CmsPbeKey pbeKey,
            string kekAlgorithmOid)
        {
            Pbkdf2Params p = new Pbkdf2Params(pbeKey.Salt, pbeKey.IterationCount);

            PasswordRecipientInfoGenerator prig = new PasswordRecipientInfoGenerator();

            prig.DerivationAlg = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbkdf2, p);
            prig.WrapAlgorithm = kekAlgorithmOid;
            prig.WrapKey       = pbeKey.GetEncoded(kekAlgorithmOid);

            recipientInfoGenerators.Add(prig);
        }
Beispiel #8
0
    public PbeS2Parameters(Asn1Sequence seq)
    {
        if (seq.Count != 2)
        {
            throw new ArgumentException("Wrong number of elements in sequence", "seq");
        }
        Asn1Sequence asn1Sequence = (Asn1Sequence)seq[0].ToAsn1Object();

        if (asn1Sequence[0].Equals(PkcsObjectIdentifiers.IdPbkdf2))
        {
            func = new KeyDerivationFunc(PkcsObjectIdentifiers.IdPbkdf2, Pbkdf2Params.GetInstance(asn1Sequence[1]));
        }
        else
        {
            func = new KeyDerivationFunc(asn1Sequence);
        }
        scheme = EncryptionScheme.GetInstance(seq[1].ToAsn1Object());
    }
        internal static KeyStoreV3 <Pbkdf2Params> EncryptKey(PrivateKey key, string password, Pbkdf2Params kdfParams)
        {
            if (ReferenceEquals(key, null))
            {
                throw new KdfException(ErrorCode.BAD_ARGUMENT, "empty key");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new KdfException(ErrorCode.BAD_ARGUMENT, "empty password");
            }

            // unsupported prf
            if (kdfParams.prf != Pbkdf2Params.HMACSHA256)
            {
                throw new KdfException(ErrorCode.UNSUPPORTED, $"unsupported kdfparams.prf:{kdfParams.prf}");
            }

            // random values ( salt, iv )
            var salt         = kdfParams.salt;
            var cipherParams = new CipherParams();

            // derivedKey -> cipherKey -> cipherText -> mac
            var derivedKey = PbkdfCrypt.GeneratePbkdf2Sha256DerivedKey(password, salt.HexToBytes(), kdfParams.c, kdfParams.dklen);
            var cipherKey  = PbkdfCrypt.GenerateCipherKey(derivedKey);
            var cipherText = PbkdfCrypt.GenerateAesCtrCipher(cipherParams.iv.HexToBytes(), cipherKey, key.Bytes);
            var mac        = PbkdfCrypt.GenerateMac(derivedKey, cipherText);

            return(new KeyStoreV3 <Pbkdf2Params>()
            {
                version = Version,
                id = Guid.NewGuid().ToString(),
                address = key.Address.HexAddress.ToLower(),
                crypto =
                {
                    ciphertext   = cipherText.ToHex(),
                    cipherparams = cipherParams,
                    cipher       = CIPHER,
                    kdf          = KdfType.pbkdf2.ToString(),
                    kdfparams    = kdfParams,
                    mac          = mac.ToHex()
                }
            });
        }
Beispiel #10
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));
        }
Beispiel #11
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));
        }
Beispiel #12
0
            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");
                    }
                }
            }
Beispiel #13
0
        private static KeyStoreV3 <Pbkdf2Params> EncryptKey(byte[] key, string address, string password, Pbkdf2Params kdfParams)
        {
            if (key.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (password.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(password));
            }
            // unsupported prf
            if (kdfParams.prf != Pbkdf2Params.HMACSHA256)
            {
                throw new ArgumentException("unsupported kdfparams.prf");
            }

            // random values ( salt, iv )
            var salt         = kdfParams.salt;
            var cipherParams = new CipherParams();

            // derivedKey -> cipherKey -> cipherText -> mac
            var derivedKey = PbkdfCrypt.GeneratePbkdf2Sha256DerivedKey(password, salt.ToByteArray(), kdfParams.c, kdfParams.dklen);
            var cipherKey  = PbkdfCrypt.GenerateCipherKey(derivedKey);
            var cipherText = PbkdfCrypt.GenerateAesCtrCipher(cipherParams.iv.ToByteArray(), cipherKey, key);
            var mac        = PbkdfCrypt.GenerateMac(derivedKey, cipherText);

            return(new KeyStoreV3 <Pbkdf2Params>()
            {
                version = Version,
                id = Guid.NewGuid().ToString(),
                address = address,
                crypto =
                {
                    ciphertext   = cipherText.ToHexString(),
                    cipherparams = cipherParams,
                    cipher       = CIPHER,
                    kdf          = KdfType.pbkdf2.ToString(),
                    kdfparams    = kdfParams,
                    mac          = mac.ToHexString()
                }
            });
        }
Beispiel #14
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];

            byte[] keyBytes;
//            string	type = (string)algorithmType[mechanism];
            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))
            {
                Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(pbeParameters);
                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }
            else
            {
                PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters);
                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }

            ICipherParameters parameters = null;

            if (mechanism.StartsWith("PBEwithSHA-1"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-1and128bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters(128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters(40);
                }
                else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(192, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(40, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters(128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters(192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters(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(128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters(192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters(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(64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters(128, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters(192, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters(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(64, 64);
                }
                else if (mechanism.Equals("PBEwithMD2andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters(64, 64);
                }
            }
            else if (mechanism.StartsWith("PBEwithHmac"))
            {
                string digestName = mechanism.Substring("PBEwithHmac".Length);

                int keySize;
                switch (digestName)
                {
                case "SHA-1":           keySize = 160;  break;

                case "SHA-224":         keySize = 224;  break;

                case "SHA-256":         keySize = 256;  break;

                case "RipeMD128":       keySize = 128;  break;

                case "RipeMD160":       keySize = 160;  break;

                case "RipeMD256":       keySize = 256;  break;

                default:
                    throw new ArgumentException("unrecognised algorithm: " + algorithm, "algorithm");
                }

                IDigest digest = DigestUtilities.GetDigest(digestName);

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

                parameters = generator.GenerateDerivedMacParameters(keySize);
            }

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

            return(parameters);
        }
Beispiel #15
0
 /// <summary>
 /// Encrypt PrivateKey to KeyStoreV3 json string with password using Pbkdf2
 /// </summary>
 /// <exception cref="KdfException"></exception>
 public static string EncryptKeyStoreV3AsJson(PrivateKey key, string password, Pbkdf2Params kdfParams)
 {
     try
     {
         return(PbkdfService.EncryptKey(key, password, kdfParams).ToJson());
     }
     catch (KdfException e)
     {
         blog.error($"WrongHmacException! e={e.ErrorMessage}");
         throw;
     }
 }
Beispiel #16
0
 public static string EncryptKeyStoreV3(PrivateKey key, string password, Pbkdf2Params kdfParams)
 {
     return(EncryptKey(key.ToByteArray(), key.Address, password, kdfParams).ToJson());
 }
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];

            byte[] keyBytes;
            //string	type = (string)algorithmType[mechanism];
            byte[] salt;
            int    iterationCount;

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

            ICipherParameters parameters = null;

            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(parameters);
        }