⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fipsalgt.cpp

📁 加密算法RSA
💻 CPP
📖 第 1 页 / 共 3 页
字号:
				OutputData(output, "Q ", pqg.GetSubgroupOrder());
				OutputData(output, "G ", pqg.GetSubgroupGenerator());

				int n = atol(m_data["N"].c_str());
				for (int i=0; i<n; i++)
				{
					DSA::Signer priv;
					priv.AccessKey().GenerateRandom(m_rng, pqg);
					DSA::Verifier pub(priv);

					OutputData(output, "X ", priv.GetKey().GetPrivateExponent());
					OutputData(output, "Y ", pub.GetKey().GetPublicElement());
					AttachedTransformation()->Put((byte *)output.data(), output.size());
					output.resize(0);
				}
			}
			else if (m_test == "PQGGen")
			{
				int n = atol(m_data["N"].c_str());
				for (int i=0; i<n; i++)
				{
					Integer p, q, h, g;
					int counter;
					
					SecByteBlock seed(SHA::DIGESTSIZE);
					do
					{
						m_rng.GenerateBlock(seed, seed.size());
					}
					while (!DSA::GeneratePrimes(seed, seed.size()*8, counter, p, 1024, q));
					h.Randomize(m_rng, 2, p-2);
					g = a_exp_b_mod_c(h, (p-1)/q, p);

					OutputData(output, "P ", p);
					OutputData(output, "Q ", q);
					OutputData(output, "G ", g);
					OutputData(output, "Seed ", seed);
					OutputData(output, "c ", counter);
					OutputData(output, "H ", h, p.ByteCount());
					AttachedTransformation()->Put((byte *)output.data(), output.size());
					output.resize(0);
				}
			}
			else if (m_test == "SigGen")
			{
				std::string &encodedKey = m_data["PrivKey"];
				int modLen = atol(m_bracketString.substr(6).c_str());
				DSA::PrivateKey priv;

				if (!encodedKey.empty())
				{
					StringStore s(encodedKey);
					priv.BERDecode(s);
					if (priv.GetGroupParameters().GetModulus().BitCount() != modLen)
						encodedKey.clear();
				}

				if (encodedKey.empty())
				{
					priv.Initialize(m_rng, modLen);
					StringSink s(encodedKey);
					priv.DEREncode(s);
					OutputData(output, "P ", priv.GetGroupParameters().GetModulus());
					OutputData(output, "Q ", priv.GetGroupParameters().GetSubgroupOrder());
					OutputData(output, "G ", priv.GetGroupParameters().GetSubgroupGenerator());
				}

				DSA::Signer signer(priv);
				DSA::Verifier pub(signer);
				OutputData(output, "Msg ", m_data["Msg"]);
				OutputData(output, "Y ", pub.GetKey().GetPublicElement());

				SecByteBlock sig(signer.SignatureLength());
				StringSource(m_data["Msg"], true, new HexDecoder(new SignerFilter(m_rng, signer, new ArraySink(sig, sig.size()))));
				SecByteBlock R(sig, sig.size()/2), S(sig+sig.size()/2, sig.size()/2);
				OutputData(output, "R ", R);
				OutputData(output, "S ", S);
				AttachedTransformation()->Put((byte *)output.data(), output.size());
				output.resize(0);
			}
			else if (m_test == "SigVer")
			{
				Integer p((m_data["P"] + "h").c_str());
				Integer	q((m_data["Q"] + "h").c_str());
				Integer g((m_data["G"] + "h").c_str());
				Integer y((m_data["Y"] + "h").c_str());
				DSA::Verifier verifier(p, q, g, y);

				HexDecoder filter(new SignatureVerificationFilter(verifier));
				StringSource(m_data["R"], true, new Redirector(filter, Redirector::DATA_ONLY));
				StringSource(m_data["S"], true, new Redirector(filter, Redirector::DATA_ONLY));
				StringSource(m_data["Msg"], true, new Redirector(filter, Redirector::DATA_ONLY));
				filter.MessageEnd();
				byte b;
				filter.Get(b);
				OutputData(output, "Result ", b ? "P" : "F");
				AttachedTransformation()->Put((byte *)output.data(), output.size());
				output.resize(0);
			}
			else if (m_test == "PQGVer")
			{
				Integer p((m_data["P"] + "h").c_str());
				Integer	q((m_data["Q"] + "h").c_str());
				Integer g((m_data["G"] + "h").c_str());
				Integer h((m_data["H"] + "h").c_str());
				int c = atol(m_data["c"].c_str());
				SecByteBlock seed(m_data["Seed"].size()/2);
				StringSource(m_data["Seed"], true, new HexDecoder(new ArraySink(seed, seed.size())));

				Integer p1, q1;
				bool result = DSA::GeneratePrimes(seed, seed.size()*8, c, p1, 1024, q1, true);
				result = result && (p1 == p && q1 == q);
				result = result && g == a_exp_b_mod_c(h, (p-1)/q, p);

				OutputData(output, "Result ", result ? "P" : "F");
				AttachedTransformation()->Put((byte *)output.data(), output.size());
				output.resize(0);
			}

			return;
		}

		if (m_algorithm == "ECDSA")
		{
			std::map<std::string, OID> name2oid;
			name2oid["P-192"] = ASN1::secp192r1();
			name2oid["P-224"] = ASN1::secp224r1();
			name2oid["P-256"] = ASN1::secp256r1();
			name2oid["P-384"] = ASN1::secp384r1();
			name2oid["P-521"] = ASN1::secp521r1();
			name2oid["K-163"] = ASN1::sect163k1();
			name2oid["K-233"] = ASN1::sect233k1();
			name2oid["K-283"] = ASN1::sect283k1();
			name2oid["K-409"] = ASN1::sect409k1();
			name2oid["K-571"] = ASN1::sect571k1();
			name2oid["B-163"] = ASN1::sect163r2();
			name2oid["B-233"] = ASN1::sect233r1();
			name2oid["B-283"] = ASN1::sect283r1();
			name2oid["B-409"] = ASN1::sect409r1();
			name2oid["B-571"] = ASN1::sect571r1();

			if (m_test == "PKV")
			{
				bool pass;
				if (m_bracketString[0] == 'P')
					pass = EC_PKV<ECP>(m_rng, DecodeHex(m_data["Qx"]), DecodeHex(m_data["Qy"]), name2oid[m_bracketString]);
				else
					pass = EC_PKV<EC2N>(m_rng, DecodeHex(m_data["Qx"]), DecodeHex(m_data["Qy"]), name2oid[m_bracketString]);

				OutputData(output, "Result ", pass ? "P" : "F");
			}
			else if (m_test == "KeyPair")
			{
				if (m_bracketString[0] == 'P')
					EC_KeyPair<ECP>(output, atol(m_data["N"].c_str()), name2oid[m_bracketString]);
				else
					EC_KeyPair<EC2N>(output, atol(m_data["N"].c_str()), name2oid[m_bracketString]);
			}
			else if (m_test == "SigGen")
			{
				if (m_bracketString[0] == 'P')
					EC_SigGen<ECP>(output, name2oid[m_bracketString]);
				else
					EC_SigGen<EC2N>(output, name2oid[m_bracketString]);
			}
			else if (m_test == "SigVer")
			{
				if (m_bracketString[0] == 'P')
					EC_SigVer<ECP>(output, name2oid[m_bracketString]);
				else
					EC_SigVer<EC2N>(output, name2oid[m_bracketString]);
			}

			AttachedTransformation()->Put((byte *)output.data(), output.size());
			output.resize(0);
			return;
		}

		if (m_algorithm == "RSA")
		{
			std::string shaAlg = m_data["SHAAlg"].substr(3);

			if (m_test == "Ver")
			{
				Integer n((m_data["n"] + "h").c_str());
				Integer e((m_data["e"] + "h").c_str());
				RSA::PublicKey pub;
				pub.Initialize(n, e);

				member_ptr<PK_Verifier> pV(CreateRSA<PK_Verifier>(m_mode, shaAlg));
				pV->AccessMaterial().AssignFrom(pub);

				HexDecoder filter(new SignatureVerificationFilter(*pV));
				for (unsigned int i=m_data["S"].size(); i<pV->SignatureLength()*2; i++)
					filter.Put('0');
				StringSource(m_data["S"], true, new Redirector(filter, Redirector::DATA_ONLY));
				StringSource(m_data["Msg"], true, new Redirector(filter, Redirector::DATA_ONLY));
				filter.MessageEnd();
				byte b;
				filter.Get(b);
				OutputData(output, "Result ", b ? "P" : "F");
			}
			else
			{
				assert(m_test == "Gen");
				int modLen = atol(m_bracketString.substr(6).c_str());
				std::string &encodedKey = m_data["PrivKey"];
				RSA::PrivateKey priv;

				if (!encodedKey.empty())
				{
					StringStore s(encodedKey);
					priv.BERDecode(s);
					if (priv.GetModulus().BitCount() != modLen)
						encodedKey.clear();
				}

				if (encodedKey.empty())
				{
					priv.Initialize(m_rng, modLen);
					StringSink s(encodedKey);
					priv.DEREncode(s);
					OutputData(output, "n ", priv.GetModulus());
					OutputData(output, "e ", priv.GetPublicExponent(), modLen/8);
				}

				member_ptr<PK_Signer> pS(CreateRSA<PK_Signer>(m_mode, shaAlg));
				pS->AccessMaterial().AssignFrom(priv);

				SecByteBlock sig(pS->SignatureLength());
				StringSource(m_data["Msg"], true, new HexDecoder(new SignerFilter(m_rng, *pS, new ArraySink(sig, sig.size()))));
				OutputData(output, "SHAAlg ", m_data["SHAAlg"]);
				OutputData(output, "Msg ", m_data["Msg"]);
				OutputData(output, "S ", sig);
			}

			AttachedTransformation()->Put((byte *)output.data(), output.size());
			output.resize(0);
			return;
		}

		if (m_algorithm == "SHA")
		{
			member_ptr<HashFunction> pHF;

			if (m_mode == "1")
				pHF.reset(new SHA1);
			else if (m_mode == "224")
				pHF.reset(new SHA224);
			else if (m_mode == "256")
				pHF.reset(new SHA256);
			else if (m_mode == "384")
				pHF.reset(new SHA384);
			else if (m_mode == "512")
				pHF.reset(new SHA512);

			if (m_test == "MONTE")
			{
				SecByteBlock seed = m_data2[INPUT];
				SecByteBlock MD[1003];
				int i,j;

				for (j=0; j<100; j++)
				{
					MD[0] = MD[1] = MD[2] = seed;
					for (i=3; i<1003; i++)
					{
						SecByteBlock Mi = MD[i-3] + MD[i-2] + MD[i-1];
						MD[i].resize(pHF->DigestSize());
						pHF->CalculateDigest(MD[i], Mi, Mi.size());
					}
					seed = MD[1002];
					OutputData(output, "COUNT ", j);
					OutputData(output, "MD ", seed);
					AttachedTransformation()->Put((byte *)output.data(), output.size());
					output.resize(0);
				}
			}
			else
			{
				SecByteBlock tag(pHF->DigestSize());
				SecByteBlock &msg(m_data2[INPUT]);
				int len = atol(m_data["Len"].c_str());
				StringSource(msg.begin(), len/8, true, new HashFilter(*pHF, new ArraySink(tag, tag.size())));
				OutputData(output, "MD ", tag);
				AttachedTransformation()->Put((byte *)output.data(), output.size());
				output.resize(0);
			}
			return;
		}

		SecByteBlock &key = m_data2[KEY_T];

		if (m_algorithm == "TDES")
		{
			if (!m_data["KEY1"].empty())
			{
				const std::string keys[3] = {m_data["KEY1"], m_data["KEY2"], m_data["KEY3"]};
				key.resize(24);
				HexDecoder hexDec(new ArraySink(key, key.size()));
				for (int i=0; i<3; i++)
					hexDec.Put((byte *)keys[i].data(), keys[i].size());

				if (keys[0] == keys[2])
				{
					if (keys[0] == keys[1])
						key.resize(8);
					else
						key.resize(16);
				}
				else
					key.resize(24);
			}
		}

		if (m_algorithm == "RNG")
		{
			key.resize(24);
			StringSource(m_data["Key1"] + m_data["Key2"] + m_data["Key3"], true, new HexDecoder(new ArraySink(key, key.size())));

			SecByteBlock seed(m_data2[INPUT]), dt(m_data2[IV]), r(8);
			X917RNG rng(new DES_EDE3::Encryption(key, key.size()), seed, dt);

			if (m_test == "MCT")
			{
				for (int i=0; i<10000; i++)
					rng.GenerateBlock(r, r.size());
			}
			else
			{
				rng.GenerateBlock(r, r.size());
			}

			OutputData(output, "R ", r);
			AttachedTransformation()->Put((byte *)output.data(), output.size());
			output.resize(0);
			return;
		}

		if (m_algorithm == "HMAC")
		{
			member_ptr<MessageAuthenticationCode> pMAC;

			if (m_bracketString == "L=20")
				pMAC.reset(new HMAC<SHA1>);
			else if (m_bracketString == "L=28")
				pMAC.reset(new HMAC<SHA224>);
			else if (m_bracketString == "L=32")
				pMAC.reset(new HMAC<SHA256>);
			else if (m_bracketString == "L=48")
				pMAC.reset(new HMAC<SHA384>);
			else if (m_bracketString == "L=64")
				pMAC.reset(new HMAC<SHA512>);
			else
				throw Exception(Exception::OTHER_ERROR, "TestDataParser: unexpected HMAC bracket string: " + m_bracketString);

			pMAC->SetKey(key, key.size());
			int Tlen = atol(m_data["Tlen"].c_str());
			SecByteBlock tag(Tlen);
			StringSource(m_data["Msg"], true, new HexDecoder(new HashFilter(*pMAC, new ArraySink(tag, Tlen), false, Tlen)));
			OutputData(output, "Mac ", tag);
			AttachedTransformation()->Put((byte *)output.data(), output.size());
			output.resize(0);
			return;
		}

		member_ptr<BlockCipher> pBT;
		if (m_algorithm == "DES")
			pBT.reset(NewBT((DES*)0));
		else if (m_algorithm == "TDES")
		{
			if (key.size() == 8)
				pBT.reset(NewBT((DES*)0));
			else if (key.size() == 16)
				pBT.reset(NewBT((DES_EDE2*)0));
			else
				pBT.reset(NewBT((DES_EDE3*)0));
		}
		else if (m_algorithm == "SKIPJACK")
			pBT.reset(NewBT((SKIPJACK*)0));
		else if (m_algorithm == "AES")
			pBT.reset(NewBT((AES*)0));
		else
			throw Exception(Exception::OTHER_ERROR, "TestDataParser: unexpected algorithm: " + m_algorithm);

		if (!pBT->IsValidKeyLength(key.size()))
			key.CleanNew(pBT->DefaultKeyLength());	// for Scbcvrct
		pBT->SetKey(key.data(), key.size());

		SecByteBlock &iv = m_data2[IV];
		if (iv.empty())
			iv.CleanNew(pBT->BlockSize());

		member_ptr<SymmetricCipher> pCipher;
		unsigned int K = m_feedbackSize;

		if (m_mode == "ECB")
			pCipher.reset(NewMode((ECB_Mode_ExternalCipher*)0, *pBT, iv));
		else if (m_mode == "CBC")
			pCipher.reset(NewMode((CBC_Mode_ExternalCipher*)0, *pBT, iv));
		else if (m_mode == "CFB")
			pCipher.reset(NewMode((CFB_Mode_ExternalCipher*)0, *pBT, iv));
		else if (m_mode == "OFB")
			pCipher.reset(NewMode((OFB_Mode_ExternalCipher*)0, *pBT, iv));
		else
			throw Exception(Exception::OTHER_ERROR, "TestDataParser: unexpected mode: " + m_mode);

		bool encrypt = m_encrypt;

		if (m_test == "MONTE")
		{
			SecByteBlock KEY[401];
			KEY[0] = key;
			int keySize = key.size();
			int blockSize = pBT->BlockSize();

			std::vector<SecByteBlock> IB(10001), OB(10001), PT(10001), CT(10001), RESULT(10001), TXT(10001), CV(10001);
			PT[0] = GetData("PLAINTEXT");
			CT[0] = GetData("CIPHERTEXT");
			CV[0] = IB[0] = iv;
			TXT[0] = GetData("TEXT");

			int outerCount = (m_algorithm == "AES") ? 100 : 400;
			int innerCount = (m_algorithm == "AES") ? 1000 : 10000;

			for (int i=0; i<outerCount; i++)
			{
				pBT->SetKey(KEY[i], keySize);

				for (int j=0; j<innerCount; j++)
				{

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -