public void ExtractEd25519PublicKeyFromEd25519SecretKeyTest()
        {
            var kp  = PublicKeyAuth.GenerateKeyPair();
            var pub = PublicKeyAuth.ExtractEd25519PublicKeyFromEd25519SecretKey(kp.Secret);

            Assert.AreEqual(Convert.ToBase64String(kp.Public), Convert.ToBase64String(pub));
        }
Example #2
0
        public void PublicKeyAuthConvertToCurve25519()
        {
            var keypairSeed = new byte[] {
                0x42, 0x11, 0x51, 0xa4, 0x59, 0xfa, 0xea, 0xde,
                0x3d, 0x24, 0x71, 0x15, 0xf9, 0x4a, 0xed, 0xae,
                0x42, 0x31, 0x81, 0x24, 0x09, 0x5a, 0xfa, 0xbe,
                0x4d, 0x14, 0x51, 0xa5, 0x59, 0xfa, 0xed, 0xee
            };

            var keys = PublicKeyAuth.GenerateKeyPair(keypairSeed);

            var ed25519Pk   = keys.PublicKey;
            var ed25519SkPk = keys.PrivateKey;

            var curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk);
            var curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk);

            Assert.AreEqual(Utilities.BinaryToHex(curve25519Pk, Utilities.HexFormat.None, Utilities.HexCase.Upper),
                            "F1814F0E8FF1043D8A44D25BABFF3CEDCAE6C22C3EDAA48F857AE70DE2BAAE50");
            Assert.AreEqual(Utilities.BinaryToHex(curve25519Sk, Utilities.HexFormat.None, Utilities.HexCase.Upper),
                            "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE166");

            for (var i = 0; i < 500; i++)
            {
                keys         = PublicKeyAuth.GenerateKeyPair();
                ed25519Pk    = keys.PublicKey;
                ed25519SkPk  = keys.PrivateKey;
                curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk);
                curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk);
                var curve25519Pk2 = ScalarMult.Base(curve25519Sk);

                CollectionAssert.AreEqual(curve25519Pk, curve25519Pk2);
            }
        }
Example #3
0
        public void TestNoiseXx()
        {
            var rootKey  = PublicKeyAuth.GenerateKeyPair();
            var Verifier = DiscoHelper.CreatePublicKeyVerifier(rootKey.PublicKey);

            var clienPair  = Asymmetric.GenerateKeyPair();
            var serverPair = Asymmetric.GenerateKeyPair();

            // init
            var clientConfig = new Config
            {
                KeyPair              = clienPair,
                HandshakePattern     = NoiseHandshakeType.NoiseXX,
                PublicKeyVerifier    = Verifier,
                StaticPublicKeyProof = DiscoHelper.CreateStaticPublicKeyProof(rootKey.PrivateKey, clienPair.PublicKey)
            };

            var serverConfig = new Config
            {
                KeyPair              = serverPair,
                HandshakePattern     = NoiseHandshakeType.NoiseXX,
                PublicKeyVerifier    = Verifier,
                StaticPublicKeyProof = DiscoHelper.CreateStaticPublicKeyProof(rootKey.PrivateKey, serverPair.PublicKey)
            };

            this.RunTwoWayTest(clientConfig, serverConfig, 1802);
        }
Example #4
0
        /// <summary>
        ///   Constructs the server given the Network key and its keypair
        /// </summary>
        /// <param name="network_key">
        ///   The key that identifies the network
        /// </param>
        /// <param name="server_keypair">
        ///   The server's long term keypair
        /// </param>
        public Server(byte[] network_key, Sodium.KeyPair server_keypair)
        {
            this._network_key             = network_key;
            this._longterm_server_keypair = server_keypair;

            _ephemeral_server_keypair = new KeyPair(PublicKeyAuth.GenerateKeyPair());
        }
