Inheritance: DsaKeyParameters
        public void TestDSA()
        {
            IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            IBigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para);

            SubjectPublicKeyInfo subInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(dsaPub);
            DsaKeyParameters testResult = (DsaKeyParameters)PublicKeyFactory.CreateKey(subInfo);

            // check RSA public key.

            Assert.IsFalse(!testResult.Equals(dsaPub), "DSA: test failed on public key to info and back to public key.");

            PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dsaPriv);
            testResult = (DsaPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

            Assert.IsFalse(!testResult.Equals(dsaPriv), "DSA: private key to info back to private key.");

            Assert.IsTrue(true, "DSATest worked.");
        }
Exemplo n.º 2
0
 protected bool Equals(DsaPublicKeyParameters other)
 {
     if (y.Equals(other.y))
     {
         return(Equals((DsaKeyParameters)other));
     }
     return(false);
 }
Exemplo n.º 3
0
        public override bool Equals(object obj)
        {
            if (obj == this)
            {
                return(true);
            }
            DsaPublicKeyParameters dsaPublicKeyParameters = obj as DsaPublicKeyParameters;

            return(dsaPublicKeyParameters != null && this.Equals(dsaPublicKeyParameters));
        }
Exemplo n.º 4
0
        public override bool Equals(object obj)
        {
            if (obj == this)
            {
                return(true);
            }
            DsaPublicKeyParameters dsaPublicKeyParameters = obj as DsaPublicKeyParameters;

            if (dsaPublicKeyParameters == null)
            {
                return(false);
            }
            return(Equals(dsaPublicKeyParameters));
        }
        public override bool Equals(object obj)
        {
            if (obj == this)
            {
                return(true);
            }
            DsaPublicKeyParameters other = obj as DsaPublicKeyParameters;

            if (other == null)
            {
                return(false);
            }
            return(this.Equals(other));
        }
        public void TestX509CertificateConversion()
        {
            IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            IBigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList(attrs.Keys);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

            cert.CheckValidity();
            cert.Verify(dsaPub);

            SystemX509.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(cert);

            X509Certificate certCopy = DotNetUtilities.FromX509Certificate(dotNetCert);

            Assert.AreEqual(cert, certCopy);

            certCopy.CheckValidity();
            certCopy.Verify(dsaPub);
        }
Exemplo n.º 7
0
		public static AsymmetricCipherKeyPair GetDsaKeyPair(
			DSAParameters dp)
		{
			DsaValidationParameters validationParameters = (dp.Seed != null)
				?	new DsaValidationParameters(dp.Seed, dp.Counter)
				:	null;

			DsaParameters parameters = new DsaParameters(
				new BigInteger(1, dp.P),
				new BigInteger(1, dp.Q),
				new BigInteger(1, dp.G),
				validationParameters);

			DsaPublicKeyParameters pubKey = new DsaPublicKeyParameters(
				new BigInteger(1, dp.Y),
				parameters);

			DsaPrivateKeyParameters privKey = new DsaPrivateKeyParameters(
				new BigInteger(1, dp.X),
				parameters);

			return new AsymmetricCipherKeyPair(pubKey, privKey);
		}
        public void TestAlgorithms()
        {
            //
            // RSA parameters
            //
            IBigInteger rsaMod = new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16);
            IBigInteger rsaPubExp = new BigInteger("10001", 16);

            IBigInteger rsaPrivExp = new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16);
            IBigInteger rsaPrivP = new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16);
            IBigInteger rsaPrivQ = new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16);
            IBigInteger rsaPrivDP = new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16);
            IBigInteger rsaPrivDQ = new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16);
            IBigInteger rsaPrivQinv = new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16);

            RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(
                rsaMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            //
            // ECDSA parameters
            //
            IBigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            IBigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            IBigInteger ECParraH = new BigInteger(Base64.Decode("AQ=="));
            IBigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            IBigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            IBigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            IBigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

            FPCurve curve = new FPCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

            ECDomainParameters ecDomain = new ECDomainParameters(curve,
                new FPPoint(curve,
                    curve.FromBigInteger(ECParraGX),
                    curve.FromBigInteger(ECParraGY)),
                ECParraN);

            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                new FPPoint(curve,
                    curve.FromBigInteger(ECPubQX),
                    curve.FromBigInteger(ECPubQY)),
                ecDomain);

            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain);

            //
            // DSA parameters
            //
            IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            IBigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para);

            //
            // ECGOST3410 parameters
            //
            IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");
            ecGostKpg.Init(
                new ECKeyGenerationParameters(
                    CryptoProObjectIdentifiers.GostR3410x2001CryptoProA,
                    new SecureRandom()));

            IAsymmetricCipherKeyPair ecGostPair = ecGostKpg.GenerateKeyPair();

            //
            // GOST3410 parameters
            //
            IAsymmetricCipherKeyPairGenerator gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
            gostKpg.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            IAsymmetricCipherKeyPair gostPair = gostKpg.GenerateKeyPair();

            //
            // signer loop
            //
            byte[] shortMsg = new byte[] { 1, 4, 5, 6, 8, 8, 4, 2, 1, 3 };
            byte[] longMsg = new byte[100];
            new SecureRandom().NextBytes(longMsg);

            foreach (string algorithm in SignerUtilities.Algorithms)
            {
                ISigner signer = SignerUtilities.GetSigner(algorithm);

                string upper = algorithm.ToUpper(CultureInfo.InvariantCulture);
                int withPos = upper.LastIndexOf("WITH");

                string cipherName = withPos < 0
                    ?	upper
                    :	upper.Substring(withPos + "WITH".Length);

                ICipherParameters signParams = null, verifyParams = null;

                if (cipherName == "RSA" || cipherName == "RSAANDMGF1")
                {
                    signParams = rsaPrivate;
                    verifyParams = rsaPublic;
                }
                else if (cipherName == "ECDSA")
                {
                    signParams = ecPriv;
                    verifyParams = ecPub;
                }
                else if (cipherName == "DSA")
                {
                    signParams = dsaPriv;
                    verifyParams = dsaPub;
                }
                else if (cipherName == "ECGOST3410")
                {
                    signParams = ecGostPair.Private;
                    verifyParams = ecGostPair.Public;
                }
                else if (cipherName == "GOST3410")
                {
                    signParams = gostPair.Private;
                    verifyParams = gostPair.Public;
                }
                else
                {
                    Assert.Fail("Unknown algorithm encountered: " + cipherName);
                }

                signer.Init(true, signParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);
                byte[] sig = signer.GenerateSignature();

                signer.Init(false, verifyParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);

                Assert.IsTrue(signer.VerifySignature(sig), cipherName + " signer " + algorithm + " failed.");
            }
        }
Exemplo n.º 9
0
		protected bool Equals(
			DsaPublicKeyParameters other)
		{
			return y.Equals(other.y) && base.Equals(other);
		}
Exemplo n.º 10
0
        private static DsaPublicKeyParameters GetDSAPublicKeyParams(byte[] dsa_p_mpi, byte[] dsa_q_mpi, byte[] dsa_g_mpi, byte[] dsa_y_mpi)
        {
            if (dsa_p_mpi == null || dsa_p_mpi.Length < 1)
                throw new ArgumentException("GetDSAPublicKeyParams: DSA P Key parameter mpi byte array cannot be null/empty");

            if (dsa_q_mpi == null || dsa_q_mpi.Length < 1)
                throw new ArgumentException("GetDSAPublicKeyParams: DSA Q Key parameter mpi byte array cannot be null/empty");

            if (dsa_g_mpi == null || dsa_g_mpi.Length < 1)
                throw new ArgumentException("GetDSAPublicKeyParams: DSA G Key parameter mpi byte array cannot be null/empty");

            if (dsa_y_mpi == null || dsa_y_mpi.Length < 1)
                throw new ArgumentException("GetDSAPublicKeyParams: DSA Y Key parameter mpi byte array cannot be null/empty");

            Org.BouncyCastle.Math.BigInteger _P = null;
            Org.BouncyCastle.Math.BigInteger _Q = null;
            Org.BouncyCastle.Math.BigInteger _G = null;
            Org.BouncyCastle.Math.BigInteger _Y = null;

            Utility.DecodeMpiFromBytes(dsa_p_mpi, 0, ref _P);
            Utility.DecodeMpiFromBytes(dsa_q_mpi, 0, ref _Q);
            Utility.DecodeMpiFromBytes(dsa_g_mpi, 0, ref _G);
            Utility.DecodeMpiFromBytes(dsa_y_mpi, 0, ref _Y);

              DsaParameters _dsa_param         = new DsaParameters(_P, _Q, _G);
              DsaPublicKeyParameters _public_key_param = new DsaPublicKeyParameters(_Y, _dsa_param);

              return _public_key_param;
        }
 protected bool Equals(DsaPublicKeyParameters other) =>
 (this.y.Equals(other.y) && base.Equals((DsaKeyParameters)other));
