Ejemplo n.º 1
0
        public void Curve25519_GetPublicKey()
        {
            var ticks = new List <long>();

            for (byte b = 0; b < 255; b++)
            {
                var stopwatch = Stopwatch.StartNew();

                byte[] privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes(b, 32));

                for (int i = 0; i < 1000; i++)
                {
                    byte[] publicKey = Curve25519.GetPublicKey(privateKey);                     // IDE0059 - Unnecessary assignment of a value
                }

                ticks.Add(stopwatch.ElapsedMilliseconds);
            }

            var min = long.MaxValue;
            var max = long.MinValue;

            foreach (var t in ticks)
            {
                if (min > t)
                {
                    min = t;
                }
                if (max < t)
                {
                    max = t;
                }
            }

            Assert.Null($"Min: {min}, Max: {max}");             // (.Inconclusive) - will Fail for now; waiting for Xunit.SkippableFact
        }
Ejemplo n.º 2
0
        public void Test_15_X25519_ECDH()
        {
            byte[]     A     = Hashes.StringToBinary("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
            Curve25519 Alice = new Curve25519(A);

            Assert.AreEqual("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a",
                            Hashes.BinaryToString(Alice.PublicKey));

            A = Hashes.StringToBinary("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb");
            Curve25519 Bob = new Curve25519(A);

            Assert.AreEqual("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f",
                            Hashes.BinaryToString(Bob.PublicKey));

            byte[] Key1 = Alice.GetSharedKey(Bob.PublicKey, Hashes.ComputeSHA256Hash);
            byte[] Key2 = Bob.GetSharedKey(Alice.PublicKey, Hashes.ComputeSHA256Hash);

            string k1 = Hashes.BinaryToString(Key1);
            string k2 = Hashes.BinaryToString(Key2);

            Assert.AreEqual(k1, k2);

            A = Hashes.StringToBinary("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742");
            if (A.Length != 32)
            {
                Array.Resize <byte>(ref A, 32);
            }

            Array.Reverse(A);   // Most significant byte first.

            A = Hashes.ComputeSHA256Hash(A);
            string k3 = Hashes.BinaryToString(A);

            Assert.AreEqual(k1, k3);
        }
Ejemplo n.º 3
0
        public static byte[] calculateAgreement(ECPublicKey publicKey, ECPrivateKey privateKey)
        {
            if (publicKey == null)
            {
                throw new InvalidKeyException("public value is null");
            }

            if (privateKey == null)
            {
                throw new InvalidKeyException("private value is null");
            }

            if (publicKey.getType() != privateKey.getType())
            {
                throw new InvalidKeyException("Public and private keys must be of the same type!");
            }

            if (publicKey.getType() == DJB_TYPE)
            {
                return(Curve25519.getInstance(Curve25519ProviderType.BEST)
                       .calculateAgreement(((DjbECPublicKey)publicKey).getPublicKey(),
                                           ((DjbECPrivateKey)privateKey).getPrivateKey()));
            }
            else
            {
                throw new InvalidKeyException("Unknown type: " + publicKey.getType());
            }
        }
Ejemplo n.º 4
0
        public void Test_11_X25519_TestVector_2()
        {
            byte[] A = Hashes.StringToBinary("4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d");
            A[0]  &= 248;
            A[31] &= 127;
            A[31] |= 64;
            BigInteger N0 = new BigInteger(A);
            BigInteger N  = BigInteger.Parse("35156891815674817266734212754503633747128614016119564763269015315466259359304");

            Assert.AreEqual(N, N0);

            A      = Hashes.StringToBinary("e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493");
            A[31] &= 127;
            BigInteger U0 = new BigInteger(A);
            BigInteger U  = BigInteger.Parse("8883857351183929894090759386610649319417338800022198945255395922347792736741");

            Assert.AreEqual(U, U0);

            A = Hashes.StringToBinary("95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957");
            BigInteger      NU0 = new BigInteger(A);
            MontgomeryCurve C   = new Curve25519();
            BigInteger      NU  = C.ScalarMultiplication(N, U);

            Assert.AreEqual(NU0, NU);
        }
Ejemplo n.º 5
0
        public static EcKeyPair GenerateKeyPair()
        {
            Curve25519KeyPair keyPair = Curve25519.GetInstance(Curve25519ProviderType.Best).GenerateKeyPair();

            return(new EcKeyPair(new DjbEcPublicKey(keyPair.GetPublicKey()),
                                 new DjbEcPrivateKey(keyPair.GetPrivateKey())));
        }
Ejemplo n.º 6
0
        public void TestCurve25519()
        {
            var kvps = new Dictionary <string, string>()
            {
                { "oB2yte8v6Edhi3t3DeHX+LEfpRGi1jVb6FYTeheQ9XI=", "HfqqvO1mk4gx2bLDO6tPxTNHl6oi7Z42YLUaLj/Oe0Y=" },
                { "YDYr+o/wLbovtba446v27X//NM4szFqXdij1dKLlPl8=", "oWX4rcyZHyQAwLRG7l4tZWgRamSPhXhfurx+y3bYAGY=" },
                { "GOYViPkGsghgYGdUCVaCqvp4qTkKQ3tfPEUdCv/NT14=", "YWeFxQabAS+sKyxqJGHothzNZxdyhEPXYyBx/DtLb24=" },
                { "oKNRZnxqn6uIpQDm58xsngQtuy8Ed0tzQbsfAUZYenQ=", "+UmPSdIVMLiIpe5WNngz5Gp85bAitD1aq0SW69D5WFU=" },
                { "QFGPYiCQE/l92/1Kea1RASI+N/wKrlFypgBNahpE438=", "drKPmk5gSAGr77Nd7/oCsahsHFZmKfFisfmzMpvmzFs=" },
                { "gFxQ2NGOJDjOww84Ye4x9Y5khSGTrTKfpJr7ODeOAEs=", "9y05bruujPguw4FFJ+JM5uHqn3IziMPTk8ag8Xpv/X8=" },
                { "aCaXfvXjUpsb9MEClv6F59XoC4/9xPvp7lCUfz0n00Y=", "np0SHP6UIjvEBhNs2yJrMlqAb0w5vw64KK0sjj+AcWE=" },
                { "yF+hep+SSWf3iVAD8AgFA7qV1KFOXprmFosh6h04Vlc=", "+T64sgnEGBsixpov0ovMNe11yThM2zkf09G8NTnbiAo=" },
                { "sOdE3Tm4af1c5AUL624wdNtAR/jwV+Fdb6UqWzMSnmQ=", "Da29TizW/FfqUb4RfaJDOFkRo97W78GslypQbKL7tDQ=" },
                { "OOzuuGFc6uug5gy/5GY5QDyqheWRYDAAJQz/LBcWZHI=", "nkqKSbuLFwYNY/2QA+C+gvRIOnc0aYowROwZmftD+Gc=" },
                { "iAMBbzRD8ThURLaD4zI/XTbEN8eGE0Hg4KOh0nrZqnI=", "m/4VkymgSpp8k8bBNQmKnYY0Y6at8ttNlr+Wm4v7gzc=" },
                { "YCfrE2SwOb4skiAFIFFpYA85WR1qR5nJmVySAHusilA=", "LATS8VywXK8813rVTdn1xfB/i3QFcY8/9BGloi++2ho=" },
                { "+I05d4noKVZ1sAopMLn3NBysHEPdmfWyGSuoR1GKj2g=", "g8UNfQYTOwhQ73XQRSdlOlsiXIY7Q4nscrdyZeHFjhQ=" },
                { "AAPEMoFI13vgwge4UhpTTnYQHAaHnYbgJHWoKjZ5Y28=", "+IU+ONtYsi4sVPNY4Xdcyoc9Q+YbTShMdZMt2+s9MRI=" },
                { "4DVgmYHhWdjieJY20VvWPocR7IIv0/HuPl1DXRTd4mU=", "UtPY7Cq7G38SXdg1l1UTzsdg48taFYetMZXoa4rmZAg=" },
            };

            foreach (var kv in kvps)
            {
                var publicKey = Curve25519.GetPublicKey(kv.Key);
                Assert.AreEqual(publicKey, kv.Value);
            }
        }
Ejemplo n.º 7
0
        private void NegotiateKey(ConnectedClient selectedClient)
        {
            var synMessage = new EncMessage()
            {
                Sender = new ConnectedClient()
                {
                    Id       = _userId,
                    Username = _username
                },
                Recipient         = selectedClient,
                UsedForDHExchange = true,
                Payload           = new byte[1] {
                    0x34
                }
            };

            _serverChannel.SendMessage(synMessage);
            byte[] rndBytes = new byte[32];
            RNGCryptoServiceProvider.Create().GetBytes(rndBytes);

            privateKey = Curve25519.ClampPrivateKey(rndBytes);
            byte[] publicKey = Curve25519.GetPublicKey(privateKey);

            synMessage.Payload = publicKey;
            _serverChannel.SendMessage(synMessage);
        }
Ejemplo n.º 8
0
        public void Curve25519_GetPublicKey()
        {
            List <long> ticks = new List <long>();

            for (int i = 0; i < 255; i++)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();

                byte[] privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32));

                for (int j = 0; j < 1000; j++)
                {
                    byte[] publicKey = Curve25519.GetPublicKey(privateKey);
                }

                ticks.Add(stopwatch.ElapsedMilliseconds);
            }

            long min = long.MaxValue;
            long max = long.MinValue;

            for (int i = 0; i < ticks.Count; i++)
            {
                if (ticks[i] < min)
                {
                    min = ticks[i];
                }
                if (ticks[i] > max)
                {
                    max = ticks[i];
                }
            }

            Assert.Inconclusive("Min: {0}, Max: {1}", min, max);
        }
Ejemplo n.º 9
0
        public void Curve25519_GetPublicKey()
        {
            var ticks = new List <long>();

            for (var i = 0; i < 255; i++)
            {
                var stopwatch = Stopwatch.StartNew();

                var privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32));

                for (var j = 0; j < 1000; j++)
                {
                    var publicKey = Curve25519.GetPublicKey(privateKey);
                }

                ticks.Add(stopwatch.ElapsedMilliseconds);
            }

            var min = long.MaxValue;
            var max = long.MinValue;

            foreach (var t in ticks)
            {
                if (t < min)
                {
                    min = t;
                }
                if (t > max)
                {
                    max = t;
                }
            }

            Assert.Inconclusive("Min: {0}, Max: {1}", min, max);
        }
Ejemplo n.º 10
0
        private void button4_Click(object sender, EventArgs e)
        {
            if (loadedPartnerKey && loadedKeychain)
            {
                OpenFileDialog theDialog = new OpenFileDialog();
                theDialog.Title  = "Open file to decrypt";
                theDialog.Filter = "CurveBox encrypted file |*.curvebox";
                if (theDialog.ShowDialog() == DialogResult.OK)
                {
                    string filename = theDialog.FileName;

                    dataPath   = filename;
                    loadedFile = true;
                }

                if (!loadedFile)
                {
                    MessageBox.Show("No file loaded!");
                    return;
                }

                byte[] sharedKey = Curve25519.GetSharedSecret(loadedPrivateKey, loadedPartnerPublicKey);
                byte[] hashedKey = sha256(System.Text.Encoding.UTF8.GetString(sharedKey));
                AES_Decrypt(dataPath, Encoding.UTF8.GetString(sharedKey));
                MessageBox.Show(String.Format("Wrote decrypted data to {0}", dataPath + ".decrypted"));
            }
            else
            {
                MessageBox.Show("Please load your keychain and your partners public key");
                return;
            }
        }