Example #5
0
        public Key(byte[] privateKey)
        {
            var keyPair = PublicKeyAuth.GenerateKeyPair(privateKey);

            PrivateKey = keyPair.PrivateKey;
            PublicKey  = keyPair.PublicKey;
        }
        public void ConvertToCurve25519Test()
        {
            // Keypair seed from libsodium-net
            var keypairSeed = new byte[] {
                0x42, 0x11, 0x51, 0xa4, 0x59, 0xfa, 0xea, 0xde,
                0x3d, 0x24, 0x71, 0x15, 0xf9, 0x4a, 0xed, 0xae,
                0x42, 0x31, 0x81, 0x24, 0x09, 0x5a, 0xfa, 0xbe,
                0x4d, 0x14, 0x51, 0xa5, 0x59, 0xfa, 0xed, 0xee
            };

            var kp = PublicKeyAuth.GenerateKeyPair(keypairSeed);

            var ed25519Pk   = kp.Public;
            var ed25519SkPk = kp.Secret;

            var curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk);
            var curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk);

            Assert.AreEqual(Convert.ToBase64String(curve25519Pk), "8YFPDo/xBD2KRNJbq/887crmwiw+2qSPhXrnDeK6rlA=");
            Assert.AreEqual(Convert.ToBase64String(curve25519Sk), "gFIDA3bUcRK+f3PtegGSk90SrZELZURVeYtGZ9c94WY=");

            for (var i = 0; i < 500; i++)
            {
                kp           = PublicKeyAuth.GenerateKeyPair();
                ed25519Pk    = kp.Public;
                ed25519SkPk  = kp.Secret;
                curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk);
                curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk);
                var curve25519Pk2 = ScalarMult.Base(curve25519Sk);

                CollectionAssert.AreEqual(curve25519Pk, curve25519Pk2);
            }
        }
Example #7
0
        public Key(byte[] seed, int index)
        {
            var encoder = new ASCIIEncoder();
            var secret  = encoder.DecodeData(Ed25519Curve);

            // var seedBytes = HexByteConvertorExtensions.HexToByteArrayInternal(seed);
            var array = new HMACSHA512(secret).ComputeHash(seed);

            var key       = array.SafeSubarray(0, 32);
            var chainCode = array.SafeSubarray(32, 32);

            var derivedPath = unchecked ((uint)index + HardenedOffset);

            derivedPath = HexByteConvertorExtensions.ReverseBytes(derivedPath);
            var dpBytes = BitConverter.GetBytes(derivedPath);
            var data = new byte[] { 0 }.Concat(key, dpBytes);

            var array2 = new HMACSHA512(chainCode).ComputeHash(data);

            var key2 = array2.SafeSubarray(0, 32);

            var keyPair = PublicKeyAuth.GenerateKeyPair(key2);

            PrivateKey = keyPair.PrivateKey;
            PublicKey  = keyPair.PublicKey;
        }
Example #8
0
        public void ItWorks()
        {
            var network_key = new byte[] {
                0xd4, 0xa1, 0xcb, 0x88, 0xa6, 0x6f, 0x02, 0xf8, 0xdb, 0x63, 0x5c,
                0xe2, 0x64, 0x41, 0xcc, 0x5d, 0xac, 0x1b, 0x08, 0x42, 0x0c, 0xea,
                0xac, 0x23, 0x08, 0x39, 0xb7, 0x55, 0x84, 0x5a, 0x9f, 0xfb
            };

            var client_keypair = PublicKeyAuth.GenerateKeyPair();
            var server_keypair = PublicKeyAuth.GenerateKeyPair();

            var client = new Client(network_key, server_keypair.PublicKey, client_keypair);
            var server = new Server(network_key, server_keypair);

            // Client -> Server [1]
            var client_hello = client.Hello();

            server.AcceptHello(client_hello);

            // Client <- Server [2]
            var server_hello = server.Hello();

            client.AcceptHello(server_hello);

            Assert.True(
                Enumerable.SequenceEqual(client.EphemeralDerivedSecret, server.EphemeralDerivedSecret),
                "The ephemeral derived secrets are not the same" +
                "client: " +
                $"{string.Join(" ", client.EphemeralDerivedSecret.Select(x => x.ToString()).ToArray())}\n" +
                "server: " +
                $"{string.Join(" ", server.EphemeralDerivedSecret.Select(x => x.ToString()).ToArray())}"
                );
            Assert.True(
                Enumerable.SequenceEqual(client.ServerDerivedSecret, server.ServerDerivedSecret),
                "The Server derived secrets are not the same\n" +
                "client: " +
                $"{string.Join(" ", client.ServerDerivedSecret.Select(x => x.ToString()).ToArray())}\n" +
                "server: " +
                $"{string.Join(" ", server.ServerDerivedSecret.Select(x => x.ToString()).ToArray())}"
                );

            // Client -> Server [3]
            var client_auth = client.Authenticate();

            server.AcceptAuth(client_auth);

            Assert.True(
                Enumerable.SequenceEqual(client.ClientDerivedSecret, server.ClientDerivedSecret),
                "The Client derived secrets are not the same\n" +
                "client: " +
                $"{string.Join(" ", client.ClientDerivedSecret.Select(x => x.ToString()).ToArray())}\n" +
                "server: " +
                $"{string.Join(" ", server.ClientDerivedSecret.Select(x => x.ToString()).ToArray())}"
                );

            // Client <- Server [4]
            var server_accept = server.Accept();

            client.VerifyAccept(server_accept);
        }
        public void GenerateKeyPairTest()
        {
            var kp = PublicKeyAuth.GenerateKeyPair();

            Assert.AreEqual(32, kp.Public.Length);
            Assert.AreEqual(64, kp.Secret.Length);
        }
        public void GenerateKeyPairFromSeedTest()
        {
            var seed = Core.GetRandomBytes(32);
            var kp   = PublicKeyAuth.GenerateKeyPair(seed);

            Assert.AreEqual(32, kp.Public.Length);
            Assert.AreEqual(64, kp.Secret.Length);
        }
