private static IBigInteger GeneratePrime(
     int bitLength,
     int certainty,
     ISecureRandom rand)
 {
     return(new BigInteger(bitLength, certainty, rand));
 }
        internal IBigInteger CalculatePrivate(
            DHParameters dhParams,
            ISecureRandom random)
        {
            int limit = dhParams.L;

            if (limit != 0)
            {
                return(new BigInteger(limit, random).SetBit(limit - 1));
            }

            IBigInteger min = BigInteger.Two;
            int         m   = dhParams.M;

            if (m != 0)
            {
                min = BigInteger.One.ShiftLeft(m - 1);
            }

            IBigInteger max = dhParams.P.Subtract(BigInteger.Two);
            IBigInteger q   = dhParams.Q;

            if (q != null)
            {
                max = q.Subtract(BigInteger.Two);
            }

            return(BigIntegers.CreateRandomInRange(min, max, random));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ECKeyGenerationParameters"/> class.
 /// </summary>
 /// <param name="publicKeyParamSet">The public key param set.</param>
 /// <param name="random">The random.</param>
 /// <param name="hashAlgorithm">The hash algorithm.</param>
 /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm.</param>
 public ECKeyGenerationParameters(DerObjectIdentifier publicKeyParamSet, ISecureRandom random, HashAlgorithmTag hashAlgorithm, SymmetricKeyAlgorithmTag symmetricKeyAlgorithm)
     : this(ECKeyParameters.LookupParameters(publicKeyParamSet), random)
 {
     _publicKeyParamSet = publicKeyParamSet;
     _hashAlgorithm = hashAlgorithm;
     _symmetricKeyAlgorithm = symmetricKeyAlgorithm;
 }
        private static void ExportKeyPair(
            Stream secretOut,
            Stream publicOut,
            IAsymmetricCipherKeyPair signingKey,
            IAsymmetricCipherKeyPair encryptionKey,
            string identity,
            char[] passPhrase,
            bool armor,
            ISecureRandom random)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

            var masterKey = new PgpKeyPair(PublicKeyAlgorithmTag.Ecdsa, signingKey, DateTime.UtcNow);
            var subKey = new PgpKeyPair(PublicKeyAlgorithmTag.Ecdh, encryptionKey, DateTime.UtcNow);
            var keyRingGenerator = new PgpKeyRingGenerator(
                PgpSignature.PositiveCertification, masterKey, identity,
                SymmetricKeyAlgorithmTag.Aes256, HashAlgorithmTag.Sha256, passPhrase, true, null, null, random);
            keyRingGenerator.AddSubKey(subKey);

            keyRingGenerator.GenerateSecretKeyRing().Encode(secretOut);

            if (armor)
            {
                secretOut.Close();
                publicOut = new ArmoredOutputStream(publicOut);
            }

            keyRingGenerator.GeneratePublicKeyRing().Encode(publicOut);
            {
                publicOut.Close();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ECKeyGenerationParameters"/> class.
 /// </summary>
 /// <param name="domainParameters">The domain parameters.</param>
 /// <param name="random">The random.</param>
 /// <param name="hashAlgorithm">The hash algorithm.</param>
 /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm.</param>
 public ECKeyGenerationParameters(ECDomainParameters domainParameters, ISecureRandom random, HashAlgorithmTag hashAlgorithm, SymmetricKeyAlgorithmTag symmetricKeyAlgorithm)
     : base(random, domainParameters.N.BitLength)
 {
     _domainParams = domainParameters;
     _hashAlgorithm = hashAlgorithm;
     _symmetricKeyAlgorithm = symmetricKeyAlgorithm;
 }
        /**
         * Return a random IBigInteger not less than 'min' and not greater than 'max'
         *
         * @param min the least value that may be generated
         * @param max the greatest value that may be generated
         * @param random the source of randomness
         * @return a random IBigInteger value in the range [min,max]
         */
        public static IBigInteger CreateRandomInRange(
            IBigInteger min,
            IBigInteger max,
            // TODO Should have been just Random class
            ISecureRandom random)
        {
            int cmp = min.CompareTo(max);

            if (cmp >= 0)
            {
                if (cmp > 0)
                {
                    throw new ArgumentException("'min' may not be greater than 'max'");
                }

                return(min);
            }

            if (min.BitLength > max.BitLength / 2)
            {
                return(CreateRandomInRange(BigInteger.Zero, max.Subtract(min), random).Add(min));
            }

            for (int i = 0; i < MaxIterations; ++i)
            {
                IBigInteger x = new BigInteger(max.BitLength, random);
                if (x.CompareTo(min) >= 0 && x.CompareTo(max) <= 0)
                {
                    return(x);
                }
            }

            // fall back to a faster (restricted) method
            return(new BigInteger(max.Subtract(min).BitLength - 1, random).Add(min));
        }
        /**
         * initialise the ElGamal engine.
         *
         * @param forEncryption true if we are encrypting, false otherwise.
         * @param param the necessary ElGamal key parameters.
         */

        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            if (parameters is ParametersWithRandom)
            {
                var p = (ParametersWithRandom)parameters;

                _key    = (ElGamalKeyParameters)p.Parameters;
                _random = p.Random;
            }
            else
            {
                _key    = (ElGamalKeyParameters)parameters;
                _random = new SecureRandom();
            }

            this._forEncryption = forEncryption;
            _bitSize            = _key.Parameters.P.BitLength;

            if (forEncryption)
            {
                if (!(_key is ElGamalPublicKeyParameters))
                {
                    throw new ArgumentException("ElGamalPublicKeyParameters are required for encryption.");
                }
            }
            else
            {
                if (!(_key is ElGamalPrivateKeyParameters))
                {
                    throw new ArgumentException("ElGamalPrivateKeyParameters are required for decryption.");
                }
            }
        }
 /**
  * @param string appName
  * @param IRequest request
  * @param IURLGenerator urlGenerator
  * @param IUserManager userManager
  * @param Defaults defaults
  * @param IL10N l10n
  * @param IConfig config
  * @param ISecureRandom secureRandom
  * @param string defaultMailAddress
  * @param IManager encryptionManager
  * @param IMailer mailer
  * @param ITimeFactory timeFactory
  * @param ICrypto crypto
  */
 public LostController(string appName,
                       IRequest request,
                       IURLGenerator urlGenerator,
                       IUserManager userManager,
                       Defaults defaults,
                       IL10N l10n,
                       IConfig config,
                       ISecureRandom secureRandom,
                       string defaultMailAddress,
                       IManager encryptionManager,
                       IMailer mailer,
                       ITimeFactory timeFactory,
                       ICrypto crypto,
                       ILogger logger,
                       OC.Authentication.TwoFactorAuth.Manager twoFactorManager) : base(appName, request)
 {
     this.urlGenerator      = urlGenerator;
     this.userManager       = userManager;
     this.defaults          = defaults;
     this.l10n              = l10n;
     this.secureRandom      = secureRandom;
     this.from              = defaultMailAddress;
     this.encryptionManager = encryptionManager;
     this.config            = config;
     this.mailer            = mailer;
     this.timeFactory       = timeFactory;
     this.crypto            = crypto;
     this.logger            = logger;
     this.twoFactorManager  = twoFactorManager;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ECKeyGenerationParameters"/> class.
 /// </summary>
 /// <param name="publicKeyParamSet">The public key param set.</param>
 /// <param name="random">The random.</param>
 /// <param name="hashAlgorithm">The hash algorithm.</param>
 /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm.</param>
 public ECKeyGenerationParameters(DerObjectIdentifier publicKeyParamSet, ISecureRandom random, HashAlgorithmTag hashAlgorithm, SymmetricKeyAlgorithmTag symmetricKeyAlgorithm)
     : this(ECKeyParameters.LookupParameters(publicKeyParamSet), random)
 {
     _publicKeyParamSet     = publicKeyParamSet;
     _hashAlgorithm         = hashAlgorithm;
     _symmetricKeyAlgorithm = symmetricKeyAlgorithm;
 }
        internal IBigInteger CalculatePrivate(
			DHParameters	dhParams,
			ISecureRandom	random)
        {
            int limit = dhParams.L;

            if (limit != 0)
            {
                return new BigInteger(limit, random).SetBit(limit - 1);
            }

            IBigInteger min = BigInteger.Two;
            int m = dhParams.M;
            if (m != 0)
            {
                min = BigInteger.One.ShiftLeft(m - 1);
            }

            IBigInteger max = dhParams.P.Subtract(BigInteger.Two);
            IBigInteger q = dhParams.Q;
            if (q != null)
            {
                max = q.Subtract(BigInteger.Two);
            }

            return BigIntegers.CreateRandomInRange(min, max, random);
        }
        public void Init(bool forSigning, ICipherParameters parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    var rParam = (ParametersWithRandom)parameters;

                    _random = rParam.Random;
                    parameters = rParam.Parameters;
                }
                else
                {
                    _random = new SecureRandom();
                }

                if (!(parameters is DsaPrivateKeyParameters))
                    throw new InvalidKeyException("DSA private key required for signing");

                _key = (DsaPrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is DsaPublicKeyParameters))
                    throw new InvalidKeyException("DSA public key required for verification");

                _key = (DsaPublicKeyParameters)parameters;
            }
        }
        public void Init(bool forSigning, ICipherParameters parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    var rParam = (ParametersWithRandom)parameters;

                    _random    = rParam.Random;
                    parameters = rParam.Parameters;
                }
                else
                {
                    _random = new SecureRandom();
                }

                if (!(parameters is DsaPrivateKeyParameters))
                {
                    throw new InvalidKeyException("DSA private key required for signing");
                }

                _key = (DsaPrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is DsaPublicKeyParameters))
                {
                    throw new InvalidKeyException("DSA public key required for verification");
                }

                _key = (DsaPublicKeyParameters)parameters;
            }
        }
        /**
        * initialise the ElGamal engine.
        *
        * @param forEncryption true if we are encrypting, false otherwise.
        * @param param the necessary ElGamal key parameters.
        */
        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            if (parameters is ParametersWithRandom)
            {
                var p = (ParametersWithRandom)parameters;

                _key = (ElGamalKeyParameters)p.Parameters;
                _random = p.Random;
            }
            else
            {
                _key = (ElGamalKeyParameters)parameters;
                _random = new SecureRandom();
            }

            this._forEncryption = forEncryption;
            _bitSize = _key.Parameters.P.BitLength;

            if (forEncryption)
            {
                if (!(_key is ElGamalPublicKeyParameters))
                {
                    throw new ArgumentException("ElGamalPublicKeyParameters are required for encryption.");
                }
            }
            else
            {
                if (!(_key is ElGamalPrivateKeyParameters))
                {
                    throw new ArgumentException("ElGamalPrivateKeyParameters are required for decryption.");
                }
            }
        }
