コード例 #1
0
        public byte[] computeSharedSecret(byte[] pri, byte[] pub)
        {
            const string Algorithm = "ECDH";
            //const int KeyBitSize = 128;

            X9ECParameters     ecPars    = NistNamedCurves.GetByName("P-256");
            ECDomainParameters ecDomPars = new ECDomainParameters(ecPars.Curve, ecPars.G, ecPars.N, ecPars.H, ecPars.GetSeed());
            var curve = ecDomPars.Curve;

            var pubQ = curve.DecodePoint(pub);
            //ECPoint pubQ = ecPars.Curve.DecodePoint(pub);
            //ECPoint priQ = curve.DecodePoint(pri);
            IBasicAgreement _aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            //csPri = ((ECPrivateKeyParameters)aliceKeyPair.Private).D.ToByteArray();
            var priKeyPara = new ECPrivateKeyParameters(new BigInteger(pri), ecDomPars);            //priQ.Curve.

            _aliceKeyAgree.Init(priKeyPara);

            AsymmetricKeyParameter pubKeyPara = new ECPublicKeyParameters(pubQ, ecDomPars);
            //SubjectPublicKeyInfo _key = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKeyPara);
            //var pubPara = new ECPublicKeyParameters(priQ, ecDomPars);
            BigInteger aliceAgree = _aliceKeyAgree.CalculateAgreement(pubKeyPara);

            KeyParameter sharedKey = new KeyParameter(aliceAgree.ToByteArrayUnsigned());

            //return sharedKey.;
            return(sharedKey.GetKey());
        }
コード例 #2
0
        public void SimpleTest()
        {
            var generator = new DHParametersGenerator();

            generator.Init(1024, 7, new SecureRandom());

            var dhParameters = generator.GenerateParameters();

            KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), dhParameters);
            var keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            keyGen.Init(kgp);

            var serverKeyPair  = keyGen.GenerateKeyPair();
            var serverKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            serverKeyAgree.Init(serverKeyPair.Private);

            var clientKeyPair  = keyGen.GenerateKeyPair();
            var clientKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            clientKeyAgree.Init(clientKeyPair.Private);

            var serverAgree = serverKeyAgree.CalculateAgreement(clientKeyPair.Public);
            var clientAgree = clientKeyAgree.CalculateAgreement(serverKeyPair.Public);

            Assert.Equal(serverAgree, clientAgree);
        }
コード例 #3
0
ファイル: Scp11Context.cs プロジェクト: qpernil/libusb-tester
        public ECPrivateKeyParameters GenerateKeyPair(string password = null)
        {
            AsymmetricCipherKeyPair pair;

            if (password == null)
            {
                pair = generator.GenerateKeyPair();
            }
            else
            {
                var bytes = Scp03Context.Pkcs5Pbkdf2Hmac(password).GetKey();
                var sk    = new ECPrivateKeyParameters(new BigInteger(1, bytes), domain);
                var pk    = new ECPublicKeyParameters(domain.G.Multiply(sk.D), domain);
                pair = new AsymmetricCipherKeyPair(pk, sk);
            }

            pk_oce = (ECPublicKeyParameters)pair.Public;

            sk_oce = AgreementUtilities.GetBasicAgreement("ECDH");
            sk_oce.Init(pair.Private);

            shsss = sk_oce.CalculateAgreement(pk_sd).ToByteArrayFixed();

            return((ECPrivateKeyParameters)pair.Private);
        }
コード例 #4
0
        public static EncryptionResult Encrypt(byte[] userKey, byte[] userSecret, byte[] payload)
        {
            var salt          = GenerateSalt(16);
            var serverKeyPair = ECKeyHelper.GenerateKeys();

            var ecdhAgreement = AgreementUtilities.GetBasicAgreement("ECDH");

            ecdhAgreement.Init(serverKeyPair.Private);

            var userPublicKey = ECKeyHelper.GetPublicKey(userKey);

            var key             = ecdhAgreement.CalculateAgreement(userPublicKey).ToByteArrayUnsigned();
            var serverPublicKey = ((ECPublicKeyParameters)serverKeyPair.Public).Q.GetEncoded(false);

            var prk   = HKDF(userSecret, key, Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32);
            var cek   = HKDF(salt, prk, CreateInfoChunk("aesgcm", userKey, serverPublicKey), 16);
            var nonce = HKDF(salt, prk, CreateInfoChunk("nonce", userKey, serverPublicKey), 12);

            var input            = AddPaddingToInput(payload);
            var encryptedMessage = EncryptAes(nonce, cek, input);

            return(new EncryptionResult
            {
                Salt = salt,
                Payload = encryptedMessage,
                PublicKey = serverPublicKey
            });
        }