Exemplo n.º 12
0
		/**
		* Read a Key Pair
		*/
		private AsymmetricCipherKeyPair ReadKeyPair(
			string	type,
			string	endMarker)
		{
			//
			// extract the key
			//
			IDictionary fields = new Hashtable();
			byte[] keyBytes = ReadBytesAndFields(endMarker, fields);

			string procType = (string) fields["Proc-Type"];

			if (procType == "4,ENCRYPTED")
			{
				if (pFinder == null)
					throw new PasswordException("No password finder specified, but a password is required");

				char[] password = pFinder.GetPassword();

				if (password == null)
					throw new PasswordException("Password is null, but a password is required");

				string dekInfo = (string) fields["DEK-Info"];
				string[] tknz = dekInfo.Split(',');

				string dekAlgName = tknz[0].Trim();
				byte[] iv = Hex.Decode(tknz[1].Trim());

				keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
			}

			try
			{
				AsymmetricKeyParameter pubSpec, privSpec;
				Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(keyBytes);

				switch (type)
				{
					case "RSA":
					{
						RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);

						pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
						privSpec = new RsaPrivateCrtKeyParameters(
							rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
							rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
							rsa.Coefficient);

						break;
					}

					case "DSA":
					{
						// TODO Create an ASN1 object somewhere for this?
						//DerInteger v = (DerInteger)seq[0];
						DerInteger p = (DerInteger)seq[1];
						DerInteger q = (DerInteger)seq[2];
						DerInteger g = (DerInteger)seq[3];
						DerInteger y = (DerInteger)seq[4];
						DerInteger x = (DerInteger)seq[5];

						DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);

						privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
						pubSpec = new DsaPublicKeyParameters(y.Value, parameters);

						break;
					}

					case "EC":
					{
						ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq);
						AlgorithmIdentifier algId = new AlgorithmIdentifier(
							X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

						PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());
						DerBitString pubKey = pKey.GetPublicKey();
						//Console.WriteLine(pubKey == null);
						SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());

						// TODO Are the keys returned here ECDSA, as Java version forces?
						privSpec = PrivateKeyFactory.CreateKey(privInfo);
						pubSpec = PublicKeyFactory.CreateKey(pubInfo);

						break;
					}

					default:
						throw new ArgumentException("Unknown key type: " + type, "type");
				}

				return new AsymmetricCipherKeyPair(pubSpec, privSpec);
			}
			catch (Exception e)
			{
				throw new PemException(
					"problem creating " + type + " private key: " + e.ToString());
			}
		}
Exemplo n.º 13
0
		private DsaPublicKeyParameters GetInheritedKey(DsaPublicKeyParameters dsaPubKey)
		{
			X509Certificate cert = new X509CertificateParser().ReadCertificate(
				GetRfc4134Data("CarlDSSSelf.cer"));

			DsaParameters dsaParams = ((DsaPublicKeyParameters)cert.GetPublicKey()).Parameters;

			return new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams);
		}