Exemple #14
0
        public IAsymmetricCipherKeyPair GenerateKeyPair()
        {
            ISecureRandom      random         = param.Random;
            Gost3410Parameters gost3410Params = param.Parameters;

            IBigInteger q = gost3410Params.Q;
            IBigInteger x;

            do
            {
                x = new BigInteger(256, random);
            }while (x.SignValue < 1 || x.CompareTo(q) >= 0);

            IBigInteger p = gost3410Params.P;
            IBigInteger a = gost3410Params.A;

            // calculate the public key.
            IBigInteger y = a.ModPow(x, p);

            if (param.PublicKeyParamSet != null)
            {
                return(new AsymmetricCipherKeyPair(
                           new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet),
                           new Gost3410PrivateKeyParameters(x, param.PublicKeyParamSet)));
            }

            return(new AsymmetricCipherKeyPair(
                       new Gost3410PublicKeyParameters(y, gost3410Params),
                       new Gost3410PrivateKeyParameters(x, gost3410Params)));
        }
        public Gost3410KeyGenerationParameters(
			ISecureRandom random,
			Gost3410Parameters parameters)
            : base(random, parameters.P.BitLength - 1)
        {
            this.parameters = parameters;
        }
        public void Init(
			bool				forSigning,
			ICipherParameters	parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                    this.random = rParam.Random;
                    parameters = rParam.Parameters;
                }
                else
                {
                    this.random = new SecureRandom();
                }

                if (!(parameters is Gost3410PrivateKeyParameters))
                    throw new InvalidKeyException("GOST3410 private key required for signing");

                this.key = (Gost3410PrivateKeyParameters) parameters;
            }
            else
            {
                if (!(parameters is Gost3410PublicKeyParameters))
                    throw new InvalidKeyException("GOST3410 public key required for signing");

                this.key = (Gost3410PublicKeyParameters) parameters;
            }
        }
        private static byte[] EncryptKeyData(
            byte[] rawKeyData,
            SymmetricKeyAlgorithmTag encAlgorithm,
            char[] passPhrase,
            ISecureRandom random,
            out S2k s2K,
            out byte[] iv)
        {
            IBufferedCipher c;

            try
            {
                var cName = PgpUtilities.GetSymmetricCipherName(encAlgorithm);
                c = CipherUtilities.GetCipher(cName + "/CFB/NoPadding");
            }
            catch (Exception e)
            {
                throw new PgpException("Exception creating cipher", e);
            }

            var s2KIv = new byte[8];

            random.NextBytes(s2KIv);
            s2K = new S2k(HashAlgorithmTag.Sha1, s2KIv, 0x60);

            var kp = PgpUtilities.MakeKeyFromPassPhrase(encAlgorithm, s2K, passPhrase);

            iv = new byte[c.GetBlockSize()];
            random.NextBytes(iv);

            c.Init(true, new ParametersWithRandom(new ParametersWithIV(kp, iv), random));

            return(c.DoFinal(rawKeyData));
        }
