示例#1
0
        private static ICipherParameters GetPrivateParameters(IKey key)
        {
            AsymmetricECPrivateKey pK;
            SecureRandom           random;

            if (key is KeyWithRandom)
            {
                KeyWithRandom k = (KeyWithRandom)key;

                pK     = (AsymmetricECPrivateKey)k.Key;
                random = k.Random;
            }
            else
            {
                pK     = (AsymmetricECPrivateKey)key;
                random = CryptoServicesRegistrar.GetSecureRandom();
            }

            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                validateCurveSize(Alg, pK.DomainParameters);
            }

            return(new ParametersWithRandom(GetPrivateKeyParameters(pK), random));
        }
示例#2
0
        /**
         * Generates a random polynomial with <code>numOnes</code> coefficients equal to 1,
         * <code>numNegOnes</code> coefficients equal to -1, and the rest equal to 0.
         *
         * @param N          number of coefficients
         * @param numOnes    number of 1's
         * @param numNegOnes number of -1's
         * @return a random polynomial.
         */
        static BigIntPolynomial GenerateRandomSmall(int N, int numOnes, int numNegOnes)
        {
            List <BigInteger> coeffs = new List <BigInteger>();

            for (int i = 0; i < numOnes; i++)
            {
                coeffs.Add(BigInteger.ValueOf(1));
            }
            for (int i = 0; i < numNegOnes; i++)
            {
                coeffs.Add(BigInteger.ValueOf(-1));
            }
            while (coeffs.Count < N)
            {
                coeffs.Add(BigInteger.ValueOf(0));
            }

            Shuffle(coeffs, CryptoServicesRegistrar.GetSecureRandom());

            BigIntPolynomial poly = new BigIntPolynomial(N);

            for (int i = 0; i < coeffs.Count; i++)
            {
                poly.coeffs[i] = (BigInteger)coeffs[i];
            }
            return(poly);
        }
示例#3
0
        private static ICipherParameters GetPrivateParameters(IKey key)
        {
            DsaPrivateKeyParameters privateKeyParameters;
            SecureRandom            random;

            if (key is KeyWithRandom)
            {
                KeyWithRandom k = (KeyWithRandom)key;

                privateKeyParameters = GetPrivateKeyParameters((AsymmetricDsaPrivateKey)k.Key);
                random = k.Random;
            }
            else
            {
                privateKeyParameters = GetPrivateKeyParameters((AsymmetricDsaPrivateKey)key);
                random = CryptoServicesRegistrar.GetSecureRandom();
            }

            int effSizeInBits = privateKeyParameters.Parameters.P.BitLength;

            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                if (effSizeInBits != 2048 && effSizeInBits != 3072)
                {
                    throw new CryptoUnapprovedOperationError("attempt to create signer with unapproved keysize [" + effSizeInBits + "]", Alg);
                }
            }

            return(new ParametersWithRandom(privateKeyParameters, random));
        }
示例#4
0
        private byte[] CreateIV(DekAlgorithm algorithm)
        {
            if (algorithm.Name.EndsWith("ECB"))
            {
                return(null);
            }

            byte[] iv;

            if (algorithm.Name.Contains("AES"))
            {
                iv = new byte[16];
            }
            else
            {
                iv = new byte[8];
            }

            if (random != null)
            {
                random.NextBytes(iv);
            }
            else
            {
                CryptoServicesRegistrar.GetSecureRandom().NextBytes(iv);
            }

            return(iv);
        }