Ejemplo n.º 11
0
        public static void Square(int[] Outv, int Outvoffset, int[] A, int Aoffset)
        {
            int j;

            for (int i = 0; i < 32; ++i)
            {
                int u = 0;

                for (j = 0; j < i - j; ++j)
                {
                    u += A[Aoffset + j] * A[Aoffset + i - j];
                }

                for (j = i + 1; j < i + 32 - j; ++j)
                {
                    u += 38 * A[Aoffset + j] * A[Aoffset + i + 32 - j];
                }

                u *= 2;

                if ((i & 1) == 0)
                {
                    u += A[Aoffset + i / 2] * A[Aoffset + i / 2];
                    u += 38 * A[Aoffset + i / 2 + 16] * A[Aoffset + i / 2 + 16];
                }

                Outv[Outvoffset + i] = u;
            }

            Curve25519.Squeeze(Outv, Outvoffset);
        }
Ejemplo n.º 12
0
        public static int CryptoScalarmult(byte[] Q, byte[] N, byte[] P)
        {
            int[]  work = new int[96];
            byte[] e    = new byte[32];

            for (int i = 0; i < 32; ++i)
            {
                e[i] = N[i];
            }

            e[0]  &= 248;
            e[31] &= 127;
            e[31] |= 64;

            for (int i = 0; i < 32; ++i)
            {
                work[i] = P[i] & 0xFF;
            }

            Curve25519.Mainloop(work, e);

            Curve25519.Recip(work, 32, work, 32);
            Curve25519.Mult(work, 64, work, 0, work, 32);
            Curve25519.Freeze(work, 64);

            for (int i = 0; i < 32; ++i)
            {
                Q[i] = (byte)work[64 + i];
            }

            return(0);
        }