Exemple #18
0
        public void Init(
            bool forSigning,
            ICipherParameters parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                    this.random = rParam.Random;
                    parameters  = rParam.Parameters;
                }
                else
                {
                    this.random = new SecureRandom();
                }

                if (!(parameters is ECPrivateKeyParameters))
                {
                    throw new InvalidKeyException("EC private key required for signing");
                }

                this.key = (ECPrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is ECPublicKeyParameters))
                {
                    throw new InvalidKeyException("EC public key required for verification");
                }

                this.key = (ECPublicKeyParameters)parameters;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ECKeyGenerationParameters"/> class.
 /// </summary>
 /// <param name="domainParameters">The domain parameters.</param>
 /// <param name="random">The random.</param>
 /// <param name="hashAlgorithm">The hash algorithm.</param>
 /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm.</param>
 public ECKeyGenerationParameters(ECDomainParameters domainParameters, ISecureRandom random, HashAlgorithmTag hashAlgorithm, SymmetricKeyAlgorithmTag symmetricKeyAlgorithm)
     : base(random, domainParameters.N.BitLength)
 {
     _domainParams          = domainParameters;
     _hashAlgorithm         = hashAlgorithm;
     _symmetricKeyAlgorithm = symmetricKeyAlgorithm;
 }
        /**
        * Return a random IBigInteger not less than 'min' and not greater than 'max'
        *
        * @param min the least value that may be generated
        * @param max the greatest value that may be generated
        * @param random the source of randomness
        * @return a random IBigInteger value in the range [min,max]
        */
        public static IBigInteger CreateRandomInRange(
            IBigInteger min,
            IBigInteger max,
			// TODO Should have been just Random class
			ISecureRandom	random)
        {
            int cmp = min.CompareTo(max);
            if (cmp >= 0)
            {
                if (cmp > 0)
                    throw new ArgumentException("'min' may not be greater than 'max'");

                return min;
            }

            if (min.BitLength > max.BitLength / 2)
            {
                return CreateRandomInRange(BigInteger.Zero, max.Subtract(min), random).Add(min);
            }

            for (int i = 0; i < MaxIterations; ++i)
            {
                IBigInteger x = new BigInteger(max.BitLength, random);
                if (x.CompareTo(min) >= 0 && x.CompareTo(max) <= 0)
                {
                    return x;
                }
            }

            // fall back to a faster (restricted) method
            return new BigInteger(max.Subtract(min).BitLength - 1, random).Add(min);
        }
        public Gost3410KeyGenerationParameters(
			ISecureRandom		random,
			DerObjectIdentifier	publicKeyParamSet)
            : this(random, LookupParameters(publicKeyParamSet))
        {
            this.publicKeyParamSet = publicKeyParamSet;
        }
Exemple #22
0
        public void Init(bool forEncryption, ICipherParameters param)
        {
            var rParam = param as ParametersWithRandom;

            _random = rParam != null ? rParam.Random : new SecureRandom();
            _engine.Init(forEncryption, param);
            _forEncryption = forEncryption;
        }
        /**
         * initialise the generator with a source of randomness
         * and a strength (in bits).
         *
         * @param random the random byte source.
         * @param strength the size, in bits, of the keys we want to produce.
         */
        public KeyGenerationParameters(ISecureRandom random, int strength)
        {
            if (random == null)
                throw new ArgumentNullException("random");
            if (strength < 1)
                throw new ArgumentException(@"strength must be a positive value", "strength");

            _random = random;
            _strength = strength;
        }
        public ParametersWithRandom(ICipherParameters parameters, ISecureRandom random)
        {
            if (parameters == null)
                throw new ArgumentNullException("random");
            if (random == null)
                throw new ArgumentNullException("random");

               _parameters = parameters;
               _random = random;
        }
 internal PgpSecretKey(
     PgpPrivateKey privKey,
     PgpPublicKey pubKey,
     SymmetricKeyAlgorithmTag encAlgorithm,
     char[] passPhrase,
     bool useSha1,
     ISecureRandom rand)
     : this(privKey, pubKey, encAlgorithm, passPhrase, useSha1, rand, false)
 {
 }
        private static IBigInteger GeneratePrivateKey(IBigInteger q, ISecureRandom random)
        {
            // TODO Prefer this method? (change test cases that used fixed random)
            // B.1.1 Key Pair Generation Using Extra Random Bits
//	        IBigInteger c = new BigInteger(q.BitLength + 64, random);
//	        return c.Mod(q.Subtract(BigInteger.One)).Add(BigInteger.One);

            // B.1.2 Key Pair Generation by Testing Candidates
            return(BigIntegers.CreateRandomInRange(BigInteger.One, q.Subtract(BigInteger.One), random));
        }
        private static IBigInteger GeneratePrivateKey(IBigInteger q, ISecureRandom random)
        {
            // TODO Prefer this method? (change test cases that used fixed random)
            // B.1.1 Key Pair Generation Using Extra Random Bits
            //	        IBigInteger c = new BigInteger(q.BitLength + 64, random);
            //	        return c.Mod(q.Subtract(BigInteger.One)).Add(BigInteger.One);

            // B.1.2 Key Pair Generation by Testing Candidates
            return BigIntegers.CreateRandomInRange(BigInteger.One, q.Subtract(BigInteger.One), random);
        }
 public PgpSecretKey(
     int certificationLevel,
     PgpKeyPair keyPair,
     string id,
     SymmetricKeyAlgorithmTag encAlgorithm,
     char[] passPhrase,
     PgpSignatureSubpacketVector hashedPackets,
     PgpSignatureSubpacketVector unhashedPackets,
     ISecureRandom rand)
     : this(certificationLevel, keyPair, id, encAlgorithm, passPhrase, false, hashedPackets, unhashedPackets, rand)
 {
 }
 public PgpSecretKey(
     int certificationLevel,
     PgpKeyPair keyPair,
     string id,
     SymmetricKeyAlgorithmTag encAlgorithm,
     char[] passPhrase,
     PgpSignatureSubpacketVector hashedPackets,
     PgpSignatureSubpacketVector unhashedPackets,
     ISecureRandom rand)
     : this(certificationLevel, keyPair, id, encAlgorithm, passPhrase, false, hashedPackets, unhashedPackets, rand)
 {
 }
        public void Init(IKeyGenerationParameters parameters)
        {
            var ecKeyGenerationParameters = parameters as ECKeyGenerationParameters;

            if (ecKeyGenerationParameters != null)
            {
                _publicKeyParamSet     = ecKeyGenerationParameters.PublicKeyParamSet;
                _parameters            = ecKeyGenerationParameters.DomainParameters;
                _hashAlgorithm         = ecKeyGenerationParameters.HashAlgorithm;
                _symmetricKeyAlgorithm = ecKeyGenerationParameters.SymmetricKeyAlgorithm;
            }
            else
            {
                DerObjectIdentifier oid;
                switch (parameters.Strength)
                {
                case 192:
                    oid = X9ObjectIdentifiers.Prime192v1;
                    break;

                case 224:
                    oid = SecObjectIdentifiers.SecP224r1;
                    break;

                case 239:
                    oid = X9ObjectIdentifiers.Prime239v1;
                    break;

                case 256:
                    oid = X9ObjectIdentifiers.Prime256v1;
                    break;

                case 384:
                    oid = SecObjectIdentifiers.SecP384r1;
                    break;

                case 521:
                    oid = SecObjectIdentifiers.SecP521r1;
                    break;

                default:
                    throw new InvalidParameterException("unknown key size.");
                }

                var ecps = FindECCurveByOid(oid);
                _parameters            = new ECDomainParameters(ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
                _hashAlgorithm         = HashAlgorithmTag.Sha512;
                _symmetricKeyAlgorithm = SymmetricKeyAlgorithmTag.Aes256;
            }

            _random = parameters.Random;
        }
 public PgpKeyRingGenerator(
     int certificationLevel,
     PgpKeyPair masterKey,
     string id,
     SymmetricKeyAlgorithmTag encAlgorithm,
     char[] passPhrase,
     bool useSha1,
     PgpSignatureSubpacketVector hashedPackets,
     PgpSignatureSubpacketVector unhashedPackets,
     ISecureRandom rand)
     : this(certificationLevel, masterKey, id, encAlgorithm, HashAlgorithmTag.Sha1, passPhrase, useSha1, hashedPackets, unhashedPackets, rand)
 {
 }
Exemple #32
0
 public PgpKeyRingGenerator(
     int certificationLevel,
     PgpKeyPair masterKey,
     string id,
     SymmetricKeyAlgorithmTag encAlgorithm,
     char[] passPhrase,
     bool useSha1,
     PgpSignatureSubpacketVector hashedPackets,
     PgpSignatureSubpacketVector unhashedPackets,
     ISecureRandom rand)
     : this(certificationLevel, masterKey, id, encAlgorithm, HashAlgorithmTag.Sha1, passPhrase, useSha1, hashedPackets, unhashedPackets, rand)
 {
 }
        public void InitForEncryption(ISecureRandom random, ECDHPublicKeyParameters publicKey, byte[] fingerPrint, out ECDHPublicKeyParameters ephemeralPublicKey)
        {
            var genParams = publicKey.CreateKeyGenerationParameters(random, publicKey.HashAlgorithm, publicKey.SymmetricKeyAlgorithm);
            var generator = new ECKeyPairGenerator("ECDH");
            generator.Init(genParams);
            var ephemeralKeyPair = generator.GenerateKeyPair();

            _fingerPrint = (byte[])fingerPrint.Clone();
            _privateKey = (ECPrivateKeyParameters)ephemeralKeyPair.Private;
            _publicKey = publicKey;
            _forEncryption = true;
            ephemeralPublicKey = (ECDHPublicKeyParameters)ephemeralKeyPair.Public;
        }
 public PgpSecretKey(
     int certificationLevel,
     PgpKeyPair keyPair,
     string id,
     SymmetricKeyAlgorithmTag encAlgorithm,
     HashAlgorithmTag hashAlgorithm,
     char[] passPhrase,
     bool useSha1,
     PgpSignatureSubpacketVector hashedPackets,
     PgpSignatureSubpacketVector unhashedPackets,
     ISecureRandom rand)
     : this(keyPair.PrivateKey, CertifiedPublicKey(certificationLevel, keyPair, id, hashedPackets, unhashedPackets, hashAlgorithm), encAlgorithm, passPhrase, useSha1, rand, true)
 {
 }
        /**
         * initialise the generator with a source of randomness
         * and a strength (in bits).
         *
         * @param random the random byte source.
         * @param strength the size, in bits, of the keys we want to produce.
         */
        public KeyGenerationParameters(ISecureRandom random, int strength)
        {
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }
            if (strength < 1)
            {
                throw new ArgumentException(@"strength must be a positive value", "strength");
            }

            _random   = random;
            _strength = strength;
        }
Exemple #36
0
        public ParametersWithRandom(ICipherParameters parameters, ISecureRandom random)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("random");
            }
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }

            _parameters = parameters;
            _random     = random;
        }
Exemple #37
0
        public void InitForEncryption(ISecureRandom random, ECDHPublicKeyParameters publicKey, byte[] fingerPrint, out ECDHPublicKeyParameters ephemeralPublicKey)
        {
            var genParams = publicKey.CreateKeyGenerationParameters(random, publicKey.HashAlgorithm, publicKey.SymmetricKeyAlgorithm);
            var generator = new ECKeyPairGenerator("ECDH");

            generator.Init(genParams);
            var ephemeralKeyPair = generator.GenerateKeyPair();

            _fingerPrint       = (byte[])fingerPrint.Clone();
            _privateKey        = (ECPrivateKeyParameters)ephemeralKeyPair.Private;
            _publicKey         = publicKey;
            _forEncryption     = true;
            ephemeralPublicKey = (ECDHPublicKeyParameters)ephemeralKeyPair.Public;
        }
 public PgpSecretKey(
     int certificationLevel,
     PgpKeyPair keyPair,
     string id,
     SymmetricKeyAlgorithmTag encAlgorithm,
     HashAlgorithmTag hashAlgorithm,
     char[] passPhrase,
     bool useSha1,
     PgpSignatureSubpacketVector hashedPackets,
     PgpSignatureSubpacketVector unhashedPackets,
     ISecureRandom rand)
     : this(keyPair.PrivateKey, CertifiedPublicKey(certificationLevel, keyPair, id, hashedPackets, unhashedPackets, hashAlgorithm), encAlgorithm, passPhrase, useSha1, rand, true)
 {
 }
            private void AddEdchSessionInfo(byte[] si, ISecureRandom random)
            {
                ECDHPublicKeyParameters ephemeralPublicKey;

                var engine = new RFC6637ECDHEngine();

                engine.InitForEncryption(random, (ECDHPublicKeyParameters)_pubKey.GetKey(), _pubKey.GetFingerprint(), out ephemeralPublicKey);
                var encSession = engine.ProcessBlock(si, 0, si.Length);

                _data = new[]
                {
                    new BigInteger(1, ephemeralPublicKey.Q.GetEncoded()),
                };
                _extraData = encSession;
            }