コード例 #5
0
        public static void TestMethod()
        {
            //BEGIN SETUP ALICE
            var aliceKeyGen    = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            var aliceGenerator = new DHParametersGenerator();

            aliceGenerator.Init(KeyBitSize, DefaultPrimeProbability, new SecureRandom());
            DHParameters aliceParameters = aliceGenerator.GenerateParameters();

            var aliceKGP = new DHKeyGenerationParameters(new SecureRandom(), aliceParameters);

            aliceKeyGen.Init(aliceKGP);

            AsymmetricCipherKeyPair aliceKeyPair = aliceKeyGen.GenerateKeyPair();
            var aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            aliceKeyAgree.Init(aliceKeyPair.Private);
            //END SETUP ALICE

            /////AT THIS POINT, Alice's Public Key, Alice's Parameter P and Alice's Parameter G are sent unsecure to BOB

            //BEGIN SETUP BOB
            var          bobKeyGen     = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            DHParameters bobParameters = new DHParameters(aliceParameters.P, aliceParameters.G);

            KeyGenerationParameters bobKGP = new DHKeyGenerationParameters(new SecureRandom(), bobParameters);

            bobKeyGen.Init(bobKGP);

            AsymmetricCipherKeyPair bobKeyPair  = bobKeyGen.GenerateKeyPair();
            IBasicAgreement         bobKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            bobKeyAgree.Init(bobKeyPair.Private);
            //END SETUP BOB

            BigInteger aliceAgree = aliceKeyAgree.CalculateAgreement(bobKeyPair.Public);
            BigInteger bobAgree   = bobKeyAgree.CalculateAgreement(aliceKeyPair.Public);

            if (!aliceAgree.Equals(bobAgree))
            {
                throw new Exception("Keys do not match.");
            }

            byte[] nonSecretMessage = GetBytes("HeaderMessageForASDF");
            byte[] secretMessage    = GetBytes("Secret message contents");
            byte[] decNonSecretBytes;

            KeyParameter sharedKey = new KeyParameter(aliceAgree.ToByteArrayUnsigned());

            var encMessage = EncryptMessage(sharedKey, nonSecretMessage, secretMessage);
            var decMessage = DecryptMessage(sharedKey, encMessage, out decNonSecretBytes);

            var decNonSecretMessage = GetString(decNonSecretBytes);
            var decSecretMessage    = GetString(decMessage);

            Debug.WriteLine(decNonSecretMessage + " - " + decSecretMessage);

            return;
        }
