Exemplo n.º 1
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));
        }
 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;
 }
Exemplo n.º 3
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));
            }
        }
Exemplo n.º 4
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);
                    }
                }
            }
Exemplo n.º 5
0
 internal static void ApprovedModeCheck(String type, Algorithm algorithm)
 {
     if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
     {
         throw new CryptoUnapprovedOperationError(type + " unavailable in approved mode: " + algorithm.Name);
     }
 }
Exemplo n.º 6
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;
            }
Exemplo n.º 7
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));
        }
Exemplo n.º 8
0
 internal void CheckApprovedOnlyModeStatus()
 {
     if (approvedModeOnly != CryptoServicesRegistrar.IsInApprovedOnlyMode())
     {
         throw new CryptoUnapprovedOperationError("No access to key in current thread.");
     }
 }
Exemplo n.º 9
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;
 }
Exemplo n.º 10
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));
            }
Exemplo n.º 11
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));
            }
Exemplo n.º 12
0
 public SignerStream(
     Stream stream,
     ISigner readSigner,
     ISigner writeSigner)
 {
     this.isApprovedModeOnly = CryptoServicesRegistrar.IsInApprovedOnlyMode();
     this.stream             = stream;
     this.inSigner           = readSigner;
     this.outSigner          = writeSigner;
 }
Exemplo n.º 13
0
 internal DigestStream(
     Stream stream,
     IDigest readDigest,
     IDigest writeDigest)
 {
     this.isApprovedModeOnly = CryptoServicesRegistrar.IsInApprovedOnlyMode();
     this.stream             = stream;
     this.inDigest           = readDigest;
     this.outDigest          = writeDigest;
 }
Exemplo n.º 14
0
        internal GeneralBlockCipherService(TProv prov, TProvWithIV provWithIV)
        {
            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                throw new CryptoUnapprovedOperationError("attempt to create non-approved service in approved only mode");
            }

            this.prov       = prov;
            this.provWithIV = provWithIV;
        }
Exemplo n.º 15
0
 /// <summary>
 /// Create a new parameter set with a different IV based on the output
 /// of the passed in random.
 /// </summary>
 /// <returns>A copy of the current parameter set with the new IV.</returns>
 /// <param name="random">A SecureRandom for deriving the IV.</param>
 public override AuthenticationParametersWithIV WithIV(SecureRandom random)
 {
     if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
     {
         if (Algorithm.Equals(Gcm.Algorithm))
         {
             Utils.ValidateRandom(random, "GCM IV can only be generated by an approved DRBG");
         }
     }
     return(new AuthenticationParametersWithIV(this.Algorithm, this.MacSizeInBits, CreateDefaultIvIfNecessary(16, random)));
 }
Exemplo n.º 16
0
        public IKeyUnwrapper <TWrapParam> CreateKeyUnwrapper(TWrapParam parameters)
        {
            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                throw new CryptoUnapprovedOperationError("Attempt to create unapproved key unwrapper in approved only mode");
            }

            IWrapper wrapper = ProviderUtils.CreateWrapper(name, parameters.Algorithm.Mode, parameters.IsUsingInverseFunction, false, engineProvider);

            return(new KeyUnwrapperImpl <TWrapParam>(parameters, wrapper));
        }
Exemplo n.º 17
0
            private KeyGenerator(FipsAlgorithm algorithm, int keySizeInBits, SecureRandom random)
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    Utils.ValidateKeyGenRandom(random, keySizeInBits, algorithm);
                }

                this.algorithm     = algorithm;
                this.keySizeInBits = keySizeInBits;
                this.random        = random;
            }
Exemplo n.º 18
0
        public IMacFactory <TAuthParam> CreateMacFactory(TAuthParam parameters)
        {
            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                throw new CryptoUnapprovedOperationError("Attempt to create unapproved MAC factory in approved only mode");
            }

            IEngineProvider <IMac> macProvider = ProviderUtils.CreateMacProvider(name, parameters, engineProvider);

            return(new MacFactory <TAuthParam>(parameters, macProvider, (parameters.MacSizeInBits + 7) / 8));
        }
        private IBlockCipherBuilder <TParamWithIV> DoCreateBlockCipherBuilder(bool forEncryption, TParamWithIV parameters)
        {
            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                throw new CryptoUnapprovedOperationError("attempt to create unapproved block cipher builder in approved only mode");
            }

            IBufferedCipher cipher = ProviderUtils.CreateBufferedCipher(name, parameters.Algorithm.Mode, parameters, forEncryption, engineProvider);

            cipher.Init(forEncryption, ParametersWithIV.ApplyOptionalIV(null, parameters.GetIV()));
            return(new BlockCipherBuilderImpl <TParamWithIV>(forEncryption, parameters, cipher));
        }
Exemplo n.º 20
0
        internal GeneralBlockCipherProvider(string name, IEngineProvider <Internal.IBlockCipher> engineProvider)
        {
            CryptoStatus.IsReady();

            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                throw new CryptoUnapprovedOperationError("Attempt to create provider for unapproved algorithm in approved only mode");
            }

            this.name           = name;
            this.engineProvider = engineProvider;
        }