Ejemplo n.º 13
0
        public static ECKeyPair generateKeyPair()
        {
            Curve25519KeyPair keyPair = Curve25519.getInstance(Curve25519ProviderType.BEST).generateKeyPair();

            return(new ECKeyPair(new DjbECPublicKey(keyPair.getPublicKey()),
                                 new DjbECPrivateKey(keyPair.getPrivateKey())));
        }
Ejemplo n.º 14
0
        private void X25519_TestVector_3(int i, string HexResult)
        {
            MontgomeryCurve C = new Curve25519();
            BigInteger      N = 9;
            BigInteger      U = 9;
            BigInteger      NU;

            while (i-- > 0)
            {
                byte[] NBin = N.ToByteArray();
                if (NBin.Length != 32)
                {
                    Array.Resize <byte>(ref NBin, 32);
                }

                NBin[0]  &= 0xf8;
                NBin[31] &= 0x3f;
                NBin[31] |= 0x40;

                NU = C.ScalarMultiplication(NBin, U);

                U = N;
                N = NU;
            }

            byte[]     A   = Hashes.StringToBinary(HexResult);
            BigInteger NU0 = new BigInteger(A);

            Assert.AreEqual(NU0, NU);
        }
Ejemplo n.º 15
0
        public Response <ECKeyPair> GenerateECKeyPair(byte[] seed = null)
        {
            var response = new Response <ECKeyPair>();

            try
            {
                var randomResponse = GetRandom(32, seed);
                if (!randomResponse.IsSuccess)
                {
                    throw new Exception(response.Error);
                }
                var privateKeyToBeClamped = randomResponse.Result.X;
                Curve25519.ClampPrivateKeyInline(privateKeyToBeClamped);
                var publicKey = Curve25519.GetPublicKey(privateKeyToBeClamped);
                var keyPair   = new ECKeyPair {
                    PrivateKey = privateKeyToBeClamped, PublicKey = publicKey
                };
                response.Result = keyPair;
                response.SetSuccess();
            }
            catch (Exception e)
            {
                response.SetError(e);
            }
            return(response);
        }