示例#5
0
        internal static EncryptionScheme GetEncryptionSchemeIdentifier(DerObjectIdentifier keyEncAlgorithm, SecureRandom random)
        {
            int ivLength = (int)Utils.ivSizesInBytes[keyEncAlgorithm];

            byte[] iv = null;

            if (ivLength != 0)
            {
                iv = new byte[ivLength];
                if (random != null)
                {
                    random.NextBytes(iv);
                }
                else
                {
                    CryptoServicesRegistrar.GetSecureRandom().NextBytes(iv);
                }
            }

            EncryptionScheme encScheme;

            if (Utils.IsAeadMode(keyEncAlgorithm))
            {
                // at the moment GCM/CCM have the same structure
                encScheme = new EncryptionScheme(keyEncAlgorithm, new CcmParameters(iv, 12));
            }
            else
            {
                encScheme = new EncryptionScheme(keyEncAlgorithm, new DerOctetString(iv));
            }

            return(encScheme);
        }
        /**
         * Reads a parameter set from an input stream.
         *
         * @param is an input stream
         * @throws java.io.IOException
         */
        public NTRUEncryptionKeyGenerationParameters(Stream inputStream) : base(CryptoServicesRegistrar.GetSecureRandom(), -1)
        {
            BinaryReader dis = new BinaryReader(inputStream);

            N            = dis.ReadInt32();
            q            = dis.ReadInt32();
            df           = dis.ReadInt32();
            df1          = dis.ReadInt32();
            df2          = dis.ReadInt32();
            df3          = dis.ReadInt32();
            db           = dis.ReadInt32();
            dm0          = dis.ReadInt32();
            c            = dis.ReadInt32();
            minCallsR    = dis.ReadInt32();
            minCallsMask = dis.ReadInt32();
            hashSeed     = dis.ReadBoolean();
            oid          = dis.ReadBytes(3);
            sparse       = dis.ReadBoolean();
            fastFp       = dis.ReadBoolean();
            polyType     = dis.Read();

            string alg = dis.ReadString();

            if ("SHA-512".Equals(alg))
            {
                hashAlg = new Sha512Digest();
            }
            else if ("SHA-256".Equals(alg))
            {
                hashAlg = new Sha256Digest();
            }

            Init();
        }
        /**
         * Reads a parameter set from an input stream.
         *
         * @param is an input stream
         * @throws java.io.IOException
         */
        public NTRUSigningKeyGenerationParameters(Stream stream) : base(CryptoServicesRegistrar.GetSecureRandom(), 0)
        {
            BinaryReader dis = new BinaryReader(stream);

            N                 = dis.ReadInt32();
            q                 = dis.ReadInt32();
            d                 = dis.ReadInt32();
            d1                = dis.ReadInt32();
            d2                = dis.ReadInt32();
            d3                = dis.ReadInt32();
            B                 = dis.ReadInt32();
            basisType         = dis.ReadInt32();
            beta              = dis.ReadDouble();
            normBound         = dis.ReadDouble();
            keyNormBound      = dis.ReadDouble();
            signFailTolerance = dis.ReadInt32();
            primeCheck        = dis.ReadBoolean();
            sparse            = dis.ReadBoolean();
            bitsF             = dis.ReadInt32();
            keyGenAlg         = dis.ReadInt32();
            string alg = dis.ReadString();

            if ("SHA-512".Equals(alg))
            {
                hashAlg = new Sha512Digest();
            }
            else if ("SHA-256".Equals(alg))
            {
                hashAlg = new Sha256Digest();
            }
            polyType = dis.ReadInt32();
            init();
        }
示例#8
0
        public void Init(
            KeyGenerationParameters parameters)
        {
            if (parameters is ECKeyGenerationParameters)
            {
                ECKeyGenerationParameters ecP = (ECKeyGenerationParameters)parameters;

                this.publicKeyParamSet = ecP.PublicKeyParamSet;
                this.parameters        = ecP.DomainParameters;
            }
            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 ArgumentException("unknown key size.");
                }

                X9ECParameters ecps = FindECCurveByOid(oid);

                this.publicKeyParamSet = oid;
                this.parameters        = new EcDomainParameters(
                    ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
            }

            this.random = parameters.Random;

            if (this.random == null)
            {
                this.random = CryptoServicesRegistrar.GetSecureRandom();
            }
        }
示例#9
0
        public IPbeSecretKeyEncryptor Build(char[] passPhrase)
        {
            byte[] s2kIv = new byte[8];

            if (random == null)
            {
                random = CryptoServicesRegistrar.GetSecureRandom();
            }

            random.NextBytes(s2kIv);

            S2k s2k = new S2k(s2kDigestFactory.AlgorithmDetails.Algorithm, s2kIv, s2kCount);

            byte[] key = PgpUtilities.MakeKeyFromPassPhrase(s2kDigestFactory, encAlgorithm, s2k, passPhrase);

            return(new SecretKeyEncryptor(encAlgorithm, key, null, s2k, new PgpSha1DigestFactory()));
        }
示例#10
0
        public void Init(
            bool forEncryption,
            ICipherParameters param)
        {
            if (param is ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;
                this.random = rParam.Random;
            }
            else if (forEncryption)
            {
                this.random = CryptoServicesRegistrar.GetSecureRandom();
            }

            engine.Init(forEncryption, param);

            this.forEncryption = forEncryption;
        }