コード例 #6
0
        public static void ECDHKeyExchangeExample()
        {
            /*NOTE: this should represent an example of ECDH. As there are no mechanisms used in order to ensure if Alice is Alice and Bob is Bob as now
             * certificate is used in this example. */

            /* Define used key exchange algorithm. In our case this is elliptic curve diffie hellmann. */
            const string Algorithm = "ECDH";

            /* ALICE starts the key exchange. She sends the the X and Y coordinates of her public key as well as the used curve to BOB */

            const string Alicebase16strpubX = "0x14CC3B7FBEF441E21DE27CA72F5E2BB60EFEA474A5973028589016D36DB11E267A1F49FD2DC1F42553E0A6BB4E66CA9E8C2667074A7EABAD1A10545626B53F4ECC9";
            const string Alicebase16strY    = "0x190E33894B32DD6FDFDF8E560630B2419CC45A7FF770530CD564354A5D4D7E76DB1F4A1C0DC9E7D5720F257C5A8D2D908C342217300ACD78D258D00EEDDB2C441F5";
            const string curve = "P-521";//"SECP521R1";

            /****************************************************************************/

            /* BOB starts the actions. Bob uses the public public key coordinates as well as the curve to generate an ephemeral key
             * pair on his side.
             */

            X9ECParameters ecP = NistNamedCurves.GetByName(curve);

            FpCurve c = (FpCurve)ecP.Curve;

            ECFieldElement x = c.FromBigInteger(new BigInteger(System.Numerics.BigInteger.Parse(Alicebase16strpubX, NumberStyles.HexNumber).ToString()));
            ECFieldElement y = c.FromBigInteger(new BigInteger(System.Numerics.BigInteger.Parse(Alicebase16strY, NumberStyles.HexNumber).ToString()));

            Org.BouncyCastle.Math.EC.ECPoint q    = new FpPoint(c, x, y);
            ECPublicKeyParameters            xxpk = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);

            IAsymmetricCipherKeyPairGenerator KeyGen       = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            KeyGenerationParameters           keygenParams = new ECKeyGenerationParameters(new ECDomainParameters(ecP.Curve, ecP.G, ecP.N), new SecureRandom());

            KeyGen.Init(keygenParams);

            AsymmetricCipherKeyPair KeyPair  = KeyGen.GenerateKeyPair();
            IBasicAgreement         KeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            /*****************************************************************************/

            /* BOB calculates the SHARED SECRET */
            KeyAgree.Init(KeyPair.Private);
            BigInteger Agree = KeyAgree.CalculateAgreement(xxpk);
            /*****************************************************************************/

            /*BOB encrypts his secret message. Using the Encryption helper method with AES 256 CBC. The helper method is using the last
             * 16 bytes of the generated secret and a generated initial vector of 16 byte to encrypt*/
            string ciphertext             = Encryption.EncryptString("Hallo Alice, this is an important message to you.", Agree.ToByteArray());
            ECPublicKeyParameters params2 = (ECPublicKeyParameters)KeyPair.Public;

            /*****************************************************************************/

            /*BOB is sending the x and y coordinates of his public key and the encrypted message to Alice on a public (not secured) channel*/
            Console.WriteLine("PublicKeyX Base(16): " + params2.Q.XCoord.ToBigInteger().ToString(16).ToUpper());
            Console.WriteLine("PublicKeyY Base(16): " + params2.Q.YCoord.ToBigInteger().ToString(16).ToUpper());
            Console.WriteLine("Ciphertext: " + ciphertext);
            /*****************************************************************************/
        }
コード例 #7
0
        private void ExchangeSessionKey(string remoteIp, int port)
        {
            Console.WriteLine("start exchanging key");

            //ECDH鍵共有のための鍵ペアを生成
            var ecKeyGen    = new ECKeyPairGenerator();
            var keyGenParam = new KeyGenerationParameters(new SecureRandom(), 256);

            ecKeyGen.Init(keyGenParam);
            var keyPair = ecKeyGen.GenerateKeyPair();

            using (var tcpClient = new TcpClient(remoteIp, port))
                using (var netStream = tcpClient.GetStream())
                    using (var reader = new StreamReader(netStream))
                        using (var writer = new StreamWriter(netStream))
                        {
                            //公開情報を送信
                            writer.WriteLine(Convert.ToBase64String(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public).GetEncoded(), Base64FormattingOptions.None));
                            writer.Flush();

                            //公開情報を受信
                            var kotlinPubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(reader.ReadLine()));

                            //共通鍵を生成
                            var keyAgree = AgreementUtilities.GetBasicAgreement("ECDH");
                            keyAgree.Init(keyPair.Private);
                            var sharedSecret = keyAgree.CalculateAgreement(kotlinPubKey);
                            var dhSecKey     = sharedSecret.ToByteArrayUnsigned();

                            var gen = new Pkcs5S2ParametersGenerator(new Sha256Digest());
                            gen.Init(Encoding.UTF8.GetBytes(pw), dhSecKey, 4096);
                            byte[] secretKey = ((KeyParameter)gen.GenerateDerivedParameters(256)).GetKey();

                            var splitted  = reader.ReadLine().Split(new string[] { "?" }, StringSplitOptions.None);
                            var iv        = Convert.FromBase64String(splitted[0]);
                            var encrypted = Convert.FromBase64String(splitted[1]);

                            try
                            {
                                sessionKey = Decrypt(iv, encrypted, secretKey);
                                writer.WriteLine(Encrypt("ok"));
                                Console.WriteLine("succeeded in exchanging key");
                            }
                            catch (CryptographicException)
                            {
                                writer.WriteLine("e1");
                                mainThreadForm.Invoke(mainThreadForm.writeLogDelegate, "パスワードが一致していません");
                                Stop();
                            }
                            writer.Flush();

                            splitted  = reader.ReadLine().Split(new string[] { "?" }, StringSplitOptions.None);
                            iv        = Convert.FromBase64String(splitted[0]);
                            encrypted = Convert.FromBase64String(splitted[1]);
                            var clientName = Encoding.UTF8.GetString(Decrypt(iv, encrypted));
                            mainThreadForm.Invoke(mainThreadForm.writeLogDelegate, clientName + "が接続しました");
                        }
        }