Example #11
0
        public void GenerateKeyTest()
        {
            var actual = PublicKeyAuth.GenerateKeyPair();

            //need a better test
            Assert.IsNotNull(actual.PrivateKey);
            Assert.IsNotNull(actual.PublicKey);
        }
Example #12
0
        /// <summary>
        ///  Sign the specified message with the private key.
        /// </summary>
        /// <param name='privateKey'>
        ///  The private key.
        /// </param>
        /// <param name='message'>
        ///  The message.
        /// </param>
        /// <returns>
        ///  The message that has been signed (encrypted) by the private key.
        /// </returns>
        public byte[] Sign(byte[] privateKey, byte[] message)
        {
            if (Keys == null)
            {
                Keys = PublicKeyAuth.GenerateKeyPair(privateKey);
            }

            return(PublicKeyAuth.Sign(message, Keys.PrivateKey));
        }
        public void ExtractEd25519SeedFromEd25519SecretKeyTest()
        {
            var kp1  = PublicKeyAuth.GenerateKeyPair();
            var seed = PublicKeyAuth.ExtractEd25519SeedFromEd25519SecretKey(kp1.Secret);
            var kp2  = PublicKeyAuth.GenerateKeyPair(seed);

            Assert.AreEqual(Convert.ToBase64String(kp1.Public), Convert.ToBase64String(kp2.Public));
            Assert.AreEqual(Convert.ToBase64String(kp1.Secret), Convert.ToBase64String(kp2.Secret));
        }
Example #14
0
        /// <summary>
        /// Generate an ed25519 root key pair and save the private and public parts in different files.
        /// </summary>
        /// <param name="discoRootPrivateKeyFile">Path to private key file</param>
        /// <param name="discoRootPublicKeyFile">Path to public key file</param>
        public static void GenerateAndSaveDiscoRootKeyPair(
            string discoRootPrivateKeyFile,
            string discoRootPublicKeyFile)
        {
            var keyPair = PublicKeyAuth.GenerateKeyPair();

            File.WriteAllText(discoRootPrivateKeyFile, keyPair.PrivateKey.ToHexString());
            File.WriteAllText(discoRootPublicKeyFile, keyPair.PublicKey.ToHexString());
        }
        /// <summary>
        ///  Generates a KeyPair.
        /// </summary>
        /// <returns>The pair auth.</returns>
        /// <param name="seed">Seed.</param>
        public static KeyPairDto KeyPairAuth(byte[] seed = null)
        {
            var kp = PublicKeyAuth.GenerateKeyPair(seed);

            return(new KeyPairDto()
            {
                PublicKey = kp.PublicKey, SecretKey = kp.PrivateKey
            });
        }
Example #16
0
 public static (string publicKey, string privateKey) GenerateSigningKeyPair()
 {
     char[] password      = PasswordPrompt.EnterNewPassword();
     byte[] passwordBytes = Password.Hash(password);
     using var keyPair = PublicKeyAuth.GenerateKeyPair();
     byte[] publicKey           = Utilities.ConcatArrays(Constants.Ed25519KeyHeader, keyPair.PublicKey);
     byte[] encryptedPrivateKey = PrivateKey.Encrypt(passwordBytes, keyPair.PrivateKey, Constants.Ed25519KeyHeader);
     return(ConvertKeys(publicKey, encryptedPrivateKey));
 }