Exemple #40
0
        /**
         * Method init
         *
         * @param forWrapping
         * @param param
         */
        public void Init(
            bool forWrapping,
            ICipherParameters parameters)
        {
            this.forWrapping = forWrapping;
            this.engine      = new CbcBlockCipher(new RC2Engine());

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom pWithR = (ParametersWithRandom)parameters;
                sr         = pWithR.Random;
                parameters = pWithR.Parameters;
            }
            else
            {
                sr = new SecureRandom();
            }

            if (parameters is ParametersWithIV)
            {
                if (!forWrapping)
                {
                    throw new ArgumentException("You should not supply an IV for unwrapping");
                }

                this.paramPlusIV = (ParametersWithIV)parameters;
                this.iv          = this.paramPlusIV.GetIV();
                this.parameters  = this.paramPlusIV.Parameters;

                if (this.iv.Length != 8)
                {
                    throw new ArgumentException("IV is not 8 octets");
                }
            }
            else
            {
                this.parameters = parameters;

                if (this.forWrapping)
                {
                    // Hm, we have no IV but we want to wrap ?!?
                    // well, then we have to create our own IV.
                    this.iv = new byte[8];
                    sr.NextBytes(iv);
                    this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
                }
            }
        }
        /**
         * Generates a permuted ArrayList from the original one. The original List
         * is not modified
         *
         * @param arr
         *            the ArrayList to be permuted
         * @param rand
         *            the source of Randomness for permutation
         * @return a new ArrayList with the permuted elements.
         */
        private static IList PermuteList(
            IList arr,
            ISecureRandom rand)
        {
            // TODO Create a utility method for generating permutation of first 'n' integers

            IList retval = Platform.CreateArrayList(arr.Count);

            foreach (object element in arr)
            {
                int index = rand.Next(retval.Count + 1);
                retval.Insert(index, element);
            }

            return(retval);
        }
Exemple #42
0
 /**
  * @param Manager manager
  * @param ISession session
  * @param ITimeFactory timeFactory
  * @param IProvider tokenProvider
  * @param IConfig config
  * @param ISecureRandom random
  * @param ILockdownManager lockdownManager
  * @param ILogger logger
  */
 public Session(Manager manager,
                ISession session,
                ITimeFactory timeFactory,
                IProvider tokenProvider,
                IConfig config,
                ISecureRandom random,
                ILockdownManager lockdownManager,
                ILogger logger)
 {
     this.manager         = manager;
     this.session         = session;
     this.timeFactory     = timeFactory;
     this.tokenProvider   = tokenProvider;
     this.config          = config;
     this.random          = random;
     this.lockdownManager = lockdownManager;
     this.logger          = logger;
 }
        /**
            * Method init
            *
            * @param forWrapping
            * @param param
            */
        public void Init(
			bool				forWrapping,
			ICipherParameters	parameters)
        {
            this.forWrapping = forWrapping;
            this.engine = new CbcBlockCipher(new RC2Engine());

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom pWithR = (ParametersWithRandom)parameters;
                sr = pWithR.Random;
                parameters = pWithR.Parameters;
            }
            else
            {
                sr = new SecureRandom();
            }

            if (parameters is ParametersWithIV)
            {
                if (!forWrapping)
                    throw new ArgumentException("You should not supply an IV for unwrapping");

                this.paramPlusIV = (ParametersWithIV)parameters;
                this.iv = this.paramPlusIV.GetIV();
                this.parameters = this.paramPlusIV.Parameters;

                if (this.iv.Length != 8)
                    throw new ArgumentException("IV is not 8 octets");
            }
            else
            {
                this.parameters = parameters;

                if (this.forWrapping)
                {
                    // Hm, we have no IV but we want to wrap ?!?
                    // well, then we have to create our own IV.
                    this.iv = new byte[8];
                    sr.NextBytes(iv);
                    this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
                }
            }
        }
Exemple #44
0
        /**
         * initialise the RSA engine.
         *
         * @param forEncryption true if we are encrypting, false otherwise.
         * @param param the necessary RSA key parameters.
         */
        public void Init(
            bool forEncryption,
            ICipherParameters param)
        {
            core.Init(forEncryption, param);

            if (param is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                key    = (RsaKeyParameters)rParam.Parameters;
                random = rParam.Random;
            }
            else
            {
                key    = (RsaKeyParameters)param;
                random = new SecureRandom();
            }
        }
