Пример #1
0
        public static string TestDecrypt()
        {
            var privateKey = "pX/BvdXXUdpC79mW/jWi10Z6PJb5SBY2+aqkR/qYOjqgakKsqZFKnl0kz10Ve+BP";
            var token      = "BDiRKNnPiPUb5oala31nkmCaXMB0iyWy3Q93p6fN7vPxEQSUlFVsInkJzPBBqmW1FUIY1KBA3BQb3W3Qv4akZ8kblqbmvupE/EJzPKbROZFBNvxpvVOHHgO2qadmHAjHSmnxUuxrpKxopWnOgyhzUx+mBUTao0pcEgqZFw0Y/qZIJPf1KusCMlz5TAhpjsw=";

            // #####
            // ##### Step 1
            // #####
            var decodedToken = Convert.FromBase64String(token);
            var decodedEphemeralPublicKey      = decodedToken.Take(97).ToArray();
            var encodedEphemeralPublicKeyCheck = Convert.ToBase64String(decodedEphemeralPublicKey);

            if (encodedEphemeralPublicKeyCheck != "BDiRKNnPiPUb5oala31nkmCaXMB0iyWy3Q93p6fN7vPxEQSUlFVsInkJzPBBqmW1FUIY1KBA3BQb3W3Qv4akZ8kblqbmvupE/EJzPKbROZFBNvxpvVOHHgO2qadmHAjHSg==")
            {
                throw new Exception("Public key check failed");
            }

            X9ECParameters curveParams = ECNamedCurveTable.GetByName("secp384r1");

            Org.BouncyCastle.Math.EC.ECPoint decodePoint = curveParams.Curve.DecodePoint(decodedEphemeralPublicKey);
            ECDomainParameters    domainParams           = new ECDomainParameters(curveParams.Curve, curveParams.G, curveParams.N, curveParams.H, curveParams.GetSeed());
            ECPublicKeyParameters ecPublicKeyParameters  = new ECPublicKeyParameters(decodePoint, domainParams);

            var x = ecPublicKeyParameters.Q.AffineXCoord.ToBigInteger();
            var y = ecPublicKeyParameters.Q.AffineYCoord.ToBigInteger();

            if (!x.Equals(new BigInteger("8706462696031173094919866327685737145866436939551712382591956952075131891462487598200779332295613073905587629438229")))
            {
                throw new Exception("X coord check failed");
            }

            if (!y.Equals(new BigInteger("10173258529327482491525749925661342501140613951412040971418641469645769857676705559747557238888921287857458976966474")))
            {
                throw new Exception("Y coord check failed");
            }

            Console.WriteLine("Step 1 complete");

            // #####
            // ##### Step 2
            // #####
            var privateKeyBytes        = Convert.FromBase64String(privateKey);
            var ecPrivateKeyParameters = new ECPrivateKeyParameters("ECDHC", new BigInteger(1, privateKeyBytes), domainParams);
            var privateKeyInfo         = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecPrivateKeyParameters);
            var ecPrivateKey           = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privateKeyInfo);

            IBasicAgreement agree = AgreementUtilities.GetBasicAgreement("ECDHC");

            agree.Init(ecPrivateKey);
            BigInteger sharedKey       = agree.CalculateAgreement(ecPublicKeyParameters);
            var        sharedKeyBytes  = sharedKey.ToByteArrayUnsigned();
            var        sharedKeyBase64 = Convert.ToBase64String(sharedKeyBytes);

            if (sharedKeyBase64 != "2lvSJsBO2keUHRfvPG6C1RMUmGpuDbdgNrZ9YD7RYnvAcfgq/fjeYr1p0hWABeif")
            {
                throw new Exception("Shared key check failed");
            }

            Console.WriteLine("Step 2 complete");

            // #####
            // ##### Step 3
            // #####
            var kdf2Bytes  = Kdf2(sharedKeyBytes, decodedEphemeralPublicKey);
            var kdf2Base64 = Convert.ToBase64String(kdf2Bytes);

            if (kdf2Base64 != "mAzkYatDlz4SzrCyM23NhgL/+mE3eGgfUz9h1CFPhZOtXequzN3Q8w+B5GE2eU5g")
            {
                throw new Exception("Kdf2 failed");
            }

            Console.WriteLine("Step 3 complete");

            // #####
            // ##### Step 4
            // #####
            var decryptionKeyBytes = kdf2Bytes.Take(32).ToArray();
            var decryptionIvBytes  = kdf2Bytes.Skip(32).ToArray();

            var decryptionKeyBase64 = Convert.ToBase64String(decryptionKeyBytes);
            var decryptionIvBase64  = Convert.ToBase64String(decryptionIvBytes);

            if (decryptionKeyBase64 != "mAzkYatDlz4SzrCyM23NhgL/+mE3eGgfUz9h1CFPhZM=")
            {
                throw new Exception("Decryption key check failed");
            }

            if (decryptionIvBase64 != "rV3qrszd0PMPgeRhNnlOYA==")
            {
                throw new Exception("Decryption iv check failed");
            }

            var encryptedDataBytes = decodedToken.Skip(97).Take(decodedToken.Length - 113).ToArray();
            var tagBytes           = decodedToken.Skip(decodedToken.Length - 16).ToArray();

            var encryptedDataBase64 = Convert.ToBase64String(encryptedDataBytes);
            var tagBase64           = Convert.ToBase64String(tagBytes);

            if (encryptedDataBase64 != "afFS7GukrGilac6DKHNTH6YFRNqjSlwSCpkXDRj+")
            {
                throw new Exception("Encrypted data check failed");
            }

            if (tagBase64 != "pkgk9/Uq6wIyXPlMCGmOzA==")
            {
                throw new Exception("Tag check failed");
            }

            KeyParameter     keyParam   = ParameterUtilities.CreateKeyParameter("AES", decryptionKeyBytes);
            ParametersWithIV parameters = new ParametersWithIV(keyParam, decryptionIvBytes);
            IBufferedCipher  cipher     = CipherUtilities.GetCipher("AES/GCM/NoPadding");

            cipher.Init(false, parameters);
            var resultBytes  = cipher.DoFinal(encryptedDataBytes.Concat(tagBytes).ToArray());
            var resultBase64 = Convert.ToBase64String(resultBytes);
            var resultString = Strings.FromByteArray(resultBytes);

            if (resultString != "xXTi32iZwrQ6O8Sy6r1isKwF6Ff1Py")
            {
                throw new Exception("Decryption failed");
            }

            Console.WriteLine("Step 4 complete");
            Console.WriteLine(resultString);

            Console.WriteLine();
            Console.WriteLine("Done... press any key to finish");
            Console.ReadLine();

            return(resultString);
        }
Пример #2
0
        private void doTestGP(
            string algName,
            int size,
            int privateValueSize,
            BigInteger g,
            BigInteger p)
        {
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            DHParameters            dhParams = new DHParameters(p, g, null, privateValueSize);
            KeyGenerationParameters kgp      = new DHKeyGenerationParameters(new SecureRandom(), dhParams);

            keyGen.Init(kgp);

            //
            // a side
            //
            AsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);

            checkKeySize(privateValueSize, aKeyPair);

            aKeyAgreeBasic.Init(aKeyPair.Private);

            //
            // b side
            //
            AsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);

            checkKeySize(privateValueSize, bKeyPair);

            bKeyAgreeBasic.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
//			bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
//			BigInteger  k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
//			BigInteger  k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
            BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
            BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail(size + " bit 2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[]              pubEnc = aKeyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory          keyFac = KeyFactory.getInstance(algName);
//			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
//			DHPublicKey         pubKey = (DHPublicKey)keyFac.generatePublic(pubX509);
            DHPublicKeyParameters pubKey = (DHPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);
//			DHParameterSpec     spec = pubKey.Parameters;
            DHParameters spec = pubKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit public key encoding/decoding test failed on parameters");
            }

            if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
            {
                Fail(size + " bit public key encoding/decoding test failed on y value");
            }

            //
            // public key serialisation test
            //
            // TODO Put back in
//			MemoryStream bOut = new MemoryStream();
//			ObjectOutputStream oOut = new ObjectOutputStream(bOut);
//
//			oOut.WriteObject(aKeyPair.Public);
//
//			MemoryStream bIn = new MemoryStream(bOut.ToArray(), false);
//			ObjectInputStream oIn = new ObjectInputStream(bIn);
//
//			pubKey = (DHPublicKeyParameters)oIn.ReadObject();
            spec = pubKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit public key serialisation test failed on parameters");
            }

            if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
            {
                Fail(size + " bit public key serialisation test failed on y value");
            }

            //
            // private key encoding test
            //
//			byte[] privEnc = aKeyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();
//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			DHPrivateKeyParameters privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8);
            DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

            spec = privKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit private key encoding/decoding test failed on parameters");
            }

            if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
            {
                Fail(size + " bit private key encoding/decoding test failed on y value");
            }

            //
            // private key serialisation test
            //
            // TODO Put back in