Example #17
0
        public void ExtractEd25519PublicKeyFromEd25519SecretKey()
        {
            // generate an Ed25519 keypair
            var keypair = PublicKeyAuth.GenerateKeyPair();
            // extract the seed from the generated keypair
            var publicKey = PublicKeyAuth.ExtractEd25519PublicKeyFromEd25519SecretKey(keypair.PrivateKey);

            CollectionAssert.AreEqual(keypair.PublicKey, publicKey);
        }
Example #18
0
        public void GenerateKeySeedTest()
        {
            var expected = new KeyPair(Utilities.HexToBinary("76a1592044a6e4f511265bca73a604d90b0529d1df602be30a19a9257660d1f5"),
                                       Utilities.HexToBinary("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff76a1592044a6e4f511265bca73a604d90b0529d1df602be30a19a9257660d1f5"));
            var actual = PublicKeyAuth.GenerateKeyPair(Utilities.HexToBinary("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));

            CollectionAssert.AreEqual(expected.PublicKey, actual.PublicKey);
            CollectionAssert.AreEqual(expected.PrivateKey, actual.PrivateKey);
        }
Example #19
0
        public void GenerateKeyVerifySignedDataTest()
        {
            var actual = PublicKeyAuth.GenerateKeyPair();

            byte[] randomArray = SodiumCore.GetRandomBytes(255);
            var    sign        = PublicKeyAuth.SignDetached(randomArray, actual.PrivateKey);

            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sign, randomArray, actual.PublicKey));
        }
        public void VerifyTest()
        {
            var kp = PublicKeyAuth.GenerateKeyPair();

            byte[] message      = System.Text.Encoding.UTF8.GetBytes("Hello, World!");
            var    signature    = PublicKeyAuth.Sign(message, kp.Secret);
            var    verification = PublicKeyAuth.Verify(signature, kp.Public);

            Assert.AreEqual(message.ToString(), verification.ToString());
        }
        /// <summary>
        ///   Constructs the client given
        /// </summary>
        /// <param name="network_key">
        ///   The key that identifies the network
        /// </param>
        /// <param name="server_pk">
        ///   The long term server public key
        /// </param>
        /// <param name="client_keys">
        ///   The long term client key pair
        /// </param>
        public Client(byte[] network_key, byte[] server_pk, Sodium.KeyPair client_keys)
        {
            this._network_key = network_key;

            var ed_keypair = PublicKeyAuth.GenerateKeyPair();

            _ephemeral_client_keypair = new KeyPair(ed_keypair);

            _longterm_server_pk      = server_pk;
            _longterm_client_keypair = client_keys;
        }
Example #22
0
 public void ItBuilds()
 {
     var network_key = new byte[] {
         0xd4, 0xa1, 0xcb, 0x88, 0xa6, 0x6f, 0x02, 0xf8, 0xdb, 0x63, 0x5c,
         0xe2, 0x64, 0x41, 0xcc, 0x5d, 0xac, 0x1b, 0x08, 0x42, 0x0c, 0xea,
         0xac, 0x23, 0x08, 0x39, 0xb7, 0x55, 0x84, 0x5a, 0x9f, 0xfb
     };
     var client_keypair = PublicKeyAuth.GenerateKeyPair();
     var server_keypair = PublicKeyAuth.GenerateKeyPair();
     var client         = new Client(network_key, server_keypair.PublicKey, client_keypair);
 }
Example #23
0
        public void ExtractEd25519SeedFromEd25519SecretKeyTest()
        {
            // generate an Ed25519 keypair
            var firstKeypair = PublicKeyAuth.GenerateKeyPair();
            // extract the seed from the generated keypair
            var seed = PublicKeyAuth.ExtractEd25519SeedFromEd25519SecretKey(firstKeypair.PrivateKey);
            // generate a second keypair from the seed
            var secondKeyPair = PublicKeyAuth.GenerateKeyPair(seed);

            CollectionAssert.AreEqual(firstKeypair.PublicKey, secondKeyPair.PublicKey);
            CollectionAssert.AreEqual(firstKeypair.PrivateKey, secondKeyPair.PrivateKey);
        }
        public void SignAndVerifyFromMessageTest()
        {
            var     kp        = PublicKeyAuth.GenerateKeyPair();
            var     signature = new PublicKeyAuth();
            IBuffer data      = CryptographicBuffer.ConvertStringToBinary("Hello, World!", BinaryStringEncoding.Utf8);

            signature.Append(data);

            var output = signature.GetValueAndReset(kp.Secret);

            Assert.AreEqual(64, output.Length);
            Assert.AreEqual(true, signature.GetValueAndVerify(output, kp.Public));
        }