コード例 #8
0
ファイル: ECKey.cs プロジェクト: Dryec/converse-backend
        public BigInteger GetSharedSecret(ECPublicKeyParameters pub)
        {
            var aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(_privateKey);
            var sharedSecret = aKeyAgree.CalculateAgreement(pub);

            return(sharedSecret);
        }
コード例 #9
0
        /// <summary>
        ///   Create a shared secret between this key and another.
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public byte[] GenerateSharedSecret(EphermalKey other)
        {
            var agreement = AgreementUtilities.GetBasicAgreement("ECDH");

            agreement.Init(privateKey);
            return(agreement
                   .CalculateAgreement(other.publicKey)
                   .ToByteArrayUnsigned());
        }
コード例 #10
0
        public string ComputeSharedSecret(string publicKey)
        {
            DHParameters param            = Parameters;
            var          importedKey      = new DHPublicKeyParameters(new BigInteger(publicKey, 16), param);
            var          internalKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            internalKeyAgree.Init(PrivateKeyParameter);
            return(internalKeyAgree.CalculateAgreement(importedKey).ToString(16));
        }
コード例 #11
0
ファイル: EphermalKey.cs プロジェクト: jakubbober/Catalyst
        /// <summary>
        ///   Create a shared secret between this key and another.
        /// </summary>
        /// <param name="other">
        ///   Another ephermal key.
        /// </param>
        /// <returns>
        ///   The shared secret as a byte array.
        /// </returns>
        /// <remarks>
        ///   Uses the ECDH agreement algorithm to generate the shared secet.
        /// </remarks>
        public byte[] GenerateSharedSecret(EphermalKey other)
        {
            var agreement = AgreementUtilities.GetBasicAgreement("ECDH");

            agreement.Init(_privateKey);
            var secret = agreement.CalculateAgreement(other._publicKey);

            return(BigIntegers.AsUnsignedByteArray(agreement.GetFieldSize(), secret));
        }
コード例 #12
0
    private static string DoECDH(byte[] dataPrv, byte[] dataPub)
    {
        IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH");

        agreement.Init(LoadPrivateKey(dataPrv));
        Org.BouncyCastle.Math.BigInteger sharedSecret = agreement.CalculateAgreement(LoadPublicKey(dataPub));
        byte[] secret = sharedSecret.ToByteArray();
        return(BytesToHex(secret));
    }
コード例 #13
0
        /// <summary>
        /// Generates the shared secret.
        /// </summary>
        /// <returns>The shared secret.</returns>
        /// <param name="clientPrivateKey">Client private key.</param>
        /// <param name="serverPublicKey">Server public key.</param>
        private static BigInteger GenerateSharedSecret(
            ICipherParameters clientPrivateKey,
            ICipherParameters serverPublicKey)
        {
            var agreement = AgreementUtilities.GetBasicAgreement("ECDH");

            agreement.Init(clientPrivateKey);

            return(agreement.CalculateAgreement(serverPublicKey));
        }
コード例 #14
0
        public byte [] Agree()
        {
            IBasicAgreement iba;

            iba = AgreementUtilities.GetBasicAgreement("DH");
            iba.Init(_kp.Private);

            _agreement = iba.CalculateAgreement(RemotePublicKey);
            return(_agreement.ToByteArray());
        }
コード例 #15
0
        private byte[] GenerateSharedSecret(ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKeys)
        {
            var keyParams = privateKey;
            var agree     = AgreementUtilities.GetBasicAgreement("ECDH");

            agree.Init(keyParams);
            var sharedSecret = agree.CalculateAgreement(publicKeys);

            return(sharedSecret.ToByteArrayUnsigned());
        }
コード例 #16
0
        public static byte[] GenerateSharedSecret(ICipherParameters clientPrivateKey, ICipherParameters foreignPublicKey)
        {
            var agreement = AgreementUtilities.GetBasicAgreement(KeyExchangeAlgorithm);

            agreement.Init(clientPrivateKey);

            var bytes = agreement.CalculateAgreement(foreignPublicKey).ToByteArrayUnsigned();

            return(bytes);
        }