//			bOut = new MemoryStream();
//			oOut = new ObjectOutputStream(bOut);
//
//			oOut.WriteObject(aKeyPair.Private);
//
//			bIn = new MemoryStream(bOut.ToArray(), false);
//			oIn = new ObjectInputStream(bIn);
//
//			privKey = (DHPrivateKeyParameters)oIn.ReadObject();
            spec = privKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit private key serialisation test failed on parameters");
            }

            if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
            {
                Fail(size + " bit private key serialisation test failed on y value");
            }

            //
            // three party test
            //
            IAsymmetricCipherKeyPairGenerator aPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            aPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            AsymmetricCipherKeyPair aPair = aPairGen.GenerateKeyPair();

            IAsymmetricCipherKeyPairGenerator bPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            bPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            AsymmetricCipherKeyPair bPair = bPairGen.GenerateKeyPair();

            IAsymmetricCipherKeyPairGenerator cPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            cPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            AsymmetricCipherKeyPair cPair = cPairGen.GenerateKeyPair();


            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            aKeyAgree.Init(aPair.Private);

            IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            bKeyAgree.Init(bPair.Private);

            IBasicAgreement cKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            cKeyAgree.Init(cPair.Private);

//			Key ac = aKeyAgree.doPhase(cPair.Public, false);
//			Key ba = bKeyAgree.doPhase(aPair.Public, false);
//			Key cb = cKeyAgree.doPhase(bPair.Public, false);
//
//			aKeyAgree.doPhase(cb, true);
//			bKeyAgree.doPhase(ac, true);
//			cKeyAgree.doPhase(ba, true);
//
//			BigInteger aShared = new BigInteger(aKeyAgree.generateSecret());
//			BigInteger bShared = new BigInteger(bKeyAgree.generateSecret());
//			BigInteger cShared = new BigInteger(cKeyAgree.generateSecret());

            DHPublicKeyParameters ac = new DHPublicKeyParameters(aKeyAgree.CalculateAgreement(cPair.Public), spec);
            DHPublicKeyParameters ba = new DHPublicKeyParameters(bKeyAgree.CalculateAgreement(aPair.Public), spec);
            DHPublicKeyParameters cb = new DHPublicKeyParameters(cKeyAgree.CalculateAgreement(bPair.Public), spec);

            BigInteger aShared = aKeyAgree.CalculateAgreement(cb);
            BigInteger bShared = bKeyAgree.CalculateAgreement(ac);
            BigInteger cShared = cKeyAgree.CalculateAgreement(ba);

            if (!aShared.Equals(bShared))
            {
                Fail(size + " bit 3-way test failed (a and b differ)");
            }

            if (!cShared.Equals(bShared))
            {
                Fail(size + " bit 3-way test failed (c and b differ)");
            }
        }
Пример #3
0
            /// <summary>
            /// Import the PKCS key.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <param name="passwordPrompt">The pass phrase prompt.</param>
            /// <returns></returns>
            /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception>
            /// <exception cref="InvalidKeySetException">Unsupported key type!</exception>
            public virtual ImportedKeySet PkcsKey(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null)
            {
                using (var password = CachedPrompt.Password(passwordPrompt))
                {
                    AsymmetricKeyParameter bouncyKey;
                    var resetStream = Utility.ResetStreamWhenFinished(input);
                    using (var streamReader = new NondestructiveStreamReader(input))
                    {
                        bouncyKey =
                            new PemReader(streamReader, new PasswordFinder(password.Prompt)).ReadObject() as
                            AsymmetricKeyParameter;
                    }

                    if (bouncyKey == null)
                    {
                        resetStream.Reset();
                        bouncyKey = passwordPrompt == null
                                        ? PrivateKeyFactory.CreateKey(input)
                                        : PrivateKeyFactory.DecryptKey(
                            (password.Prompt() ?? String.Empty).ToCharArray(), input);
                    }

                    Key key;

                    if (bouncyKey is RsaPrivateCrtKeyParameters)
                    {
                        var keyParam = bouncyKey as RsaPrivateCrtKeyParameters;
                        key = new RsaPrivateKey()
                        {
                            PublicKey = new RsaPublicKey()
                            {
                                Modulus        = keyParam.Modulus.ToSystemBigInteger(),
                                PublicExponent = keyParam.PublicExponent.ToSystemBigInteger(),
                                Size           = keyParam.Modulus.BitLength,
                            },
                            PrimeP          = keyParam.P.ToSystemBigInteger(),
                            PrimeExponentP  = keyParam.DP.ToSystemBigInteger(),
                            PrimeExponentQ  = keyParam.DQ.ToSystemBigInteger(),
                            PrimeQ          = keyParam.Q.ToSystemBigInteger(),
                            CrtCoefficient  = keyParam.QInv.ToSystemBigInteger(),
                            PrivateExponent = keyParam.Exponent.ToSystemBigInteger(),
                            Size            = keyParam.Modulus.BitLength,
                        };
                    }
                    else if (bouncyKey is DsaPrivateKeyParameters)
                    {
                        var keyParam = bouncyKey as DsaPrivateKeyParameters;
                        if (KeyPurpose.DecryptAndEncrypt == purpose)
                        {
                            throw new InvalidKeySetException("DSA key cannot be used for encryption and decryption!");
                        }


                        key = new DsaPrivateKey()
                        {
                            X         = keyParam.X.ToSystemBigInteger(),
                            PublicKey = new DsaPublicKey
                            {
                                Y =
                                    keyParam.Parameters.G.ModPow(keyParam.X,
                                                                 keyParam.Parameters.P)
                                    .ToSystemBigInteger(),
                                G    = keyParam.Parameters.G.ToSystemBigInteger(),
                                P    = keyParam.Parameters.P.ToSystemBigInteger(),
                                Q    = keyParam.Parameters.Q.ToSystemBigInteger(),
                                Size = keyParam.Parameters.P.BitLength
                            },
                            Size = keyParam.Parameters.P.BitLength
                        };
                    }
                    else
                    {
                        throw new InvalidKeySetException("Unsupported key type!");
                    }


                    return(new ImportedKeySet(key, purpose, "imported from pkcs file"));
                }
            }