Ejemplo n.º 16
0
        public DNSCrypt(IOptionsMonitor <DNSCryptOptions> DNSCryptOptions)
        {
            Options = DNSCryptOptions;

            Random = new Random();

            Client = new UdpClient
            {
                Client =
                {
                    SendTimeout    = Options.CurrentValue.Timeout,
                    ReceiveTimeout = Options.CurrentValue.Timeout
                }
            };

            Stamp = (DNSCryptStamp)Options.CurrentValue.Stamp.Value;

            IPEndPoint = IPEndPoint.Parse(Stamp.Address);

            var ClientCurve25519 = new Curve25519();

            ClientPublicKey = ClientCurve25519.GetPublicKey();

            ClientPrivateKey = ClientCurve25519.GetPrivateKey();

            ChaCha20Poly1305 = new ChaCha20Poly1305();

            IsInitialized = false;
        }
Ejemplo n.º 17
0
        public byte[] CalculateAndHashSharedSecret(byte[] privateKey, byte[] publicKey)
        {
            Guard.NotNull(privateKey, publicKey);
            var sharedSecret     = Curve25519.GetSharedSecret(privateKey, publicKey);
            var sharedSecretHash = this._platform.ComputeSHA256(sharedSecret);

            return(sharedSecretHash);
        }
Ejemplo n.º 18
0
    static byte[] GenerateCurve25519PrivateKey()
    {
        RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();

        byte[] key = new byte[32];
        rngCsp.GetBytes(key);
        return(Curve25519.ClampPrivateKey(key));
    }
Ejemplo n.º 19
0
        public ECDHCryptor()
        {
            //first we generate random bytes as starting sequence
            byte[] aliceRandomBytes = new byte[32];                       //must be 32 bytes long
            RNGCryptoServiceProvider.Create().GetBytes(aliceRandomBytes); //generate random bytes

            _privateKey = Curve25519.ClampPrivateKey(aliceRandomBytes);
            PublicKey   = Curve25519.GetPublicKey(_privateKey);
        }
Ejemplo n.º 20
0
        private void loadKeychain(string location)
        {
            try {
                using (FileStream fsSource = new FileStream(location, FileMode.Open, FileAccess.Read)) {
                    byte[] bytes          = new byte[fsSource.Length];
                    int    numBytesToRead = (int)fsSource.Length;
                    int    numBytesRead   = 0;
                    while (numBytesToRead > 0)
                    {
                        // Read may return anything from 0 to numBytesToRead.
                        int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

                        // Break when the end of the file is reached.
                        if (n == 0)
                        {
                            break;
                        }

                        numBytesRead   += n;
                        numBytesToRead -= n;
                    }
                    numBytesToRead = bytes.Length;
                    Byte[] hash = new Byte[64];
                    Buffer.BlockCopy(bytes, 0, hash, 0, hash.Length);

                    string publicKeyhash = Encoding.UTF8.GetString(hash);
                    byte[] hashBytes     = Encoding.UTF8.GetBytes(publicKeyhash);

                    Byte[] fileBytes = new Byte[bytes.Length - 64];
                    Buffer.BlockCopy(bytes, 64, fileBytes, 0, fileBytes.Length);

                    string encodedKey   = Encoding.UTF8.GetString(fileBytes);
                    byte[] decodedBytes = Base64Decode(fileBytes);

                    byte[] publicKey  = Curve25519.GetPublicKey(decodedBytes);
                    byte[] hashPublic = sha256(System.Text.Encoding.UTF8.GetString(publicKey));

                    if (String.ReferenceEquals(Encoding.UTF8.GetString(hashPublic), publicKeyhash))
                    {
                        MessageBox.Show("Expected pubic key hash does not match calculated hash, loading failed.");
                        return;
                    }

                    loadedPrivateKey = decodedBytes;
                    loadedPublicKey  = publicKey;

                    label1.Text    = String.Format("Keychain Loaded: YES");
                    label3.Text    = String.Format("Loaded path: {0}", location);
                    label2.Text    = String.Format("Publickey hash: {0}", publicKeyhash);
                    loadedKeychain = true;
                }
            }
            catch (FileNotFoundException ioEx)
            {
                Console.WriteLine(ioEx.Message);
            }
        }