コード例 #17
0
        private void doTestDesAndDesEde(
            IBigInteger g,
            IBigInteger p)
        {
            DHParameters dhParams = new DHParameters(p, g, null, 256);

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams));

            IAsymmetricCipherKeyPair kp = keyGen.GenerateKeyPair();

            IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreement("DH");

            keyAgreement.Init(kp.Private);
            IBigInteger agreed = keyAgreement.CalculateAgreement(kp.Public);

            byte[] agreedBytes = agreed.ToByteArrayUnsigned();

            // TODO Figure out where the magic happens of choosing the right
            // bytes from 'agreedBytes' for each key type - need C# equivalent?
            // (see JCEDHKeyAgreement.engineGenerateSecret)

//			SecretKey key = keyAgreement.generateSecret("DES");
//
//			if (key.getEncoded().length != 8)
//			{
//				Fail("DES length wrong");
//			}
//
//			if (!DESKeySpec.isParityAdjusted(key.getEncoded(), 0))
//			{
//				Fail("DES parity wrong");
//			}
//
//			key = keyAgreement.generateSecret("DESEDE");
//
//			if (key.getEncoded().length != 24)
//			{
//				Fail("DESEDE length wrong");
//			}
//
//			if (!DESedeKeySpec.isParityAdjusted(key.getEncoded(), 0))
//			{
//				Fail("DESEDE parity wrong");
//			}
//
//			key = keyAgreement.generateSecret("Blowfish");
//
//			if (key.getEncoded().length != 16)
//			{
//				Fail("Blowfish length wrong");
//			}
        }
コード例 #18
0
        /// <summary>
        ///     Decrypts data wit EC cryptography.
        /// </summary>
        /// <param name="data">Encrypted data.</param>
        /// <param name="privateKey">Private key.</param>
        /// <returns>Plain data.</returns>
        public static byte[] DecryptEc(byte[] data, ECPrivateKeyParameters privateKey)
        {
            var ePublicKey = LoadPublicEcKey(data.Take(65).ToArray());
            var agreement  = AgreementUtilities.GetBasicAgreement("ECDHC");

            agreement.Init(privateKey);
            var key = agreement.CalculateAgreement(ePublicKey).ToByteArrayUnsigned();

            key = SHA256.Create().ComputeHash(key);
            return(DecryptAesV2(data.Skip(65).ToArray(), key));
        }
コード例 #19
0
        public void run()
        {
            AsymmetricCipherKeyPair aKeyPair       = _keyGen.GenerateKeyPair();
            IBasicAgreement         aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgreeBasic.Init(aKeyPair.Private);
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

            IPAddress  ip     = IPAddress.Parse("192.168.1.117");
            IPEndPoint ipe    = new IPEndPoint(ip, 8899);
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(ipe);
            //byte[] bs = Encoding.ASCII.GetBytes("Windows Test");
            socket.Send(pubEnc, pubEnc.Length, 0);

            byte[] recvBytes = new byte[1024];
            int    bytes     = socket.Receive(recvBytes, recvBytes.Length, 0);

            socket.Close();

            byte[] bPub = new byte[bytes];
            for (int i = 0; i < bytes; i++)
            {
                bPub[i] = recvBytes[i];
            }
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(bPub);
            BigInteger            k      = aKeyAgreeBasic.CalculateAgreement(pubKey);

            byte[] keyBytes = k.ToByteArray();
            //Console.WriteLine(keybytes.Length);
            if (keyBytes.Length > 24)
            {
                byte[] fixedKeybytes = new byte[24];
                for (int i = 0; i < 24; i++)
                {
                    fixedKeybytes[i] = keyBytes[i + keyBytes.Length - 24];
                }
                keyBytes = fixedKeybytes;
            }
            Console.WriteLine(Hex.ToHexString(keyBytes));

            IDigest digest = new MD5Digest();

            digest.BlockUpdate(keyBytes, 0, keyBytes.Length);
            byte[] idBytes = new byte[digest.GetDigestSize()];
            digest.DoFinal(idBytes, 0);
            _id = Hex.ToHexString(idBytes);
            Console.WriteLine(_id);
            _trivium = new Trivium();
            _trivium.setKIV(keyBytes);
            _trivium.initProcess();
        }