Пример #4
0
 public static AsymmetricKeyParameter PrivateKeyFrom(byte[] privateKeyContents)
 {
     return(PrivateKeyFactory.CreateKey(privateKeyContents));
 }
Пример #5
0
        private void doTestECDH(
            string algorithm)
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm);

//			EllipticCurve curve = new EllipticCurve(
//				new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q
//				new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
//				new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),         // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));        // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
//				ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"),      // n
                BigInteger.One);                                                                                 //1); // h

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            //
            // a side
            //
            AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();

            IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            aKeyAgreeBasic.Init(aKeyPair.Private);

            //
            // b side
            //
            AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();

            IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            bKeyAgreeBasic.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
//			bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
//			BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
//			BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
            BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
            BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail(algorithm + " 2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[] pubEnc = aKeyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory keyFac = KeyFactory.getInstance(algorithm);
//			X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

            ECDomainParameters ecDP = pubKey.Parameters;

//			if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW()))
            ECPoint pq1 = pubKey.Q.Normalize(), pq2 = ((ECPublicKeyParameters)aKeyPair.Public).Q.Normalize();

            if (!pq1.Equals(pq2))
            {
//				Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX());
//				Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY());
//				Fail(algorithm + " public key encoding (W test) failed");
                Console.WriteLine(" expected " + pq1.AffineXCoord.ToBigInteger()
                                  + " got " + pq2.AffineXCoord.ToBigInteger());
                Console.WriteLine(" expected " + pq1.AffineYCoord.ToBigInteger()
                                  + " got " + pq2.AffineYCoord.ToBigInteger());
                Fail(algorithm + " public key encoding (Q test) failed");
            }

//			if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator()))
            if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G))
            {
                Fail(algorithm + " public key encoding (G test) failed");
            }

            //
            // private key encoding test
            //
//			byte[] privEnc = aKeyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
            {
//				Fail(algorithm + " private key encoding (S test) failed");
                Fail(algorithm + " private key encoding (D test) failed");
            }

//			if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator()))
            if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G))
            {
                Fail(algorithm + " private key encoding (G test) failed");
            }
        }
Пример #6
0
        private void DoTestECDH(string algorithm)
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm);

            X9ECParameters     x9     = ECNamedCurveTable.GetByName("prime239v1");
            ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H);

            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            //
            // a side
            //
            AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();

            IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            aKeyAgreeBasic.Init(aKeyPair.Private);

            //
            // b side
            //
            AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();

            IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            bKeyAgreeBasic.Init(bKeyPair.Private);

            //
            // agreement
            //
            BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
            BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail(algorithm + " 2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[] pubEnc = aKeyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory keyFac = KeyFactory.getInstance(algorithm);
//			X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

            ECDomainParameters ecDP = pubKey.Parameters;

//			if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW()))
            ECPoint pq1 = pubKey.Q.Normalize(), pq2 = ((ECPublicKeyParameters)aKeyPair.Public).Q.Normalize();

            if (!pq1.Equals(pq2))
            {
//				Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX());
//				Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY());
//				Fail(algorithm + " public key encoding (W test) failed");
                Console.WriteLine(" expected " + pq1.AffineXCoord.ToBigInteger()
                                  + " got " + pq2.AffineXCoord.ToBigInteger());
                Console.WriteLine(" expected " + pq1.AffineYCoord.ToBigInteger()
                                  + " got " + pq2.AffineYCoord.ToBigInteger());
                Fail(algorithm + " public key encoding (Q test) failed");
            }

//			if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator()))
            if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G))
            {
                Fail(algorithm + " public key encoding (G test) failed");
            }

            //
            // private key encoding test
            //