示例#11
0
        public virtual void Init(
            bool forSigning,
            ICipherParameters parameters)
        {
            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom)parameters;

                parameters = p.Parameters;
                random     = p.Random;
                cipher.Init(forSigning, p);
            }
            else
            {
                if (forSigning)
                {
                    random = CryptoServicesRegistrar.GetSecureRandom();
                }
                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];
        }
示例#12
0
        private static ICipherParameters GetPrivateParameters(IKey key)
        {
            DsaPrivateKeyParameters privateKeyParameters;
            SecureRandom            random;

            if (key is KeyWithRandom)
            {
                KeyWithRandom k = (KeyWithRandom)key;

                privateKeyParameters = GetPrivateKeyParameters((AsymmetricDsaPrivateKey)k.Key);
                random = k.Random;
            }
            else
            {
                privateKeyParameters = GetPrivateKeyParameters((AsymmetricDsaPrivateKey)key);
                random = CryptoServicesRegistrar.GetSecureRandom();
            }

            return(new ParametersWithRandom(privateKeyParameters, random));
        }
示例#13
0
        /**
         * initialise the RSA engine.
         *
         * @param forEncryption true if we are encrypting, false otherwise.
         * @param param the necessary RSA key parameters.
         */
        public virtual 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;
                if (key.IsPrivate)
                {
                    random = CryptoServicesRegistrar.GetSecureRandom();
                }
            }
        }
示例#14
0
 protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided)
 {
     return(!needed ? null : (provided != null) ? provided : CryptoServicesRegistrar.GetSecureRandom());
 }
示例#15
0
        private static ICipherParameters GetPrivateParameters(IKey privateKey, AsymmetricRsaKey.Usage rsaUsage)
        {
            if (privateKey is KeyWithRandom)
            {
                KeyWithRandom k = (KeyWithRandom)privateKey;

                return(new ParametersWithRandom(GetPrivateKeyParameters((AsymmetricRsaPrivateKey)k.Key, rsaUsage), k.Random));
            }
            else
            {
                return(new ParametersWithRandom(GetPrivateKeyParameters((AsymmetricRsaPrivateKey)privateKey, rsaUsage), CryptoServicesRegistrar.GetSecureRandom()));
            }
        }