コード例 #20
0
        public ServerAuthority(DHParameters parameters)
        {
            this.parameters = parameters;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
            KeyGenerationParameters           kgp    = new DHKeyGenerationParameters(new SecureRandom(), parameters);

            keyGen.Init(kgp);
            kp        = keyGen.GenerateKeyPair();
            agreement = AgreementUtilities.GetBasicAgreement("DH");
            agreement.Init(kp.Private);
        }
コード例 #21
0
        private void doTestExplicitWrapping(
            int size,
            int privateValueSize,
            IBigInteger g,
            IBigInteger p)
        {
            DHParameters dhParams = new DHParameters(p, g, null, privateValueSize);

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams));

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

            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            checkKeySize(privateValueSize, aKeyPair);

            aKeyAgree.Init(aKeyPair.Private);

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

            IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            checkKeySize(privateValueSize, bKeyPair);

            bKeyAgree.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgree.doPhase(bKeyPair.Public, true);
//			bKeyAgree.doPhase(aKeyPair.Public, true);
//
//			SecretKey k1 = aKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id);
//			SecretKey k2 = bKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id);

            // TODO Does this really test the same thing as the above code?
            IBigInteger b1 = aKeyAgree.CalculateAgreement(bKeyPair.Public);
            IBigInteger b2 = bKeyAgree.CalculateAgreement(aKeyPair.Public);

            if (!b1.Equals(b2))
            {
                Fail("Explicit wrapping test failed");
            }
        }
コード例 #22
0
        public byte[] FinalizeKeyExchange(byte[] peer_pk)
        {
            PemReader pem = new PemReader(new StringReader(Encoding.UTF8.GetString(peer_pk)));

            ECPublicKeyParameters  peer_ecdh_pk = (ECPublicKeyParameters)pem.ReadObject();
            ECPrivateKeyParameters self_priv    = ECDHEPair.Private as ECPrivateKeyParameters;

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH");

            agreement.Init(self_priv);

            return(agreement.CalculateAgreement(peer_ecdh_pk).ToByteArray());
        }
コード例 #23
0
        private string GeneratePassword()
        {
            DHPublicKeyParameters publicKey = new DHPublicKeyParameters(
                ((DHPublicKeyParameters)PublicKeyFactory.CreateKey(encodedPublicKey)).Y, sharedParameters);

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("DH");

            agreement.Init(keyPair.Private);

            BigInteger agreementValue = agreement.CalculateAgreement(publicKey);

            return(agreementValue.ToString(16));
        }
コード例 #24
0
        public static IEnumerable <byte> GetDeriveKey(byte[] key1, AsymmetricCipherKeyPair senderKeyPair,
                                                      string curveName, string algorithm)
        {
            var ecP       = CustomNamedCurves.GetByName(curveName);
            var ecSpec    = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            var publicKey = new ECPublicKeyParameters(ecSpec.Curve.DecodePoint(key1), ecSpec);
            var agreement = AgreementUtilities.GetBasicAgreement(algorithm);

            agreement.Init(senderKeyPair.Private);
            var result = agreement.CalculateAgreement(publicKey);

            return(result.ToByteArrayUnsigned());
        }
コード例 #25
0
        /// <summary>
        ///     Encrypts data with EC cryptography.
        /// </summary>
        /// <param name="data">Plain text</param>
        /// <param name="publicKey">Public key.</param>
        /// <returns>Encrypted data</returns>
        /// <remarks>[EPHEMERAL PUBLIC KEY][AES GCM ENCRYPTED DATA]</remarks>
        public static byte[] EncryptEc(byte[] data, ECPublicKeyParameters publicKey)
        {
            GenerateEcKey(out var ePrivateKey, out var ePublicKey);
            var agreement = AgreementUtilities.GetBasicAgreement("ECDHC");

            agreement.Init(ePrivateKey);
            var key = agreement.CalculateAgreement(publicKey).ToByteArrayUnsigned();

            key = SHA256.Create().ComputeHash(key);
            var encryptedData = EncryptAesV2(data, key);

            return(UnloadEcPublicKey(ePublicKey).Concat(encryptedData).ToArray());
        }