Exemplo n.º 21
0
        private static void ValidateKeyUse(Algorithm keyAlg, byte[] keyBytes, Algorithm usageAlg, bool forReading)
        {
            // FSM_STATE:5.11,"TDES KEY VALIDITY TEST", "The module is validating the size and purpose of an TDES key"
            // FSM_TRANS:5.TDES.0,"CONDITIONAL TEST", "TDES KEY VALIDITY TEST", "Invoke Validity test on TDES key"
            int keyLength = keyBytes.Length * 8;

            if (!forReading)      // decryption using 2 key TDES okay,
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    if (keyLength == 128)
                    {
                        // FSM_TRANS:5.TDES.2,"TDES KEY VALIDITY TEST", "USER COMMAND REJECTED", "Validity test on TDES key failed"
                        throw new IllegalKeyException("key must be of length 192 bits: " + usageAlg.Name);
                    }

                    if (!DesEdeParameters.IsReal3Key(keyBytes))
                    {
                        // FSM_TRANS:5.TDES.2,"TDES KEY VALIDITY TEST", "USER COMMAND REJECTED", "Validity test on TDES key failed"
                        throw new IllegalKeyException("key not real 3-Key TripleDES key");
                    }
                }
            }

            if (!Properties.IsOverrideSet("Org.BouncyCastle.TripleDes.AllowWeak"))
            {
                if (!forReading)
                {
                    if (!DesEdeParameters.IsRealEdeKey(keyBytes))
                    {
                        // FSM_TRANS:5.TDES.2,"TDES KEY VALIDITY TEST", "USER COMMAND REJECTED", "Validity test on TDES key failed"
                        throw new IllegalKeyException("attempt to use repeated DES key: " + usageAlg.Name);
                    }
                    if (DesEdeParameters.IsWeakKey(keyBytes, 0, keyBytes.Length))
                    {
                        // FSM_TRANS:5.TDES.2,"TDES KEY VALIDITY TEST", "USER COMMAND REJECTED", "Validity test on TDES key failed"
                        throw new IllegalKeyException("attempt to use weak key: " + usageAlg.Name);
                    }
                }
            }

            if (keyAlg != Alg && keyAlg != Alg112 && keyAlg != Alg168)
            {
                if (keyAlg != usageAlg)
                {
                    // FSM_TRANS:5.TDES.2,"TDES KEY VALIDITY TEST", "USER COMMAND REJECTED", "Validity test on TDES key failed"
                    throw new IllegalKeyException("FIPS key not for specified algorithm");
                }
            }

            // FSM_TRANS:5.TDES.0,"TDES KEY VALIDITY TEST", "CONDITIONAL TEST", "Validity test on TDES key successful"
        }
Exemplo n.º 22
0
        public IBlockCipherBuilder <TParam> CreateBlockEncryptorBuilder(TParam parameters)
        {
            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                throw new CryptoUnapprovedOperationError("Attempt to create unapproved BlockCipherBuilder in approved only mode");
            }

            IBufferedCipher cipher = ProviderUtils.CreateBufferedCipher(name, parameters.Algorithm.Mode, parameters, engineProvider.CreateEngine(EngineUsage.ENCRYPTION));

            cipher.Init(true, null);

            return(new BlockCipherBuilderImpl <TParam>(true, parameters, cipher));
        }
        private IAeadCipherBuilder <TAuthParamWithIV> DoCreateAeadCipherBuilder(bool forEncryption, TAuthParamWithIV parameters)
        {
            if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
            {
                throw new CryptoUnapprovedOperationError("attempt to create unapproved AEAD cipher builder in approved only mode");
            }

            IAeadBlockCipher cipher = ProviderUtils.CreateAeadCipher(name, parameters.Algorithm.Mode, parameters, false, engineProvider);

            cipher.Init(forEncryption, new AeadParameters(null, parameters.MacSizeInBits, parameters.GetIV()));

            return(new AeadCipherBuilderImpl <TAuthParamWithIV>(forEncryption, parameters, cipher));
        }
Exemplo n.º 24
0
            /// <summary>
            /// Construct a key pair generator for EC keys,
            /// </summary>
            /// <param name="keyGenParameters">Domain parameters and algorithm for the generated key.</param>
            /// <param name="random">A source of randomness for calculating the private value.</param>
            internal KeyPairGenerator(KeyGenerationParameters keyGenParameters, SecureRandom random) : base(keyGenParameters)
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    validateCurveSize(keyGenParameters.Algorithm, keyGenParameters.DomainParameters);

                    Utils.ValidateKeyPairGenRandom(random, Utils.GetECCurveSecurityStrength(keyGenParameters.DomainParameters.Curve), Alg);
                }

                this.param            = new Org.BouncyCastle.Crypto.Internal.Parameters.ECKeyGenerationParameters(getDomainParams(keyGenParameters.DomainParameters), random);
                this.domainParameters = keyGenParameters.DomainParameters;
                this.engine.Init(param);
            }