示例#16
0
 internal ParametersWithRandom(
     ICipherParameters parameters)
     : this(parameters, CryptoServicesRegistrar.GetSecureRandom())
 {
 }
 /**
  * Constructs a parameter set that uses ternary private keys (i.e. <code>polyType=SIMPLE</code>).
  *
  * @param N            number of polynomial coefficients
  * @param q            modulus
  * @param d            number of -1's in the private polynomials <code>f</code> and <code>g</code>
  * @param B            number of perturbations
  * @param basisType    whether to use the standard or transpose lattice
  * @param beta         balancing factor for the transpose lattice
  * @param normBound    maximum norm for valid signatures
  * @param keyNormBound maximum norm for the ploynomials <code>F</code> and <code>G</code>
  * @param primeCheck   whether <code>2N+1</code> is prime
  * @param sparse       whether to treat ternary polynomials as sparsely populated ({@link org.bouncycastle.pqc.math.ntru.polynomial.SparseTernaryPolynomial} vs {@link org.bouncycastle.pqc.math.ntru.polynomial.DenseTernaryPolynomial})
  * @param keyGenAlg    <code>RESULTANT</code> produces better bases, <code>FLOAT</code> is slightly faster. <code>RESULTANT</code> follows the EESS standard while <code>FLOAT</code> is described in Hoffstein et al: An Introduction to Mathematical Cryptography.
  * @param hashAlg      a valid identifier for a <code>java.security.MessageDigest</code> instance such as <code>SHA-256</code>. The <code>MessageDigest</code> must support the <code>getDigestLength()</code> method.
  */
 public NTRUSigningKeyGenerationParameters(int N, int q, int d, int B, int basisType, double beta, double normBound, double keyNormBound, bool primeCheck, bool sparse, int keyGenAlg, IDigest hashAlg) : base(CryptoServicesRegistrar.GetSecureRandom(), N)
 {
     this.N            = N;
     this.q            = q;
     this.d            = d;
     this.B            = B;
     this.basisType    = basisType;
     this.beta         = beta;
     this.normBound    = normBound;
     this.keyNormBound = keyNormBound;
     this.primeCheck   = primeCheck;
     this.sparse       = sparse;
     this.keyGenAlg    = keyGenAlg;
     this.hashAlg      = hashAlg;
     polyType          = (int)NTRUParameters.TERNARY_POLYNOMIAL_TYPE_SIMPLE;
     init();
 }
 /**
  * Constructs a parameter set that uses ternary private keys (i.e. <code>polyType=SIMPLE</code>).
  * @param N            number of polynomial coefficients
  * @param q            modulus
  * @param df           number of ones in the private polynomial <code>f</code>
  * @param dm0          minimum acceptable number of -1's, 0's, and 1's in the polynomial <code>m'</code> in the last encryption step
  * @param db           number of random bits to prepend to the message
  * @param c            a parameter for the Index Generation Function ({@link IndexGenerator})
  * @param minCallsR    minimum number of hash calls for the IGF to make
  * @param minCallsMask minimum number of calls to generate the masking polynomial
  * @param hashSeed     whether to hash the seed in the MGF first (true) or use the seed directly (false)
  * @param oid          three bytes that uniquely identify the parameter set
  * @param sparse       whether to treat ternary polynomials as sparsely populated ({@link org.bouncycastle.pqc.math.ntru.polynomial.SparseTernaryPolynomial} vs {@link org.bouncycastle.pqc.math.ntru.polynomial.DenseTernaryPolynomial})
  * @param fastFp       whether <code>f=1+p*F</code> for a ternary <code>F</code> (true) or <code>f</code> is ternary (false)
  * @param hashAlg      a valid identifier for a <code>java.security.MessageDigest</code> instance such as <code>SHA-256</code>. The <code>MessageDigest</code> must support the <code>getDigestLength()</code> method.
  * @param random       entropy source, if <code>null</code> uses {@link CryptoServicesRegistrar#getSecureRandom()}
  */
 public NTRUEncryptionKeyGenerationParameters(int N, int q, int df, int dm0, int db, int c, int minCallsR, int minCallsMask, bool hashSeed, byte[] oid, bool sparse, bool fastFp, IDigest hashAlg, SecureRandom random) : base(random ?? CryptoServicesRegistrar.GetSecureRandom(), db)
 {
     this.N            = N;
     this.q            = q;
     this.df           = df;
     this.db           = db;
     this.dm0          = dm0;
     this.c            = c;
     this.minCallsR    = minCallsR;
     this.minCallsMask = minCallsMask;
     this.hashSeed     = hashSeed;
     this.oid          = oid;
     this.sparse       = sparse;
     this.fastFp       = fastFp;
     this.polyType     = (int)NTRUParameters.TERNARY_POLYNOMIAL_TYPE_SIMPLE;
     this.hashAlg      = hashAlg;
     Init();
 }
        public RecipientOperator GetRecipientOperator(AlgorithmIdentifier keyEncAlg, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentKey)
        {
            byte[] keyBytes = null;
            AsymmetricRsaPrivateKey rsaKey = privKey as AsymmetricRsaPrivateKey;

            if (rsaKey != null)
            {
                // random required for blinding operations
                keyBytes = CryptoServicesRegistrar.CreateService(rsaKey, random != null ? random: CryptoServicesRegistrar.GetSecureRandom()).CreateKeyUnwrapper(FipsRsa.WrapOaep.WithDigest(FipsShs.Sha1)).Unwrap(encryptedContentKey, 0, encryptedContentKey.Length).Collect();
            }
            IParameters <Algorithm> cipherParams = Utils.GetCipherParameters(contentEncryptionAlgorithm);

            ICipherBuilder <AlgorithmIdentifier> decryptor;

            if (Utils.IsBlockMode(cipherParams.Algorithm))
            {
                decryptor = new PkixBlockCipherBuilder(contentEncryptionAlgorithm, Utils.CreateBlockDecryptorBuilder(contentEncryptionAlgorithm, keyBytes, cipherParams));
            }
            else if (Utils.IsAeadMode(cipherParams.Algorithm))
            {
                decryptor = new PkixAeadCipherBuilder(contentEncryptionAlgorithm, Utils.CreateAeadDecryptorBuilder(contentEncryptionAlgorithm, keyBytes, cipherParams));
            }
            else
            {
                decryptor = new PkixCipherBuilder(contentEncryptionAlgorithm, Utils.CreateDecryptorBuilder(contentEncryptionAlgorithm, keyBytes, cipherParams));
            }

            return(new RecipientOperator(decryptor));
        }