示例#1
0
        /**
         * generate an enveloped object that contains an CMS Enveloped Data object
         * @throws IOException
         */
        public Stream Open(
            Stream outStream,
            string encryptionOid,
            int keySize)
        {
            try
            {
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                keyGen.Init(new KeyGenerationParameters(rand, keySize));

                return(Open(outStream, encryptionOid, keyGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
        /// <summary>Generate an enveloped object that contains an CMS Enveloped Data object.</summary>
        public CmsEnvelopedData Generate(
            CmsProcessable content,
            string encryptionOid,
            int keySize)
        {
            try
            {
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                keyGen.Init(new KeyGenerationParameters(rand, keySize));

                return(Generate(content, encryptionOid, keyGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
        /**
         * generate an authenticated object that contains an CMS Authenticated Data object
         */
        public CmsAuthenticatedData Generate(
            CmsProcessable content,
            string encryptionOid)
        {
            try
            {
                // FIXME Will this work for macs?
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));

                return(Generate(content, encryptionOid, keyGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
示例#4
0
        private void doOidTest()
        {
            string[] oids =
            {
                CryptoProObjectIdentifiers.GostR28147Cbc.Id,
            };

            string[] names =
            {
                "GOST28147/CBC/PKCS7Padding"
            };

            try
            {
                byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
//				IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]);
                byte[] iv = new byte[8];

                for (int i = 0; i != oids.Length; i++)
                {
                    IBufferedCipher c1 = CipherUtilities.GetCipher(oids[i]);
                    IBufferedCipher c2 = CipherUtilities.GetCipher(names[i]);

//					KeyGenerator kg = KeyGenerator.getInstance(oids[i]);
//					SecretKey k = kg.generateKey();
                    CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]);
                    KeyParameter       k  = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey());

                    c1.Init(true, new ParametersWithIV(k, iv));
                    c2.Init(false, new ParametersWithIV(k, iv));

                    byte[] result = c2.DoFinal(c1.DoFinal(data));

                    if (!AreEqual(data, result))
                    {
                        Fail("failed OID test");
                    }
                }
            }
            catch (Exception ex)
            {
                Fail("failed exception " + ex.ToString(), ex);
            }
        }
示例#5
0
        public void doTestHMac(
            string hmacName,
            byte[]  output)
        {
            KeyParameter key = new KeyParameter(keyBytes); //, hmacName);

            IMac mac = MacUtilities.GetMac(hmacName);

            mac.Init(key);

            mac.Reset();

            mac.BlockUpdate(message, 0, message.Length);

//			byte[] outBytes = mac.DoFinal();
            byte[] outBytes = new byte[mac.GetMacSize()];
            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // no key generator for the old algorithms
            if (hmacName.StartsWith("Old"))
            {
                return;
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(hmacName);

            mac.Init(new KeyParameter(kGen.GenerateKey())); // hmacName

            mac.BlockUpdate(message, 0, message.Length);

//			outBytes = mac.DoFinal();
            outBytes = new byte[mac.GetMacSize()];
            mac.DoFinal(outBytes, 0);
        }
示例#6
0
        /// <summary>
        /// Generates a secret key according to the selected algorithim and the keysize
        /// </summary>
        /// <param name="selectedAlgorithim"></param>
        /// <param name="keySize"></param>
        /// <returns></returns>
        public List <byte[]> GenerateKey(int selectedAlgorithim, int keySize)
        {
            var keyAndIv      = new List <byte[]>();
            var algorithim    = ((SymmetricBouncyCastleCipher)selectedAlgorithim).ToString().Replace("_", "-");
            var keyGenerator  = GeneratorUtilities.GetKeyGenerator(algorithim);
            var keyParameters = new KeyGenerationParameters(new SecureRandom(), keySize);

            keyGenerator.Init(keyParameters);
            keyAndIv.Add(keyGenerator.GenerateKey());
            var ivSize = GetIvSize(selectedAlgorithim);

            if (ivSize > 0)
            {
                algorithim    = ((SymmetricBouncyCastleCipher)selectedAlgorithim).ToString().Replace("_", "-");
                keyGenerator  = GeneratorUtilities.GetKeyGenerator(algorithim);
                keyParameters = new KeyGenerationParameters(new SecureRandom(), ivSize);
                keyGenerator.Init(keyParameters);
                keyAndIv.Add(keyGenerator.GenerateKey());
            }
            return(keyAndIv);
        }
示例#7
0
        protected void oidTest(
            string[]        oids,
            string[]        names,
            int groupSize)
        {
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

            for (int i = 0; i != oids.Length; i++)
            {
                IBufferedCipher    c1 = CipherUtilities.GetCipher(oids[i]);
                IBufferedCipher    c2 = CipherUtilities.GetCipher(names[i]);
                CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]);

                KeyParameter k = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey());

                ICipherParameters cp = k;
                if (names[i].IndexOf("/ECB/") < 0)
                {
                    cp = new ParametersWithIV(cp, new byte[16]);
                }

                c1.Init(true, cp);
                c2.Init(false, cp);

                byte[] result = c2.DoFinal(c1.DoFinal(data));

                if (!AreEqual(data, result))
                {
                    Fail("failed OID test");
                }

                if (k.GetKey().Length != (16 + ((i / groupSize) * 8)))
                {
                    Fail("failed key length test");
                }
            }
        }
示例#8
0
        static CmsTestUtil()
        {
            try
            {
                rand = new SecureRandom();

                aes192kg = GeneratorUtilities.GetKeyGenerator("AES");
                aes192kg.Init(new KeyGenerationParameters(rand, 192));

                desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
                desede128kg.Init(new KeyGenerationParameters(rand, 112));

                desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
                desede192kg.Init(new KeyGenerationParameters(rand, 168));

                rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc240kg.Init(new KeyGenerationParameters(rand, 40));

                rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc264kg.Init(new KeyGenerationParameters(rand, 64));

                rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc2128kg.Init(new KeyGenerationParameters(rand, 128));

                aesKg = GeneratorUtilities.GetKeyGenerator("AES");

                seedKg = GeneratorUtilities.GetKeyGenerator("SEED");

                camelliaKg = GeneratorUtilities.GetKeyGenerator("Camellia");

                serialNumber = BigInteger.One;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
示例#9
0
        private void doRunTest(
            string name,
            int ivLength)
        {
            string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";

            string baseName = name;

            if (name.IndexOf('/') >= 0)
            {
                baseName = name.Substring(0, name.IndexOf('/'));
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName);

            IBufferedCipher inCipher  = CipherUtilities.GetCipher(name);
            IBufferedCipher outCipher = CipherUtilities.GetCipher(name);
            KeyParameter    key       = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey());
            MemoryStream    bIn       = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false);
            MemoryStream    bOut      = new MemoryStream();

            // In the Java build, this IV would be implicitly created and then retrieved with getIV()
            ICipherParameters cipherParams = key;

            if (ivLength > 0)
            {
                cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]);
            }

            inCipher.Init(true, cipherParams);

            // TODO Should we provide GetIV() method on IBufferedCipher?
            //if (inCipher.getIV() != null)
            //{
            //	outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV()));
            //}
            //else
            //{
            //	outCipher.Init(false, key);
            //}
            outCipher.Init(false, cipherParams);

            CipherStream cIn  = new CipherStream(bIn, inCipher, null);
            CipherStream cOut = new CipherStream(bOut, null, outCipher);

            int c;

            while ((c = cIn.ReadByte()) >= 0)
            {
                cOut.WriteByte((byte)c);
            }

            cIn.Close();

            cOut.Flush();
            cOut.Close();

            byte[] bs  = bOut.ToArray();
            string res = Encoding.ASCII.GetString(bs, 0, bs.Length);

            if (!res.Equals(lCode))
            {
                Fail("Failed - decrypted data doesn't match.");
            }
        }
        /**
         * Prepare the document for encryption.
         *
         * @param doc The document that will be encrypted.
         *
         * @throws IOException If there is an error while encrypting.
         */
        public override void PrepareDocumentForEncryption(Document doc)
        {
            try
            {
                PdfEncryption dictionary = doc.File.Encryption;
                if (dictionary == null)
                {
                    dictionary = new PdfEncryption(doc.File);
                }

                dictionary.Filter = FILTER;
                dictionary.Length = this.keyLength;
                int version = ComputeVersionNumber();
                dictionary.Version = version;

                // remove CF, StmF, and StrF entries that may be left from a previous encryption
                dictionary.RemoveV45filters();

                // create the 20 bytes seed
                byte[] seed = new byte[20];

                CipherKeyGenerator key;
                try
                {
                    key = GeneratorUtilities.GetKeyGenerator("AES");
                }
                catch (Exception e)
                {
                    // should never happen
                    throw new Exception("AES Key Generator", e);
                }

                key.Init(new KeyGenerationParameters(new SecureRandom(), 192));
                var sk = key.GenerateKey();

                // create the 20 bytes seed
                Array.Copy(sk, 0, seed, 0, 20);

                byte[][] recipientsFields = ComputeRecipientsField(seed);

                int shaInputLength = seed.Length;

                foreach (byte[] field in recipientsFields)
                {
                    shaInputLength += field.Length;
                }

                byte[] shaInput = new byte[shaInputLength];

                Array.Copy(seed, 0, shaInput, 0, 20);

                int shaInputOffset = 20;

                foreach (byte[] recipientsField in recipientsFields)
                {
                    Array.Copy(recipientsField, 0, shaInput, shaInputOffset, recipientsField.Length);
                    shaInputOffset += recipientsField.Length;
                }

                byte[] mdResult;
                if (version == 4 || version == 5)
                {
                    dictionary.SubFilter = SUBFILTER5;
                    mdResult             = SHA256.Create().Digest(shaInput);
                    PdfName aesVName = version == 5 ? PdfName.AESV3 : PdfName.AESV2;
                    PrepareEncryptionDictAES(dictionary, aesVName, recipientsFields);
                }
                else
                {
                    dictionary.SubFilter = SUBFILTER4;
                    mdResult             = SHA1.Create().Digest(shaInput);
                    dictionary.SetRecipients(recipientsFields);
                }

                this.encryptionKey = new byte[this.keyLength / 8];
                Array.Copy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8);

                doc.File.Encryption = dictionary;
            }
            catch (Exception e)
            {
                throw new IOException("", e);
            }
        }
示例#11
0
        private void doTest(
            string alg,
            int strength,
            byte[]  input,
            byte[]  output)
        {
            KeyParameter       key = null;
            CipherKeyGenerator keyGen;
            SecureRandom       rand;
            IBufferedCipher    inCipher  = null;
            IBufferedCipher    outCipher = null;
            CipherStream       cIn;
            CipherStream       cOut;
            MemoryStream       bIn;
            MemoryStream       bOut;

            rand = new FixedSecureRandom();

            try
            {
                keyGen = GeneratorUtilities.GetKeyGenerator(alg);
                keyGen.Init(new KeyGenerationParameters(rand, strength));

                key = new DesEdeParameters(keyGen.GenerateKey());

                inCipher  = CipherUtilities.GetCipher(alg + "/ECB/PKCS7Padding");
                outCipher = CipherUtilities.GetCipher(alg + "/ECB/PKCS7Padding");

                outCipher.Init(true, new ParametersWithRandom(key, rand));
            }
            catch (Exception e)
            {
                Fail(alg + " failed initialisation - " + e.ToString());
            }

            try
            {
                inCipher.Init(false, key);
            }
            catch (Exception e)
            {
                Fail(alg + " failed initialisation - " + e.ToString());
            }

            //
            // encryption pass
            //
            bOut = new MemoryStream();

            cOut = new CipherStream(bOut, null, outCipher);

            try
            {
                for (int i = 0; i != input.Length / 2; i++)
                {
                    cOut.WriteByte(input[i]);
                }
                cOut.Write(input, input.Length / 2, input.Length - input.Length / 2);
                cOut.Close();
            }
            catch (IOException e)
            {
                Fail(alg + " failed encryption - " + e.ToString());
            }

            byte[] bytes = bOut.ToArray();

            if (!Arrays.AreEqual(bytes, output))
            {
                Fail(alg + " failed encryption - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(bytes));
            }

            //
            // decryption pass
            //
            bIn = new MemoryStream(bytes, false);

            cIn = new CipherStream(bIn, inCipher, null);

            try
            {
//				DataInputStream dIn = new DataInputStream(cIn);
                BinaryReader dIn = new BinaryReader(cIn);

                bytes = new byte[input.Length];

                for (int i = 0; i != input.Length / 2; i++)
                {
                    bytes[i] = (byte)dIn.ReadByte();
                }
//				dIn.readFully(bytes, input.Length / 2, bytes.Length - input.Length / 2);
                int    remaining = bytes.Length - input.Length / 2;
                byte[] rest      = dIn.ReadBytes(remaining);
                if (rest.Length != remaining)
                {
                    throw new Exception("IO problem with BinaryReader");
                }
                rest.CopyTo(bytes, input.Length / 2);
            }
            catch (Exception e)
            {
                Fail(alg + " failed encryption - " + e.ToString());
            }

            if (!Arrays.AreEqual(bytes, input))
            {
                Fail(alg + " failed decryption - expected "
                     + Hex.ToHexString(input) + " got "
                     + Hex.ToHexString(bytes));
            }

            // TODO Put back in
//			//
//			// keyspec test
//			//
//			try
//			{
//				SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(alg);
//				DESedeKeySpec keySpec = (DESedeKeySpec)keyFactory.getKeySpec((SecretKey)key, DESedeKeySpec.class);
//
//				if (!equalArray(key.getEncoded(), keySpec.getKey(), 16))
//				{
//					Fail(alg + " KeySpec does not match key.");
//				}
//			}
//			catch (Exception e)
//			{
//				Fail(alg + " failed keyspec - " + e.ToString());
//			}
        }
示例#12
0
        /// <summary>
        /// 生成密钥KEY
        /// </summary>
        /// <param name="algorithm">密文算法,参考Algorithms.cs中提供的HMac algorithm</param>
        /// <returns>密钥KEY</returns>
        public static string GeneratorKey(string algorithm)
        {
            var kGen = GeneratorUtilities.GetKeyGenerator(algorithm);

            return(Encoding.UTF8.GetString(kGen.GenerateKey()));
        }
示例#13
0
        /// <summary>
        /// 生成密钥KEY
        /// </summary>
        /// <param name="algorithm">密文算法,参考Algorithms.cs中提供的HMac algorithm</param>
        /// <returns>密钥KEY</returns>
        public static byte[] GeneratorKey(string algorithm)
        {
            var kGen = GeneratorUtilities.GetKeyGenerator(algorithm);

            return(kGen.GenerateKey());
        }
        static TspTestUtil()
        {
            rand = new SecureRandom();

            kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpg.Init(new RsaKeyGenerationParameters(
                         BigInteger.ValueOf(0x10001), rand, 1024, 25));

            desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
            desede128kg.Init(new KeyGenerationParameters(rand, 112));

            desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
            desede192kg.Init(new KeyGenerationParameters(rand, 168));

            rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc240kg.Init(new KeyGenerationParameters(rand, 40));

            rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc264kg.Init(new KeyGenerationParameters(rand, 64));

            rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc2128kg.Init(new KeyGenerationParameters(rand, 128));

            serialNumber = BigInteger.One;

            AddEntries(NistObjectIdentifiers.DsaWithSha224, "SHA224", "DSA");
            AddEntries(NistObjectIdentifiers.DsaWithSha256, "SHA256", "DSA");
            AddEntries(NistObjectIdentifiers.DsaWithSha384, "SHA384", "DSA");
            AddEntries(NistObjectIdentifiers.DsaWithSha512, "SHA512", "DSA");
            AddEntries(OiwObjectIdentifiers.DsaWithSha1, "SHA1", "DSA");
            AddEntries(OiwObjectIdentifiers.MD4WithRsa, "MD4", "RSA");
            AddEntries(OiwObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
            AddEntries(OiwObjectIdentifiers.MD5WithRsa, "MD5", "RSA");
            AddEntries(OiwObjectIdentifiers.Sha1WithRsa, "SHA1", "RSA");
            AddEntries(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2", "RSA");
            AddEntries(PkcsObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
            AddEntries(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512", "RSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512", "ECDSA");
            AddEntries(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1", "DSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, "SHA1", "RSA");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, "SHA256", "RSA");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_1, "SHA1", "RSAandMGF1");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_256, "SHA256", "RSAandMGF1");

            encryptionAlgs.Add(X9ObjectIdentifiers.IdDsa.Id, "DSA");
            encryptionAlgs.Add(PkcsObjectIdentifiers.RsaEncryption.Id, "RSA");
            encryptionAlgs.Add(TeleTrusTObjectIdentifiers.TeleTrusTRsaSignatureAlgorithm.Id, "RSA");
            encryptionAlgs.Add(X509ObjectIdentifiers.IdEARsa.Id, "RSA");
            encryptionAlgs.Add(EncryptionRsaPss, "RSAandMGF1");
            encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x94.Id, "GOST3410");
            encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x2001.Id, "ECGOST3410");
            encryptionAlgs.Add("1.3.6.1.4.1.5849.1.6.2", "ECGOST3410");
            encryptionAlgs.Add("1.3.6.1.4.1.5849.1.1.5", "GOST3410");

            digestAlgs.Add(PkcsObjectIdentifiers.MD2.Id, "MD2");
            digestAlgs.Add(PkcsObjectIdentifiers.MD4.Id, "MD4");
            digestAlgs.Add(PkcsObjectIdentifiers.MD5.Id, "MD5");
            digestAlgs.Add(OiwObjectIdentifiers.IdSha1.Id, "SHA1");
            digestAlgs.Add(NistObjectIdentifiers.IdSha224.Id, "SHA224");
            digestAlgs.Add(NistObjectIdentifiers.IdSha256.Id, "SHA256");
            digestAlgs.Add(NistObjectIdentifiers.IdSha384.Id, "SHA384");
            digestAlgs.Add(NistObjectIdentifiers.IdSha512.Id, "SHA512");
            digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, "RIPEMD128");
            digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, "RIPEMD160");
            digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, "RIPEMD256");
            digestAlgs.Add(CryptoProObjectIdentifiers.GostR3411.Id, "GOST3411");
            digestAlgs.Add("1.3.6.1.4.1.5849.1.2.1", "GOST3411");

            digestAliases.Add("SHA1", new string[] { "SHA-1" });
            digestAliases.Add("SHA224", new string[] { "SHA-224" });
            digestAliases.Add("SHA256", new string[] { "SHA-256" });
            digestAliases.Add("SHA384", new string[] { "SHA-384" });
            digestAliases.Add("SHA512", new string[] { "SHA-512" });

            noParams.Add(EncryptionDsa);
            //noParams.Add(EncryptionECDsa);
            noParams.Add(EncryptionECDsaWithSha1);
            noParams.Add(EncryptionECDsaWithSha224);
            noParams.Add(EncryptionECDsaWithSha256);
            noParams.Add(EncryptionECDsaWithSha384);
            noParams.Add(EncryptionECDsaWithSha512);

            ecAlgorithms.Add(DigestSha1, EncryptionECDsaWithSha1);
            ecAlgorithms.Add(DigestSha224, EncryptionECDsaWithSha224);
            ecAlgorithms.Add(DigestSha256, EncryptionECDsaWithSha256);
            ecAlgorithms.Add(DigestSha384, EncryptionECDsaWithSha384);
            ecAlgorithms.Add(DigestSha512, EncryptionECDsaWithSha512);
        }