コード例 #26
0
        public static string ViettelEncryption(string inputText, string viettelPublicKey, string customerPrivateKey)
        {
            string encryptedSMSText = "";

            try
            {
                //string privateKeyConek = @"MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQg1OGD/UuZ3FO9u6e60TmOJne47RWWYGqH7FIzRvxxhruhRANCAAQKJjarvVgOWJz6eg5ncv5WucbRBR2/qJqXpe5Yo9a9NQ7gzOgRBvejgj2q2NFNo9lgZgeFXl4fuoqOiLCGawaO";
                //string publicKeyViettel = @"MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEe9YVVfiuEbTC8MLFcmettM9z6i1bh49kM97NZJ0yLCZcDQtWhuQ230W/nackSySWO8tErAzDWiMdvEACaHevaA==";

                //PublicKey Viettel
                var base64PubKeyStr = viettelPublicKey; // "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEe9YVVfiuEbTC8MLFcmettM9z6i1bh49kM97NZJ0yLCZcDQtWhuQ230W/nackSySWO8tErAzDWiMdvEACaHevaA==";
                var publicKeyBytes  = Convert.FromBase64String(base64PubKeyStr);
                ECPublicKeyParameters otherPartyPublicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(publicKeyBytes);
                Console.WriteLine(otherPartyPublicKey.ToString());

                //PrivateKey
                var base64PrivateKeyStr           = customerPrivateKey; // "MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgnFkCkg26s2pwWa1oV0cYFUUqU0sCDeYP2wRpUQcu74WhRANCAASDBA7GheF0EFqZY8xhQSXhYog6pEEtOBIo64eFBT2JZsPZysxk5i+PQXfVhkvib/tTLag6MuNiL451+u9qPbg5";
                var privateKeyBytes               = Convert.FromBase64String(base64PrivateKeyStr);
                ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privateKeyBytes);
                Console.WriteLine(privateKey.ToString());

                //Make share key
                IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");
                aKeyAgree.Init(privateKey);
                BigInteger sharedSecret      = aKeyAgree.CalculateAgreement(otherPartyPublicKey);
                byte[]     sharedSecretBytes = sharedSecret.ToByteArrayUnsigned();
                var        keyparam          = ParameterUtilities.CreateKeyParameter("AES", sharedSecretBytes);

                var    plainText     = inputText; // "Hello! This is an banksms message!";
                byte[] plainTextByte = Encoding.UTF8.GetBytes(plainText);
                var    bankSmsIv     = "Banksms@Viettel!";
                byte[] iv            = Encoding.UTF8.GetBytes(bankSmsIv);

                var parametersWithIV = new ParametersWithIV(keyparam, iv);
                Console.WriteLine(Encoding.ASCII.GetString(parametersWithIV.GetIV()));
                Console.WriteLine(parametersWithIV.ToString());

                var cipher = CipherUtilities.GetCipher("AES/CBC/PKCS5Padding");
                cipher.Init(true, parametersWithIV);
                byte[] output = cipher.DoFinal(plainTextByte);

                Console.WriteLine(string.Concat(output.Select(b => b.ToString("X2"))));
                encryptedSMSText = string.Concat(output.Select(b => b.ToString("X2")));  // Nội dung sau khi được mã hóa
            } catch (Exception ex)
            {
                Console.WriteLine("Exception ex = " + ex.Message);
            }


            return(encryptedSMSText);
        }
コード例 #27
0
ファイル: MqvTest.cs プロジェクト: tcz1237/MissionPlanner
        public void TestECMqv()
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECMQV");

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

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

            //
            // U side
            //
            AsymmetricCipherKeyPair U1 = g.GenerateKeyPair();
            AsymmetricCipherKeyPair U2 = g.GenerateKeyPair();

            IBasicAgreement uAgree = AgreementUtilities.GetBasicAgreement("ECMQV");

            uAgree.Init(new MqvPrivateParameters(
                            (ECPrivateKeyParameters)U1.Private,
                            (ECPrivateKeyParameters)U2.Private,
                            (ECPublicKeyParameters)U2.Public));

            //
            // V side
            //
            AsymmetricCipherKeyPair V1 = g.GenerateKeyPair();
            AsymmetricCipherKeyPair V2 = g.GenerateKeyPair();

            IBasicAgreement vAgree = AgreementUtilities.GetBasicAgreement("ECMQV");

            vAgree.Init(new MqvPrivateParameters(
                            (ECPrivateKeyParameters)V1.Private,
                            (ECPrivateKeyParameters)V2.Private,
                            (ECPublicKeyParameters)V2.Public));

            //
            // agreement
            //
            BigInteger ux = uAgree.CalculateAgreement(new MqvPublicParameters(
                                                          (ECPublicKeyParameters)V1.Public,
                                                          (ECPublicKeyParameters)V2.Public));
            BigInteger vx = vAgree.CalculateAgreement(new MqvPublicParameters(
                                                          (ECPublicKeyParameters)U1.Public,
                                                          (ECPublicKeyParameters)U2.Public));

            if (!ux.Equals(vx))
            {
                Fail("Agreement failed");
            }
        }