Exemplo n.º 25
0
            internal KeyPairGenerator(KeyGenerationParameters keyGenParameters, SecureRandom random) : base(keyGenParameters)
            {
                int keySize = keyGenParameters.KeySize;

                keyGenParameters.Validate();

                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    Utils.ValidateKeyPairGenRandom(random, Utils.GetAsymmetricSecurityStrength(keySize), Alg);
                }

                this.param = new RsaKeyGenerationParameters(keyGenParameters.PublicExponent, random, keySize, keyGenParameters.Certainty);
                this.engine.Init(param);
            }
Exemplo n.º 26
0
            internal Service(Key key)
            {
                this.approvedOnlyMode = CryptoServicesRegistrar.IsInApprovedOnlyMode();
                this.keyAlg           = key.Algorithm;
                this.keyBytes         = key.GetKeyBytes();

                IEngineProvider <Internal.IBlockCipher> engineProvider = new EngineProvider(new KeyParameter(keyBytes));

                this.prov = new Provider("FipsTripleDes", engineProvider);

                if (!CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    this.genProvForIV = new TripleDes.ProviderForIV("FipsTripleDes", engineProvider);
                }
            }
Exemplo n.º 27
0
 /// <summary>
 /// Create a new parameter set with a different IV based on the output
 /// of the passed in random.
 /// </summary>
 /// <returns>A copy of the current parameter set with the new IV.</returns>
 /// <param name="random">A SecureRandom for deriving the IV.</param>
 /// <param name="ivLen">Length of the IV to generate.</param>
 public override AuthenticationParametersWithIV WithIV(SecureRandom random, int ivLen)
 {
     if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
     {
         if (Algorithm.Equals(Gcm.Algorithm))
         {
             Utils.ValidateRandom(random, "GCM IV can only be generated by an approved DRBG");
         }
         if (ivLen < 12)
         {
             throw new CryptoUnapprovedOperationError("GCM IV must be at least 96 bits", Gcm.Algorithm);
         }
     }
     return(new AuthenticationParametersWithIV(this.Algorithm, this.MacSizeInBits, CreateDefaultIvIfNecessary(ivLen, random)));
 }
Exemplo n.º 28
0
            internal RsaKeyWrapper(OaepWrapParameters algorithmDetails, IKey rsaPublicKey)
            {
                this.algorithmDetails = algorithmDetails;
                this.wrapper          = new OaepEncoding(ENGINE_PROVIDER.CreateEngine(EngineUsage.ENCRYPTION), FipsShs.CreateDigest(algorithmDetails.DigestAlgorithm), FipsShs.CreateDigest(algorithmDetails.MgfDigestAlgorithm), algorithmDetails.GetEncodingParams());

                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    AsymmetricRsaPublicKey rsaKey = GetPublicKey(rsaPublicKey);
                    int bitLength = rsaKey.Modulus.BitLength;
                    if (bitLength != 2048 && bitLength != 3072)
                    {
                        throw new CryptoUnapprovedOperationError("Attempt to use RSA key with non-approved size: " + bitLength, rsaKey.Algorithm);
                    }
                }
                wrapper.Init(true, GetPublicParameters(rsaPublicKey, AsymmetricRsaKey.Usage.EncryptOrDecrypt));
            }
Exemplo n.º 29
0
            /// <summary>
            /// Base constructor.
            /// </summary>
            /// <param name="version">The version of DSS the validator is for.</param>
            /// <param name="digestAlgorithm">Digest to use in prime calculations.</param>
            /// <param name="random">Source of randomness for prime number testing.</param>
            public DomainParametersValidator(Version version, FipsDigestAlgorithm digestAlgorithm, SecureRandom random)
            {
                if (Version.FipsPub186_2 == version && digestAlgorithm != FipsShs.Sha1.Algorithm)
                {
                    throw new ArgumentException("186-2 can only validate with SHA-1");
                }

                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    Utils.ValidateRandom(random, "FIPS SecureRandom required for DSA parameter validation in approved mode.");
                }

                this.version         = version;
                this.digestAlgorithm = digestAlgorithm;
                this.random          = random;
            }
Exemplo n.º 30
0
            /// <summary>
            /// Base constructor.
            /// </summary>
            /// <param name="parameters">domain generation parameters.</param>
            /// <param name="random">A source of randomness for the parameter generation.</param>
            internal DomainParametersGenerator(DomainGenParameters parameters, SecureRandom random)
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    int effSizeInBits = parameters.L;

                    if (effSizeInBits != 2048 && effSizeInBits != 3072)
                    {
                        throw new CryptoUnapprovedOperationError("attempt to create parameters with unapproved key size [" + effSizeInBits + "]", Alg);
                    }

                    Utils.ValidateRandom(random, Utils.GetAsymmetricSecurityStrength(effSizeInBits), Alg, "attempt to create parameters with unapproved RNG");
                }

                this.digestAlgorithm = parameters.Digest;
                this.parameters      = parameters;
                this.random          = random;
            }