//			byte[] privEnc = aKeyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
            {
//				Fail(algorithm + " private key encoding (S test) failed");
                Fail(algorithm + " private key encoding (D test) failed");
            }

//			if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator()))
            if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G))
            {
                Fail(algorithm + " private key encoding (G test) failed");
            }
        }
Пример #7
0
        /// <summary>
        ///     Private Key Convert Pkcs1->xml
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyPkcs1ToXml(string privateKey)
        {
            privateKey = Pkcs1PrivateKeyFormat(privateKey);

            var pr = new PemReader(new StringReader(privateKey));

            if (!(pr.ReadObject() is AsymmetricCipherKeyPair asymmetricCipherKeyPair)
                )
            {
                throw new Exception("Private key format is incorrect");
            }
            var rsaPrivateCrtKeyParameters =
                (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(
                    PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                        asymmetricCipherKeyPair.Private));

            var privatElement = new XElement("RSAKeyValue");
            //Modulus
            var primodulus = new XElement("Modulus",
                                          Convert.ToBase64String(rsaPrivateCrtKeyParameters.Modulus
                                                                 .ToByteArrayUnsigned()));
            //Exponent
            var priexponent = new XElement("Exponent",
                                           Convert.ToBase64String(rsaPrivateCrtKeyParameters.PublicExponent
                                                                  .ToByteArrayUnsigned()));
            //P
            var prip = new XElement("P",
                                    Convert.ToBase64String(rsaPrivateCrtKeyParameters.P
                                                           .ToByteArrayUnsigned()));
            //Q
            var priq = new XElement("Q",
                                    Convert.ToBase64String(rsaPrivateCrtKeyParameters.Q
                                                           .ToByteArrayUnsigned()));
            //DP
            var pridp = new XElement("DP",
                                     Convert.ToBase64String(rsaPrivateCrtKeyParameters.DP
                                                            .ToByteArrayUnsigned()));
            //DQ
            var pridq = new XElement("DQ",
                                     Convert.ToBase64String(rsaPrivateCrtKeyParameters.DQ
                                                            .ToByteArrayUnsigned()));
            //InverseQ
            var priinverseQ = new XElement("InverseQ",
                                           Convert.ToBase64String(rsaPrivateCrtKeyParameters.QInv
                                                                  .ToByteArrayUnsigned()));
            //D
            var prid = new XElement("D",
                                    Convert.ToBase64String(rsaPrivateCrtKeyParameters.Exponent
                                                           .ToByteArrayUnsigned()));

            privatElement.Add(primodulus);
            privatElement.Add(priexponent);
            privatElement.Add(prip);
            privatElement.Add(priq);
            privatElement.Add(pridp);
            privatElement.Add(pridq);
            privatElement.Add(priinverseQ);
            privatElement.Add(prid);

            return(privatElement.ToString());
        }
Пример #8
0
        public static RsaKeyParameters GetDeserializedPrivateKey(string serializedPrivateKey)
        {
            RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(serializedPrivateKey));

            return(privateKey);
        }
Пример #9
0
        public void SaveNotebooks(bool background)
        {
            AsymmetricCipherKeyPair kp = new AsymmetricCipherKeyPair(PublicKeyFactory.CreateKey(m_pubKey), PrivateKeyFactory.CreateKey(m_decPrivKey));

            m_mgr.SaveNotebooks(kp, background);
        }
Пример #10
0
        public void Start()
        {
            m_mgr.OnNotebooksLoaded += new EventHandler((o, e) =>
            {
                if ((bool)o == false)
                {
                    return;
                }
                //create the master detail page
                HomeMDP mdp = new HomeMDP();
                ((HomeMDPMaster)mdp.Master).ListView.ItemsSource = m_mgr.Notebooks;
                //display page
                mdp.NavigationPage.PushAsync(new HomePage());
                App.Current.MainPage = mdp;
            });
            AsymmetricCipherKeyPair kp = new AsymmetricCipherKeyPair(PublicKeyFactory.CreateKey(m_pubKey), PrivateKeyFactory.CreateKey(m_decPrivKey));

            m_mgr.LoadNotebooks(kp);
        }