Exemplo n.º 14
0
        public static bool VerifySignature(DsaPublicKeyParameters public_key_param, byte[] data_to_sign_byte_array, byte[] r_byte_array, byte[] s_byte_array)
        {
            BigInteger _data_to_sign = new BigInteger(1, data_to_sign_byte_array);
            BigInteger _r = new BigInteger(1, r_byte_array);
            BigInteger _s = new BigInteger(1, s_byte_array);
            DsaParameters _parameters = public_key_param.Parameters;

            BigInteger zero = BigInteger.ValueOf(0);

            /*
            if (IsValidPQLength(_parameters.P.BitLength, _parameters.Q.BitLength) == false)
            throw new InvalidDataException("VerifySignature: The Length of the DSA key P parameter does not correspond to that of the Q parameter");
            */

            if (zero.CompareTo(_r) >= 0 || _parameters.Q.CompareTo(_r) <= 0)
                return false;

            if (zero.CompareTo(_s) >= 0 || _parameters.Q.CompareTo(_s) <= 0)
                return false;

            BigInteger _w = _s.ModInverse(_parameters.Q);
            BigInteger _u1 = _data_to_sign.Multiply(_w).Mod(_parameters.Q);
            BigInteger _u2 = _r.Multiply(_w).Mod(_parameters.Q);

            _u1 = _parameters.G.ModPow(_u1, _parameters.P);
            _u2 = public_key_param.Y.ModPow(_u2, _parameters.P);
            BigInteger _v = _u1.Multiply(_u2).Mod(_parameters.P).Mod(_parameters.Q);

            // Console.WriteLine("Size of Q:{0}   \n   Size of R:{1}   \n  Size of S:{2} ", _parameters.Q.BitLength/8, r_byte_array.Length, s_byte_array.Length);

            return _v.Equals(_r);
        }
Exemplo n.º 15
0
        private void SetKey(BigInteger p, BigInteger q, BigInteger g, BigInteger x)
        {
            if (p == null)
                throw new ArgumentException("The DSA key parameter P cannot be null");

            if (q == null)
                throw new ArgumentException("The DSA key parameter Q cannot be null");

            if (g == null)
                throw new ArgumentException("The DSA key parameter G cannot be null");

            if (x == null)
                throw new ArgumentException("The DSA key parameter X cannot be null");

            _P = p;
            _Q = q;
            _G = g;
            _X = x;

            _Y = _G.ModPow(_X, _P);

            DsaParameters _dsa_param = new DsaParameters(_P, _Q, _G);
            _public_key_param = new DsaPublicKeyParameters(_Y, _dsa_param);
            _private_key_param = new DsaPrivateKeyParameters(_X, _dsa_param);

            SetPublicKeyEncodedMpi();
        }