Example #25
0
        public void GenerateKeyPairWithBadSeed()
        {
            //Don`t copy bobSk for other tests (bad key)!
            //30 byte
            var bobSk = new byte[] {
                0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b,
                0x79, 0xe1, 0x7f, 0x8b, 0x83, 0x80, 0x0e, 0xe6,
                0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd,
                0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88
            };

            PublicKeyAuth.GenerateKeyPair(bobSk);
        }
        KeyPair EnsureKeyPair()
        {
            if (!System.IO.File.Exists(System.IO.Path.Combine("db", "oracle-key.txt")))
            {
                var keyPair = PublicKeyAuth.GenerateKeyPair();
                System.IO.File.WriteAllText(System.IO.Path.Combine("db", "oracle-key.txt"), Convert.ToBase64String(keyPair.PublicKey) + " " + Convert.ToBase64String(keyPair.PrivateKey));
                return(keyPair);
            }

            var data  = System.IO.File.ReadAllText(System.IO.Path.Combine("db", "oracle-key.txt"));
            var parts = data.Split(null);

            return(new KeyPair(Convert.FromBase64String(parts[0]), Convert.FromBase64String(parts[1])));
        }
Example #27
0
        public void SignTest()
        {
            var kp = PublicKeyAuth.GenerateKeyPair();

            byte[] message   = System.Text.Encoding.UTF8.GetBytes("Hello, World!");
            var    signature = PublicKeyAuth.Sign(message, kp.Secret);

            // Test against a seed and expected output generated from libsodium
            var seed     = Convert.FromBase64String("zYZceFCtMRu4FAi/a47fN+21396uv/QcUMvi/u08zCw=");
            var expected = Convert.FromBase64String("BlWhHIrosG+Q7jq/lMgxkw79f7dM1x2u+IR6f5nPojaVdaXpUbSpzVSPT238CCDInCnQQ5ueMetEoaXYhET+CEhlbGxvLCBXb3JsZCE=");

            kp        = PublicKeyAuth.GenerateKeyPair(seed);
            signature = PublicKeyAuth.Sign(message, kp.Secret);
            Assert.AreEqual(expected.ToString(), signature.ToString());
        }
Example #28
0
        public static Key Create(string base64EncodedPrivateKey = null)
        {
            byte[] privateKey;
            byte[] publicKey;

            if (string.IsNullOrEmpty(base64EncodedPrivateKey))
            {
                var keyPair = PublicKeyAuth.GenerateKeyPair();

                privateKey = keyPair.PrivateKey;
                publicKey  = keyPair.PublicKey;
            }
            else
            {
                privateKey = Convert.FromBase64String(base64EncodedPrivateKey);
                publicKey  = PublicKeyAuth.ExtractEd25519PublicKeyFromEd25519SecretKey(privateKey);
            }

            return(new Key(privateKey, publicKey));
        }
        public SigningKey(string keyContents)
        {
            var split = keyContents.Split(" ");

            if (split.Length != 3)
            {
                throw new InvalidDataException("Key file is in the wrong format. Should be '$type $name $key'");
            }

            Type = split[0];
            Name = split[1];
            // Synapse uses unpadded base64, so we need to add our own padding to make this work.
            var b64Seed = split[2].Trim();

            while (b64Seed.Length % 4 != 0)
            {
                b64Seed += "=";
            }

            Pair      = PublicKeyAuth.GenerateKeyPair(Convert.FromBase64String(b64Seed));
            PublicKey = Convert.ToBase64String(Pair.PublicKey);
        }
        public void DetachedSignTest()
        {
            var    kp      = PublicKeyAuth.GenerateKeyPair();
            string message = "Hello, World!";

            byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message);

            var sig1 = PublicKeyAuth.SignDetached(message, kp.Secret);
            var sig2 = PublicKeyAuth.SignDetached(byteMessage, kp.Secret);

            Assert.AreEqual(Convert.ToBase64String(sig1), Convert.ToBase64String(sig2));
            Assert.AreEqual(64, sig1.Length);
            Assert.AreEqual(64, sig2.Length);

            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig1, byteMessage, kp.Public));
            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig1, message, kp.Public));
            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig2, byteMessage, kp.Public));
            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig2, message, kp.Public));

            var kp2 = PublicKeyAuth.GenerateKeyPair();

            Assert.IsFalse(PublicKeyAuth.VerifyDetached(sig2, message, kp2.Public));
            Assert.IsFalse(PublicKeyAuth.VerifyDetached(sig2, "Invalid message test", kp.Public));
        }