Exemple #45
0
        /**
         * initialise the cipher.
         *
         * @param forEncryption if true the cipher is initialised for
         *  encryption, if false for decryption.
         * @param param the key and other data required by the cipher.
         * @exception ArgumentException if the parameters argument is
         * inappropriate.
         */
        public override void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            this.ForEncryption = forEncryption;

            ISecureRandom initRandom = null;

            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom)parameters;
                initRandom = p.Random;
                parameters = p.Parameters;
            }

            Reset();
            padding.Init(initRandom);
            Cipher.Init(forEncryption, parameters);
        }
        /**
        * Initialise the factor generator
        *
        * @param param the necessary RSA key parameters.
        */
        public void Init(
			ICipherParameters param)
        {
            if (param is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                key = (RsaKeyParameters)rParam.Parameters;
                random = rParam.Random;
            }
            else
            {
                key = (RsaKeyParameters)param;
                random = new SecureRandom();
            }

            if (key.IsPrivate)
                throw new ArgumentException("generator requires RSA public key");
        }
        /**
         * initialise the RSA engine.
         *
         * @param forEncryption true if we are encrypting, false otherwise.
         * @param param the necessary RSA key parameters.
         */
        public void Init(
			bool				forEncryption,
			ICipherParameters	param)
        {
            core.Init(forEncryption, param);

            if (param is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                key = (RsaKeyParameters)rParam.Parameters;
                random = rParam.Random;
            }
            else
            {
                key = (RsaKeyParameters)param;
                random = new SecureRandom();
            }
        }
        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            IAsymmetricKeyParameter kParam;

            var rParam = parameters as ParametersWithRandom;

            if (rParam != null)
            {
                _random = rParam.Random;
                kParam  = (AsymmetricKeyParameter)rParam.Parameters;
            }
            else
            {
                _random = new SecureRandom();
                kParam  = (AsymmetricKeyParameter)parameters;
            }

            _engine.Init(forEncryption, parameters);
            _forPrivateKey = kParam.IsPrivate;
            _forEncryption = forEncryption;
        }