Exemplo n.º 16
0
        private void InitKey()
        {
            _secure_random = new SecureRandom();
            DsaParametersGenerator _dsa_param_gen = new DsaParametersGenerator();
            DsaKeyPairGenerator _dsa_key_pair_gen = new DsaKeyPairGenerator();
            _dsa_param_gen.Init(1024, 80, _secure_random);

            DsaKeyGenerationParameters _dsa_key_gen_params = new DsaKeyGenerationParameters(_secure_random, _dsa_param_gen.GenerateParameters());

            _dsa_key_pair_gen.Init(_dsa_key_gen_params);
            _key_pair = _dsa_key_pair_gen.GenerateKeyPair();

            _private_key_param = (DsaPrivateKeyParameters)_key_pair.Private;
            _public_key_param = (DsaPublicKeyParameters)_key_pair.Public;
        }
        public void TestCreationDSA()
        {
            IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            IBigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

            //			Assert.IsTrue((cert.IsValidNow && cert.Verify(dsaPub)), "Certificate failed to be valid (DSA Test)");
            cert.CheckValidity();
            cert.Verify(dsaPub);

            ISet dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();

            dummySet = cert.GetNonCriticalExtensionOids();
            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 18
0
        /**
        * Read a Key Pair
        */
        private object ReadPrivateKey(PemObject pemObject)
        {
            //
            // extract the key
            //
            Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY"));

            string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();
            byte[] keyBytes = pemObject.Content;

            IDictionary fields = Platform.CreateHashtable();
            foreach (PemHeader header in pemObject.Headers)
            {
                fields[header.Name] = header.Value;
            }

            string procType = (string) fields["Proc-Type"];

            if (procType == "4,ENCRYPTED")
            {
                if (pFinder == null)
                    throw new PasswordException("No password finder specified, but a password is required");

                char[] password = pFinder.GetPassword();

                if (password == null)
                    throw new PasswordException("Password is null, but a password is required");

                string dekInfo = (string) fields["DEK-Info"];
                string[] tknz = dekInfo.Split(',');

                string dekAlgName = tknz[0].Trim();
                byte[] iv = Hex.Decode(tknz[1].Trim());

                keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
            }

            try
            {
                IAsymmetricKeyParameter pubSpec, privSpec;
                Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(keyBytes);

                switch (type)
                {
                    case "RSA":
                    {
                        if (seq.Count != 9)
                            throw new PemException("malformed sequence in RSA private key");

                        RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);

                        pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
                        privSpec = new RsaPrivateCrtKeyParameters(
                            rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                            rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                            rsa.Coefficient);

                        break;
                    }

                    case "DSA":
                    {
                        if (seq.Count != 6)
                            throw new PemException("malformed sequence in DSA private key");

                        // TODO Create an ASN1 object somewhere for this?
                        //DerInteger v = (DerInteger)seq[0];
                        DerInteger p = (DerInteger)seq[1];
                        DerInteger q = (DerInteger)seq[2];
                        DerInteger g = (DerInteger)seq[3];
                        DerInteger y = (DerInteger)seq[4];
                        DerInteger x = (DerInteger)seq[5];

                        DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);

                        privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
                        pubSpec = new DsaPublicKeyParameters(y.Value, parameters);

                        break;
                    }

                    case "EC":
                    {
                        ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq);
                        AlgorithmIdentifier algId = new AlgorithmIdentifier(
                            X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

                        PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());

                        // TODO Are the keys returned here ECDSA, as Java version forces?
                        privSpec = PrivateKeyFactory.CreateKey(privInfo);

                        DerBitString pubKey = pKey.GetPublicKey();
                        if (pubKey != null)
                        {
                            SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());

                            // TODO Are the keys returned here ECDSA, as Java version forces?
                            pubSpec = PublicKeyFactory.CreateKey(pubInfo);
                        }
                        else
                        {
                            pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey(
                                (ECPrivateKeyParameters)privSpec);
                        }

                        break;
                    }

                    case "ENCRYPTED":
                    {
                        char[] password = pFinder.GetPassword();

                        if (password == null)
                            throw new PasswordException("Password is null, but a password is required");

                        return PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq));
                    }

                    case "":
                    {
                        return PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq));
                    }

                    default:
                        throw new ArgumentException("Unknown key type: " + type, "type");
                }

                return new AsymmetricCipherKeyPair(pubSpec, privSpec);
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new PemException(
                    "problem creating " + type + " private key: " + e.ToString());
            }
        }
Exemplo n.º 19
0
 protected bool Equals(
     DsaPublicKeyParameters other)
 {
     return(y.Equals(other.y) && base.Equals(other));
 }
Exemplo n.º 20
0
		private bool VerifyDsa(byte[] buffer, int length, byte[] signature)
		{
			int numberSize = 64 + PublicKey[0] * 8;

			DsaPublicKeyParameters parameters = new DsaPublicKeyParameters(
				new BigInteger(1, PublicKey, 21 + 2 * numberSize, numberSize),
				new DsaParameters(
					new BigInteger(1, PublicKey, 21, numberSize),
					new BigInteger(1, PublicKey, 1, 20),
					new BigInteger(1, PublicKey, 21 + numberSize, numberSize))
				);

			var dsa = new DsaSigner();
			dsa.Init(false, parameters);

			var sha1 = new Sha1Digest();

			sha1.BlockUpdate(buffer, 0, length);
			byte[] hash = new byte[sha1.GetDigestSize()];
			sha1.DoFinal(hash, 0);

			return dsa.VerifySignature(hash, new BigInteger(1, signature, 1, 20), new BigInteger(1, signature, 21, 20));
		}