示例#15
0
        private void GenerateKey(string cipher)
        {
            var gen = GeneratorUtilities.GetKeyGenerator(cipher);

            _config.DigestKey = gen.GenerateKey();
        }
示例#16
0
        private void doTest(
            string algorithm,
            byte[]      input,
            byte[]      output)
        {
            KeyParameter       key = null;
            CipherKeyGenerator keyGen;
            SecureRandom       rand;
            IBufferedCipher    inCipher = null, outCipher = null;

            byte[]       iv = null;
            CipherStream cIn, cOut;
            MemoryStream bIn, bOut;

            rand = new FixedSecureRandom();

            string[] parts = algorithm.ToUpper(CultureInfo.InvariantCulture).Split('/');
            string   baseAlgorithm = parts[0];
            string   mode  = parts.Length > 1 ? parts[1] : null;

#if !INCLUDE_IDEA
            if (baseAlgorithm.Equals("IDEA"))
            {
                return;
            }
#endif

            try
            {
                keyGen = GeneratorUtilities.GetKeyGenerator(baseAlgorithm);

                // TODO Add Algorithm property to CipherKeyGenerator?
//				if (!keyGen.getAlgorithm().Equals(baseAlgorithm))
//				{
//					Fail("wrong key generator returned!");
//				}

                // TODO Add new Init method to CipherKeyGenerator?
//				keyGen.Init(rand);
                keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));

                byte[] keyBytes = keyGen.GenerateKey();

                if (algorithm.StartsWith("RC5"))
                {
                    key = new RC5Parameters(keyBytes, rc5Rounds);
                }
                else
                {
                    key = ParameterUtilities.CreateKeyParameter(baseAlgorithm, keyBytes);
                }

                inCipher  = CipherUtilities.GetCipher(algorithm);
                outCipher = CipherUtilities.GetCipher(algorithm);

                if (!inCipher.AlgorithmName.ToUpper(CultureInfo.InvariantCulture).StartsWith(baseAlgorithm))
                {
                    Fail("wrong cipher returned!");
                }

                ICipherParameters parameters = key;

                int ivLength = GetIVLength(algorithm);

                if (ivLength > 0)
                {
                    if (baseAlgorithm == "RC2")
                    {
                        iv = rc2IV;
                    }
                    else if (baseAlgorithm == "RC5")
                    {
                        iv = rc5IV;
                    }
                    else if (baseAlgorithm == "RC5-64")
                    {
                        iv = rc564IV;
                    }
                    else
                    {
                        // NB: rand always generates same values each test run
                        iv = rand.GenerateSeed(ivLength);
                    }

                    parameters = new ParametersWithIV(key, iv);
                }

                // NB: 'rand' still needed e.g. for some paddings
                parameters = new ParametersWithRandom(parameters, rand);

                outCipher.Init(true, parameters);
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed initialisation - " + e.ToString(), e);
            }

            //
            // grab the iv if there is one
            //
            try
            {
                // The Java version set this implicitly, but we set it explicity
                //byte[] iv = outCipher.getIV();

                if (iv != null)
                {
                    // TODO Examine short IV handling for these FIPS-compliant modes in Java build
                    if (mode.StartsWith("CFB") ||
                        mode.StartsWith("GOFB") ||
                        mode.StartsWith("OFB") ||
                        mode.StartsWith("OPENPGPCFB"))
                    {
                        // These modes automatically pad out the IV if it is short
                    }
                    else
                    {
                        try
                        {
                            byte[] nIv = new byte[iv.Length - 1];
                            inCipher.Init(false, new ParametersWithIV(key, nIv));
                            Fail("failed to pick up short IV");
                        }
                        //catch (InvalidAlgorithmParameterException e)
                        catch (ArgumentException)
                        {
                            // ignore - this is what we want...
                        }
                    }

                    //IvParameterSpec spec = new IvParameterSpec(iv);
                    inCipher.Init(false, new ParametersWithIV(key, iv));
                }
                else
                {
                    inCipher.Init(false, key);
                }
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed initialisation - " + e.ToString());
            }

            //
            // encryption pass
            //
            bOut = new MemoryStream();
            cOut = new CipherStream(bOut, null, outCipher);

            try
            {
                for (int i = 0; i != input.Length / 2; i++)
                {
                    cOut.WriteByte(input[i]);
                }
                cOut.Write(input, input.Length / 2, input.Length - input.Length / 2);
                cOut.Close();
            }
            catch (IOException e)
            {
                Fail("" + algorithm + " failed encryption - " + e.ToString());
            }

            byte[] bytes = bOut.ToArray();

            if (!AreEqual(bytes, output))
            {
                Fail("" + algorithm + " failed encryption - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(bytes));
            }

            //
            // decryption pass
            //
            bIn = new MemoryStream(bytes, false);
            cIn = new CipherStream(bIn, inCipher, null);

            try
            {
                BinaryReader dIn = new BinaryReader(cIn);

                bytes = new byte[input.Length];

                for (int i = 0; i != input.Length / 2; i++)
                {
                    bytes[i] = dIn.ReadByte();
                }

                int    remaining = bytes.Length - input.Length / 2;
                byte[] extra     = dIn.ReadBytes(remaining);
                if (extra.Length < remaining)
                {
                    throw new EndOfStreamException();
                }
                extra.CopyTo(bytes, input.Length / 2);
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed decryption - " + e.ToString());
            }

            if (!AreEqual(bytes, input))
            {
                Fail("" + algorithm + " failed decryption - expected "
                     + Hex.ToHexString(input) + " got "
                     + Hex.ToHexString(bytes));
            }
        }
