Пример #1
0
        internal static ICipherParameters GetSigKeyParams(IKey key)
        {
            if (key is AsymmetricRsaPublicKey)
            {
                AsymmetricRsaPublicKey rsaPubKey = (AsymmetricRsaPublicKey)key;
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    int bitLength = rsaPubKey.Modulus.BitLength;

                    if (bitLength != 2048 && bitLength != 3072 && bitLength != 1024 && bitLength != 4096 && bitLength != 1536) // includes 186-2 legacy sizes
                    {
                        throw new CryptoUnapprovedOperationError("Attempt to use RSA key with non-approved size: " + bitLength, key.Algorithm);
                    }
                }

                return(GetPublicKeyParameters(rsaPubKey, AsymmetricRsaKey.Usage.SignOrVerify));
            }
            else
            {
                AsymmetricRsaPrivateKey rsaPrivKey = GetPrivateKey(key);
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    int bitLength = rsaPrivKey.Modulus.BitLength;
                    if (bitLength != 2048 && bitLength != 3072)
                    {
                        throw new CryptoUnapprovedOperationError("Attempt to use RSA key with non-approved size: " + bitLength, key.Algorithm);
                    }
                }

                return(GetPrivateParameters(key, AsymmetricRsaKey.Usage.SignOrVerify));
            }
        }
        /**
         * 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();
        }
Пример #4
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));
        }
        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));
        }
Пример #6
0
        public override int Read(
            byte[]  buffer,
            int offset,
            int count)
        {
            CryptoServicesRegistrar.ApprovedModeCheck(isApprovedModeOnly, "CipherStream");

            if (inCipher == null)
            {
                return(stream.Read(buffer, offset, count));
            }

            int num = 0;

            while (num < count)
            {
                if (mInBuf == null || mInPos >= mInBuf.Length)
                {
                    if (!FillInBuf())
                    {
                        break;
                    }
                }

                int numToCopy = System.Math.Min(count - num, mInBuf.Length - mInPos);
                Array.Copy(mInBuf, mInPos, buffer, offset + num, numToCopy);
                mInPos += numToCopy;
                num    += numToCopy;
            }

            return(num);
        }
Пример #7
0
 internal void CheckApprovedOnlyModeStatus()
 {
     if (approvedModeOnly != CryptoServicesRegistrar.IsInApprovedOnlyMode())
     {
         throw new CryptoUnapprovedOperationError("No access to key in current thread.");
     }
 }
Пример #8
0
        public override void Write(
            byte[]  buffer,
            int offset,
            int count)
        {
            CryptoServicesRegistrar.ApprovedModeCheck(isApprovedModeOnly, "CipherStream");

            Debug.Assert(buffer != null);
            Debug.Assert(0 <= offset && offset <= buffer.Length);
            Debug.Assert(count >= 0);

            int end = offset + count;

            Debug.Assert(0 <= end && end <= buffer.Length);

            if (outCipher == null)
            {
                stream.Write(buffer, offset, count);
                return;
            }

            byte[] data = outCipher.ProcessBytes(buffer, offset, count);
            if (data != null)
            {
                stream.Write(data, 0, data.Length);
            }
        }
Пример #9
0
        public override void Flush()
        {
            CryptoServicesRegistrar.ApprovedModeCheck(isApprovedModeOnly, "CipherStream");

            // Note: outCipher.DoFinal is only called during Close()
            stream.Flush();
        }
Пример #10
0
 internal AsymmetricSphincsKey(Algorithm algorithm, Sphincs256KeyParams parameters)
 {
     this.approvedModeOnly = CryptoServicesRegistrar.IsInApprovedOnlyMode();
     this.algorithm        = algorithm;
     this.parameters       = parameters;
     this.treeAlgorithm    = parameters.TreeDigest.Algorithm.Equals(NistObjectIdentifiers.IdSha3_256) ? FipsShs.Sha3_256 : FipsShs.Sha512_256;
 }
Пример #11
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));
        }
Пример #12
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);
        }
Пример #13
0
 internal static void ApprovedModeCheck(String type, Algorithm algorithm)
 {
     if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
     {
         throw new CryptoUnapprovedOperationError(type + " unavailable in approved mode: " + algorithm.Name);
     }
 }
Пример #14
0
        public override void SetLength(
            long length)
        {
            CryptoServicesRegistrar.ApprovedModeCheck(isApprovedModeOnly, "DigestStream");

            stream.SetLength(length);
        }
Пример #15
0
        public override void Close()
        {
            CryptoServicesRegistrar.ApprovedModeCheck(isApprovedModeOnly, "DigestStream");

            Platform.Dispose(stream);
            base.Close();
        }
Пример #16
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);
        }
Пример #17
0
            internal void Validate()
            {
                if (!this.publicExponent.TestBit(0))
                {
                    throw new ArgumentException("Public exponent must be an odd number: " + Algorithm.Name);
                }

                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    if (this.keySize != 2048 && this.keySize != 3072)
                    {
                        throw new CryptoUnapprovedOperationError("Attempt to use RSA key size outside of accepted range - requested keySize " + keySize + " bits", Algorithm);
                    }

                    if (this.publicExponent.CompareTo(MIN_PUB_EXP) < 0)
                    {
                        throw new CryptoUnapprovedOperationError("Public exponent too small", Algorithm);
                    }

                    if (this.publicExponent.CompareTo(MAX_PUB_EXP) > 0)
                    {
                        throw new CryptoUnapprovedOperationError("Public exponent too large", Algorithm);
                    }

                    if (!this.publicExponent.TestBit(0))
                    {
                        throw new CryptoUnapprovedOperationError("Public exponent must be an odd number", Algorithm);
                    }

                    if (this.certainty < PrimeCertaintyCalculator.GetDefaultCertainty(keySize))
                    {
                        throw new CryptoUnapprovedOperationError("Prime generation certainty " + certainty + " inadequate for key of  " + keySize + " bits", Algorithm);
                    }
                }
            }
Пример #18
0
            private KeyGenerator(FipsAlgorithm algorithm, KeyGenerationParameters keyGenParams, SecureRandom random)
            {
                int keySizeInBits = keyGenParams.KeySize;

                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    Utils.ValidateKeyGenRandom(random, 112, algorithm);

                    if (keySizeInBits != 168 && keySizeInBits != 192)
                    {
                        throw new ArgumentException("Attempt to create key with unapproved key size [" + keySizeInBits + "]: " + algorithm.Name);
                    }
                }
                else
                {
                    if (keySizeInBits != 112 && keySizeInBits != 168 && keySizeInBits != 128 && keySizeInBits != 192)
                    {
                        throw new ArgumentException("Attempt to create key with invalid key size [" + keySizeInBits + "]: " + algorithm.Name);
                    }
                }

                this.algorithm     = algorithm;
                this.keySizeInBits = keySizeInBits;
                this.random        = random;
            }
        /// <summary>
        /// Build a MAC factory based on the current configuration, keyed using password.
        /// </summary>
        /// <param name="password">the password to derive the MAC key from.</param>
        /// <returns>a new MAC factory for PKCS#12</returns>
        public IMacFactory <Pkcs12MacAlgDescriptor> Build(char[] password)
        {
            IPasswordBasedDeriver <Pbkd.PbkdParameters> deriver = CryptoServicesRegistrar.CreateService(Pbkd.Pkcs12).From(PasswordConverter.PKCS12, password)
                                                                  .WithPrf(prf).WithSalt(salt).WithIterationCount(iterationCount).Build();

            return(new Pkcs12MacFactory(new Pkcs12MacAlgDescriptor((AlgorithmIdentifier)Utils.pkcs12MacAlgIds[prf], salt, iterationCount), password));
        }
Пример #20
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);
        }
Пример #21
0
            public IMacFactory <A> CreateMacFactory <A>(A algorithmDetails) where A : IAuthenticationParameters <A, Algorithm>
            {
                CryptoServicesRegistrar.ApprovedModeCheck(approvedOnlyMode, "Service");

                ValidateKeyUse(keyAlg, keyBytes, algorithmDetails.Algorithm);

                return(((IMacFactoryProvider <A>)prov).CreateMacFactory(algorithmDetails));
            }
Пример #22
0
            public IAeadCipherBuilder <A> CreateAeadEncryptorBuilder <A>(A algorithmDetails) where A : IParameters <Algorithm>
            {
                CryptoServicesRegistrar.ApprovedModeCheck(approvedOnlyMode, "Service");

                ValidateKeyUse(keyAlg, keyBytes, algorithmDetails.Algorithm);

                return(((IAeadEncryptorBuilderProvider <A>)prov).CreateAeadEncryptorBuilder(algorithmDetails));
            }
Пример #23
0
        public override long Seek(
            long offset,
            SeekOrigin origin)
        {
            CryptoServicesRegistrar.ApprovedModeCheck(isApprovedModeOnly, "DigestStream");

            return(stream.Seek(offset, origin));
        }
Пример #24
0
 internal AsymmetricRsaKey(Algorithm algorithm, BigInteger modulus)
 {
     this.approvedModeOnly = CryptoServicesRegistrar.IsInApprovedOnlyMode();
     this.algorithm        = algorithm;
     this.keyMarker        = GetKeyMarker(modulus);
     this.modulus          = keyMarker.modulus;
     this.rsaAlgIdentifier = DEF_ALG_ID;
 }
Пример #25
0
            public IKeyWrapper <A> CreateKeyWrapper <A>(A algorithmDetails) where A : ISymmetricWrapParameters <A, Algorithm>
            {
                CryptoServicesRegistrar.ApprovedModeCheck(approvedOnlyMode, "Service");

                ValidateKeyUse(keyAlg, keyBytes, algorithmDetails.Algorithm);

                return(((IKeyWrapperProvider <A>)prov).CreateKeyWrapper(algorithmDetails));
            }
Пример #26
0
            public IBlockResult Wrap(byte[] keyData)
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    throw new CryptoUnapprovedOperationError("attempt to create unapproved unwrapper in approved only mode");
                }

                return new SimpleBlockResult(wrapper.ProcessBlock(keyData, 0, keyData.Length));
            }
Пример #27
0
            public IBlockResult Unwrap(byte[] cipherText, int offset, int length)
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    throw new CryptoUnapprovedOperationError("attempt to create unapproved unwrapper in approved only mode");
                }

                return new SimpleBlockResult(unwrapper.ProcessBlock(cipherText, offset, length));
            }
Пример #28
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();
            }
        }
Пример #29
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                CryptoServicesRegistrar.ApprovedModeCheck(isApprovedModeOnly, "DigestStream");

                Platform.Dispose(stream);
            }
            base.Dispose(disposing);
        }
Пример #30
0
 internal DigestStream(
     Stream stream,
     IDigest readDigest,
     IDigest writeDigest)
 {
     this.isApprovedModeOnly = CryptoServicesRegistrar.IsInApprovedOnlyMode();
     this.stream             = stream;
     this.inDigest           = readDigest;
     this.outDigest          = writeDigest;
 }