Ejemplo n.º 21
0
        public static void Main()
        {
            var curve      = new Curve25519();
            var privateKey = curve.CreateRandomPrivateKey();
            var publicKey  = curve.GetPublicKey(privateKey);

            Console.WriteLine(Convert.ToBase64String(privateKey));
            Console.WriteLine(Convert.ToBase64String(publicKey));
        }
Ejemplo n.º 22
0
 public static bool VerifySignature(ECPublicKey signingKey, byte[] message, byte[] signature)
 {
     if (signingKey.GetKeyType() == DJB_TYPE)
     {
         return(Curve25519.GetInstance(Curve25519ProviderType.BEST).VerifySignature(((DjbECPublicKey)signingKey).GetPublicKey(), message, signature));
     }
     else
     {
         throw new InvalidKeyException("Unknown type: " + signingKey.GetKeyType());
     }
 }
Ejemplo n.º 23
0
 public static byte[] CalculateSignature(ECPrivateKey signingKey, byte[] message)
 {
     if (signingKey.GetKeyType() == DJB_TYPE)
     {
         return(Curve25519.GetInstance(Curve25519ProviderType.BEST).CalculateSignature(((DjbECPrivateKey)signingKey).GetPrivateKey(), message));
     }
     else
     {
         throw new InvalidKeyException("Unknown type: " + signingKey.GetKeyType());
     }
 }