示例#17
0
        // TODO Make private again and call from PerformTest
        public void doTestExceptions()
        {
            // TODO Put back in
//			SecretKeyFactory skF = null;
//
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			KeySpec ks = null;
//			SecretKey secKey = null;
//			byte[] bb = new byte[24];
//
//			try
//			{
//				skF.getKeySpec(null, null);
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				ks = (KeySpec)new DESedeKeySpec(bb);
//				skF.getKeySpec(null, ks.getClass());
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay;
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				skF.getKeySpec(secKey, null);
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}

            try
            {
                CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator("DESede");

                try
                {
                    kg.Init(new KeyGenerationParameters(new SecureRandom(), int.MinValue));

                    Fail("failed exception test - no exception thrown");
                }
//				catch (InvalidParameterException)
                catch (ArgumentException)
                {
                    // ignore okay
                }
                catch (Exception e)
                {
                    Fail("failed exception test.", e);
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//
//				try
//				{
//					skF.translateKey(null);
//
//					Fail("failed exception test - no exception thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore okay
//				}
//				catch (Exception e)
//				{
//					Fail("failed exception test.", e);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

//			try
//			{
//				byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134,
//						(byte)137, (byte)138, (byte)140, (byte)143 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/CBC/NoPadding");
//
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if this
//					// cipher is being
//					// initialized for decryption and requires algorithm parameters
//					// that cannot be determined from the given key
////					cipher.Init(false, cipherKey, (SecureRandom)null);
//					cipher.Init(false, new ParametersWithRandom(cipherKey, new SecureRandom()));
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
//				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118 };
                byte[] rawDESKey = { 128, 131, 133, 134, 137, 138 };

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");

//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
                try
                {
                    KeyParameter cipherKey = new DesParameters(rawDESKey);

                    // According specification engineInit(int opmode, Key key,
                    // SecureRandom random) throws InvalidKeyException if the given
                    // key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);

//					Fail("failed exception test - no InvalidKeyException thrown");
                    Fail("failed exception test - no ArgumentException thrown");
                }
//				catch (InvalidKeyException)
                catch (ArgumentException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

//			try
//			{
////				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118, -117, -115, -114 };
//				byte[] rawDESKey = { 128, 131, 133, 134, 137, 138, 139, 141, 142 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if the given
//					// key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}


            try
            {
                byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134,
                                     (byte)137, (byte)138, (byte)140, (byte)143 };

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
                KeyParameter cipherKey = new DesParameters(rawDESKey);

                IBufferedCipher ecipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding");
                ecipher.Init(true, cipherKey);

                byte[] cipherText = new byte[0];
                try
                {
                    // According specification Method engineUpdate(byte[] input,
                    // int inputOffset, int inputLen, byte[] output, int
                    // outputOffset)
                    // throws ShortBufferException - if the given output buffer is
                    // too
                    // small to hold the result
//					ecipher.update(new byte[20], 0, 20, cipherText);
                    ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0);

//					Fail("failed exception test - no ShortBufferException thrown");
                    Fail("failed exception test - no DataLengthException thrown");
                }
//				catch (ShortBufferException)
                catch (DataLengthException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				KeyGenerator keyGen = KeyGenerator.getInstance("DES");
//
//				keyGen.init((SecureRandom)null);
//
//				// According specification engineGenerateKey() doesn't throw any exceptions.
//
//				SecretKey key = keyGen.generateKey();
//				if (key == null)
//				{
//					Fail("key is null!");
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			try
//			{
//				AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");
//
//				algParams.init(new IvParameterSpec(new byte[8]));
//
//				// According specification engineGetEncoded() returns
//				// the parameters in their primary encoding format. The primary
//				// encoding
//				// format for parameters is ASN.1, if an ASN.1 specification for
//				// this type
//				// of parameters exists.
//				byte[] iv = algParams.getEncoded();
//
//				if (iv.Length!= 10)
//				{
//					Fail("parameters encoding wrong length - "  + iv.Length);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
                try
                {
//					AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");

                    byte[] encoding = new byte[10];
                    encoding[0] = 3;
                    encoding[1] = 8;

//					algParams.init(encoding, "ASN.1");
                    ParameterUtilities.GetCipherParameters(
                        "AES",
                        ParameterUtilities.CreateKeyParameter("AES", new byte[16]),
                        Asn1Object.FromByteArray(encoding));

//					Fail("failed exception test - no IOException thrown");
                    Fail("failed exception test - no Exception thrown");
                }
//				catch (IOException)
                catch (ArgumentException)
                {
                    // okay
                }

//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PublicKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(true, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for public key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
//
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PrivateKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(false, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for private key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }
        }
示例#18
0
 internal CipherKeyGenerator CreateKeyGenerator(
     string encryptionOid)
 {
     return(GeneratorUtilities.GetKeyGenerator(encryptionOid));
 }