Exemple #49
0
        /**
         * Initialise the factor generator
         *
         * @param param the necessary RSA key parameters.
         */
        public void Init(
            ICipherParameters param)
        {
            if (param is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                key    = (RsaKeyParameters)rParam.Parameters;
                random = rParam.Random;
            }
            else
            {
                key    = (RsaKeyParameters)param;
                random = new SecureRandom();
            }

            if (key.IsPrivate)
            {
                throw new ArgumentException("generator requires RSA public key");
            }
        }
        public virtual void Init(bool forSigning, ICipherParameters parameters)
        {
            var p = parameters as ParametersWithRandom;

            if (p != null)
            {
                parameters = p.Parameters;
                _random    = p.Random;
            }
            else
            {
                if (forSigning)
                {
                    _random = new SecureRandom();
                }
            }

            _cipher.Init(forSigning, parameters);

            RsaKeyParameters kParam;

            if (parameters is RsaBlindingParameters)
            {
                kParam = ((RsaBlindingParameters)parameters).PublicKey;
            }
            else
            {
                kParam = (RsaKeyParameters)parameters;
            }

            _emBits = kParam.Modulus.BitLength - 1;

            if (_emBits < (8 * _hLen + 8 * _sLen + 9))
            {
                throw new ArgumentException("key too small for specified hash and salt lengths");
            }

            _block = new byte[(_emBits + 7) / 8];
        }
        public void Init(ICipherParameters parameters)
        {
            IAsymmetricKeyParameter kParam;
            var rParam = parameters as ParametersWithRandom;
            if (rParam != null)
            {
                _random = rParam.Random;
                kParam = (AsymmetricKeyParameter)rParam.Parameters;
            }
            else
            {
                _random = new SecureRandom();
                kParam = (AsymmetricKeyParameter)parameters;
            }

            if (!(kParam is DHPrivateKeyParameters))
            {
                throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
            }

            _key = (DHPrivateKeyParameters)kParam;
            _dhParams = _key.Parameters;
        }
        public void Init(
			bool				forWrapping,
			ICipherParameters	param)
        {
            this.forWrapping = forWrapping;

            if (param is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom) param;

                this.rand = p.Random;
                this.param = (ParametersWithIV) p.Parameters;
            }
            else
            {
                if (forWrapping)
                {
                    rand = new SecureRandom();
                }

                this.param = (ParametersWithIV) param;
            }
        }
 internal ECKeyGenerationParameters CreateKeyGenerationParameters(ISecureRandom random, HashAlgorithmTag hashAlgorithm, SymmetricKeyAlgorithmTag symmetricKeyAlgorithm)
 {
     return _publicKeyParamSet != null
         ? new ECKeyGenerationParameters(_publicKeyParamSet, random, hashAlgorithm, symmetricKeyAlgorithm)
         : new ECKeyGenerationParameters(_parameters, random, hashAlgorithm, symmetricKeyAlgorithm);
 }
        private static byte[] EncryptKeyData(
            byte[] rawKeyData,
            SymmetricKeyAlgorithmTag encAlgorithm,
            char[] passPhrase,
            ISecureRandom random,
            out S2k s2K,
            out byte[] iv)
        {
            IBufferedCipher c;
            try
            {
                var cName = PgpUtilities.GetSymmetricCipherName(encAlgorithm);
                c = CipherUtilities.GetCipher(cName + "/CFB/NoPadding");
            }
            catch (Exception e)
            {
                throw new PgpException("Exception creating cipher", e);
            }

            var s2KIv = new byte[8];
            random.NextBytes(s2KIv);
            s2K = new S2k(HashAlgorithmTag.Sha1, s2KIv, 0x60);

            var kp = PgpUtilities.MakeKeyFromPassPhrase(encAlgorithm, s2K, passPhrase);

            iv = new byte[c.GetBlockSize()];
            random.NextBytes(iv);

            c.Init(true, new ParametersWithRandom(new ParametersWithIV(kp, iv), random));

            return c.DoFinal(rawKeyData);
        }
 public DHKeyGenerationParameters(ISecureRandom random, DHParameters parameters)
     : base(random, GetStrength(parameters))
 {
     _parameters = parameters;
 }
        internal PgpSecretKey(
            PgpPrivateKey privKey,
            PgpPublicKey pubKey,
            SymmetricKeyAlgorithmTag encAlgorithm,
            char[] passPhrase,
            bool useSha1,
            ISecureRandom rand,
            bool isMasterKey)
        {
            BcpgObject secKey;

            _pub = pubKey;

            switch (pubKey.Algorithm)
            {
                case PublicKeyAlgorithmTag.RsaEncrypt:
                case PublicKeyAlgorithmTag.RsaSign:
                case PublicKeyAlgorithmTag.RsaGeneral:
                    var rsK = (RsaPrivateCrtKeyParameters)privKey.Key;
                    secKey = new RsaSecretBcpgKey(rsK.Exponent, rsK.P, rsK.Q);
                    break;
                case PublicKeyAlgorithmTag.Dsa:
                    var dsK = (DsaPrivateKeyParameters)privKey.Key;
                    secKey = new DsaSecretBcpgKey(dsK.X);
                    break;
                case PublicKeyAlgorithmTag.ElGamalEncrypt:
                case PublicKeyAlgorithmTag.ElGamalGeneral:
                    var esK = (ElGamalPrivateKeyParameters)privKey.Key;
                    secKey = new ElGamalSecretBcpgKey(esK.X);
                    break;

                case PublicKeyAlgorithmTag.Ecdh:
                case PublicKeyAlgorithmTag.Ecdsa:
                    var ecK = (ECPrivateKeyParameters)privKey.Key;
                    secKey = new ECSecretBcpgKey(ecK.D);
                    break;

                default:
                    throw new PgpException("unknown key class");
            }

            try
            {
                using (var bOut = new MemoryStream())
                {

                    using (var pOut = new BcpgOutputStream(bOut))
                    {

                        pOut.WriteObject(secKey);

                        var keyData = bOut.ToArray();
                        var checksumBytes = Checksum(useSha1, keyData, keyData.Length);

                        pOut.Write(checksumBytes);

                        var bOutData = bOut.ToArray();

                        if (encAlgorithm == SymmetricKeyAlgorithmTag.Null)
                        {
                            this._secret = isMasterKey
                                ? new SecretKeyPacket(_pub.PublicKeyPacket, encAlgorithm, null, null, bOutData)
                                : new SecretSubkeyPacket(_pub.PublicKeyPacket, encAlgorithm, null, null, bOutData);
                        }
                        else
                        {
                            S2k s2K;
                            byte[] iv;
                            var encData = EncryptKeyData(bOutData, encAlgorithm, passPhrase, rand, out s2K, out iv);

                            var s2KUsage = useSha1 ? SecretKeyPacket.UsageSha1 : SecretKeyPacket.UsageChecksum;
                            this._secret = isMasterKey
                                ? new SecretKeyPacket(_pub.PublicKeyPacket, encAlgorithm, s2KUsage, s2K, iv, encData)
                                : new SecretSubkeyPacket(_pub.PublicKeyPacket, encAlgorithm, s2KUsage, s2K, iv, encData);
                        }
                    }
                }
            }
            catch (PgpException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new PgpException("Exception encrypting key", e);
            }
        }
 internal PgpSecretKey(
     PgpPrivateKey privKey,
     PgpPublicKey pubKey,
     SymmetricKeyAlgorithmTag encAlgorithm,
     char[] passPhrase,
     bool useSha1,
     ISecureRandom rand)
     : this(privKey, pubKey, encAlgorithm, passPhrase, useSha1, rand, false)
 {
 }
        public void Init(IKeyGenerationParameters parameters)
        {
            var ecKeyGenerationParameters = parameters as ECKeyGenerationParameters;
            if (ecKeyGenerationParameters != null)
            {
                _publicKeyParamSet = ecKeyGenerationParameters.PublicKeyParamSet;
                _parameters = ecKeyGenerationParameters.DomainParameters;
                _hashAlgorithm = ecKeyGenerationParameters.HashAlgorithm;
                _symmetricKeyAlgorithm = ecKeyGenerationParameters.SymmetricKeyAlgorithm;
            }
            else
            {
                DerObjectIdentifier oid;
                switch (parameters.Strength)
                {
                    case 192:
                        oid = X9ObjectIdentifiers.Prime192v1;
                        break;
                    case 224:
                        oid = SecObjectIdentifiers.SecP224r1;
                        break;
                    case 239:
                        oid = X9ObjectIdentifiers.Prime239v1;
                        break;
                    case 256:
                        oid = X9ObjectIdentifiers.Prime256v1;
                        break;
                    case 384:
                        oid = SecObjectIdentifiers.SecP384r1;
                        break;
                    case 521:
                        oid = SecObjectIdentifiers.SecP521r1;
                        break;
                    default:
                        throw new InvalidParameterException("unknown key size.");
                }

                var ecps = FindECCurveByOid(oid);
                _parameters = new ECDomainParameters(ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
                _hashAlgorithm = HashAlgorithmTag.Sha512;
                _symmetricKeyAlgorithm = SymmetricKeyAlgorithmTag.Aes256;
            }

            _random = parameters.Random;
        }
 /// <summary> Initialise the padder.</summary>
 /// <param name="random">- a SecureRandom if available.
 /// </param>
 public virtual void Init(ISecureRandom random)
 {
     // nothing to do.
 }
 internal ECKeyGenerationParameters CreateKeyGenerationParameters(ISecureRandom random)
 {
     return CreateKeyGenerationParameters(random, HashAlgorithmTag.Sha512, SymmetricKeyAlgorithmTag.Aes256);
 }