Ejemplo n.º 24
0
        public void TestExternal()
        {
            for (int i = 0; i < 100; i++)
            {
                var privateKey = (i % 2 == 0) ? Utils.CreateProcess(wg, "genkey") : Curve25519.GetPrivateKey();
                var publicKey1 = Utils.CreateProcess(wg, "pubkey", privateKey);
                var publicKey2 = Curve25519.GetPublicKey(privateKey);

                Assert.AreEqual(publicKey1, publicKey2);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 交换密钥
        /// </summary>
        /// <param name="exchange">交换流程(输入值是我方公钥,返回值是对端公钥)</param>
        /// <returns>密钥</returns>
        public byte[] ExchangeSecret(Func <byte[], byte[]> exchange)
        {
            Guard.Requires <ArgumentNullException>(exchange != null);
            var randBytes = new byte[32];

            RandomNumberGenerator.Create().GetBytes(randBytes);
            var privateKey = Curve25519.ClampPrivateKey(randBytes);
            var publicKey  = Curve25519.GetPublicKey(privateKey);

            return(Curve25519.GetSharedSecret(privateKey, exchange.Invoke(publicKey)));
        }
Ejemplo n.º 26
0
 public static byte[] VerifyVrfSignature(IEcPublicKey signingKey, byte[] message, byte[] signature)
 {
     if (signingKey.GetKeyType() == DjbType)
     {
         return(Curve25519.GetInstance(Curve25519ProviderType.Best)
                .VerifyVrfSignature(((DjbEcPublicKey)signingKey).GetPublicKey(), message, signature));
     }
     else
     {
         throw new InvalidKeyException("Unknown type: " + signingKey.GetKeyType());
     }
 }
Ejemplo n.º 27
0
 /// <summary>
 ///     Performs an Elliptic Curve Diffie-Hellman key agreement operation (scalar multiplication),
 ///     with cofactor multiplication (ECDHC).
 /// </summary>
 /// <returns>The ECDHC shared secret.</returns>
 /// <param name="publicKey">Public key.</param>
 /// <param name="privateKey">Private key.</param>
 public static byte[] CalculateEcdhcSecret(ECKey publicKey, ECKey privateKey)
 {
     if (publicKey.CurveName.Equals(DjbCurve.Curve25519.ToString()))
     {
         return(Curve25519.CalculateSharedSecret(privateKey.EncodedKey, publicKey.EncodedKey));
     }
     else if (publicKey.CurveName.Equals(DjbCurve.Ed25519.ToString()))
     {
         return(Ed25519.KeyExchange(publicKey.EncodedKey, privateKey.EncodedKey));
     }
     return
         (CalculateEcdhcSecret(DecodeToPublicKey(publicKey), DecodeToPrivateKey(privateKey)).ToByteArrayUnsigned());
 }
        public void TestDonnaPublicKeyGeneration()
        {
            Curve25519 curve = Curve25519.getInstance(Curve25519.BEST);

            byte[] private_key = new byte[BYTES_SIZE];
            byte[] public_key  = new byte[BYTES_SIZE];

            for (int i = 0; i < TEST_COUNT; i++)
            {
                private_key = curve.generatePrivateKey();
                public_key  = curve.generatePublicKey(private_key);
            }
        }
Ejemplo n.º 29
0
        public RemoteAttestationKeys(Curve25519KeyPair keyPair, byte[] serverPublicEphemeral, byte[] serverPublicStatic)
        {
            byte[] ephemeralToEphemeral = Curve25519.getInstance(Curve25519.BEST).calculateAgreement(serverPublicEphemeral, keyPair.getPrivateKey());
            byte[] ephemeralToStatic    = Curve25519.getInstance(Curve25519.BEST).calculateAgreement(serverPublicStatic, keyPair.getPrivateKey());

            byte[] masterSecret = ByteUtil.combine(ephemeralToEphemeral, ephemeralToStatic);
            byte[] publicKeys   = ByteUtil.combine(keyPair.getPublicKey(), serverPublicEphemeral, serverPublicStatic);

            HkdfBytesGenerator generator = new HkdfBytesGenerator(new Sha256Digest());

            generator.Init(new HkdfParameters(masterSecret, publicKeys, null));
            generator.GenerateBytes(ClientKey, 0, ClientKey.Length);
            generator.GenerateBytes(ServerKey, 0, ServerKey.Length);
        }
Ejemplo n.º 30
0
        private void button5_Click(object sender, EventArgs e)
        {
            byte[] aliceRandomBytes = new byte[32];
            RNGCryptoServiceProvider.Create().GetBytes(aliceRandomBytes);

            byte[] alicePrivate = Curve25519.ClampPrivateKey(aliceRandomBytes);
            byte[] alicePublic  = Curve25519.GetPublicKey(alicePrivate);

            string base64Key = Base64Encode(alicePrivate);

            byte[] encodedBytes = Encoding.UTF8.GetBytes(base64Key);
            byte[] hashPublic   = sha256(System.Text.Encoding.UTF8.GetString(alicePublic));

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "CurveBox keychain|*.curvechain";
            saveFileDialog1.Title  = "Save CurveBox keychain";
            saveFileDialog1.ShowDialog();

            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
                // Saves the Image via a FileStream created by the OpenFile method.
                System.IO.FileStream fs =
                    (System.IO.FileStream)saveFileDialog1.OpenFile();
                // Saves the Image in the appropriate ImageFormat based upon the
                // File type selected in the dialog box.
                // NOTE that the FilterIndex property is one-based.
                var fw = new BinaryWriter(fs);

                fw.Write(hashPublic);
                fw.Write(encodedBytes);

                fw.Flush();
                fw.Close();
                fs.Close();
            }

            DialogResult dialogResult = MessageBox.Show("Would you like to try to load this new keychain now?", "Load keychain", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                loadKeychain(saveFileDialog1.FileName);
            }
            else if (dialogResult == DialogResult.No)
            {
                // do nothing n***a
            }
        }