コード例 #28
0
        private static byte[] GetKeyingMaterial(PushSubscription subscription, AsymmetricKeyParameter applicationServerPrivateKey, byte[] applicationServerPublicKey)
        {
            IBasicAgreement ecdhAgreement = AgreementUtilities.GetBasicAgreement("ECDH");

            ecdhAgreement.Init(applicationServerPrivateKey);

            byte[] userAgentPublicKey   = UrlBase64Converter.FromUrlBase64String(subscription.GetKey(PushEncryptionKeyName.P256DH));
            byte[] authenticationSecret = UrlBase64Converter.FromUrlBase64String(subscription.GetKey(PushEncryptionKeyName.Auth));
            byte[] sharedSecret         = ecdhAgreement.CalculateAgreement(ECKeyHelper.GetECPublicKeyParameters(userAgentPublicKey)).ToByteArrayUnsigned();
            byte[] sharedSecretHash     = HmacSha256(authenticationSecret, sharedSecret);
            byte[] infoParameter        = GetKeyingMaterialInfoParameter(userAgentPublicKey, applicationServerPublicKey);
            byte[] keyingMaterial       = HmacSha256(sharedSecretHash, infoParameter);

            return(keyingMaterial);
        }
コード例 #29
0
        /**
         * Add a key agreement based recipient.
         *
         * @param agreementAlgorithm key agreement algorithm to use.
         * @param senderPrivateKey private key to initialise sender side of agreement with.
         * @param senderPublicKey sender public key to include with message.
         * @param recipientCert recipient's public key certificate.
         * @param cekWrapAlgorithm OID for key wrapping algorithm to use.
         * @exception SecurityUtilityException if the algorithm requested cannot be found
         * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
         */
        public void AddKeyAgreementRecipient(
            string agreementAlgorithm,
            AsymmetricKeyParameter senderPrivateKey,
            AsymmetricKeyParameter senderPublicKey,
            X509Certificate recipientCert,
            string cekWrapAlgorithm)
        {
            if (!senderPrivateKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "senderPrivateKey");
            }
            if (senderPublicKey.IsPrivate)
            {
                throw new ArgumentException("Expected public key", "senderPublicKey");
            }

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                agreementAlgorithm, cekWrapAlgorithm);

            agreement.Init(new ParametersWithRandom(senderPrivateKey, rand));

            BigInteger secretNum = agreement.CalculateAgreement(recipientCert.GetPublicKey());

            try
            {
                SubjectPublicKeyInfo oPubKeyInfo =
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(senderPublicKey);

                OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
                    new OriginatorPublicKey(
                        new AlgorithmIdentifier(oPubKeyInfo.AlgorithmID.ObjectID, DerNull.Instance),
                        oPubKeyInfo.PublicKeyData.GetBytes()));

                // TODO Fix the way bytes are derived from the secret
                byte[]       secretBytes = secretNum.ToByteArrayUnsigned();
                KeyParameter secret      = ParameterUtilities.CreateKeyParameter(
                    cekWrapAlgorithm, secretBytes);

                recipientInfs.Add(
                    new RecipientInf(cekWrapAlgorithm, secret, agreementAlgorithm,
                                     cekWrapAlgorithm, originator, recipientCert));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }
        }
コード例 #30
0
        private byte[] GenerateAESKey(ECPublicKeyParameters bobPublicKey, AsymmetricKeyParameter alicePrivateKey)
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(alicePrivateKey);
            BigInteger sharedSecret = aKeyAgree.CalculateAgreement(bobPublicKey);

            byte[] sharedSecretBytes = sharedSecret.ToByteArray();

            IDigest digest = new Sha256Digest();

            byte[] symmetricKey = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length);
            digest.DoFinal(symmetricKey, 0);

            return(symmetricKey);
        }