Beispiel #1
0
        public void Sha256Test()
        {
            var    sha256 = CryptoHash.Sha256(System.Text.Encoding.UTF8.GetBytes(hashString));
            string hex    = BitConverter.ToString(sha256).Replace("-", string.Empty).ToLower();

            Assert.AreEqual(sha256out, hex);
        }
        /// <summary>
        ///   Validates server acceptance message
        /// </summary>
        /// <remark>
        ///   Here the client verifies that the received message length is 80
        ///   bytes, then opens the encrypted box and verifies that the sent
        ///   message is server's signature to the derived shared secrets. With
        ///   this the handshake concludes.
        /// </remark>
        /// <exception cref="ArgumentException">
        ///   Thrown if the server's Accept <paramref name="msg"/> is not the
        ///   correct size or the signature is not valid.
        /// </exception>
        /// <param name="msg">
        ///   The received message, encrypted server's signature.
        /// </param>
        public void VerifyAccept(byte[] msg)
        {
            if (msg.Length != 80)
            {
                throw new ArgumentException("Incorrect message size");
            }

            var nonce = new byte[NONCE_SIZE];

            nonce.Initialize();

            // Concatenate the network key and derived secrets to obtain
            // the message key
            var key = CryptoHash.Sha256(
                Utils.Concat(_network_key, _shared_ab, _shared_aB, _shared_Ab)
                );

            var opened_msg = SecretBox.Open(msg, nonce, key);

            // Compute the message that it is supposed to be signed with the
            // server's long term key
            var hashed        = CryptoHash.Sha256(_shared_ab);
            var msg_to_verify = Utils.Concat(
                _network_key, detached_signature_A,
                _longterm_client_keypair.PublicKey, hashed
                );

            if (!PublicKeyAuth.VerifyDetached(opened_msg, msg_to_verify, _longterm_server_pk))
            {
                throw new ArgumentException("Invalid signature");
            }
        }
Beispiel #3
0
        /// <summary>
        ///   Computes the message that accepts the handshake.
        /// </summary>
        /// <remark>
        ///   Here the server computes a signature of the network key, the
        ///   signature of the long term client's public key and a sha 256 of
        ///   the shared ab secret. This is signed with the server's long term
        ///   private key.
        ///
        ///   This signature is encrypted using a sha 256 of the network key
        ///   and all of the derived secrets.
        /// </remark>
        /// <returns>
        ///   A byte array of length 80 consisting of the message.
        /// </returns>
        public byte[] Accept()
        {
            var detached_signature = PublicKeyAuth.SignDetached(
                Utils.Concat(
                    _network_key,
                    detached_signature_A,
                    _longterm_client_pk,
                    CryptoHash.Sha256(_shared_ab)
                    ),
                _longterm_server_keypair.PrivateKey
                );

            // A nonce consisting of 24 zeros
            var nonce = new byte[NONCE_SIZE];

            nonce.Initialize();

            var key = CryptoHash.Sha256(
                Utils.Concat(_network_key, _shared_ab, _shared_aB, _shared_Ab)
                );

            var msg = SecretBox.Create(detached_signature, nonce, key);

            return(msg);
        }
        /// <summary>
        ///   Crafts the client Authenticate message
        /// </summary>
        /// <remark>
        ///   Consists of a signature of the network identifier, the server's
        ///   long term public key and a sha 256 of the derived secret ab,
        ///   concatenated with the client's long term public key. All
        ///   encrypted using the network identifier and the derived secrets
        ///   ab and aB.
        ///
        ///   This sets the object's <see cref="detached_signature_A"/>
        /// </remark>
        /// <returns>
        ///   The client Authenticate message
        /// </returns>
        public byte[] Authenticate()
        {
            var hash_ab = CryptoHash.Sha256(this._shared_ab);

            // Concatenate the network identifier, the server's public key and
            // the hash of the derived secret.
            var to_sign = Utils.Concat(
                _network_key, _longterm_server_pk, hash_ab
                );

            // Sign the first portion of the message and save it in the object
            // state for later use in the server accept verification.
            detached_signature_A = PublicKeyAuth.SignDetached(
                to_sign, _longterm_client_keypair.PrivateKey
                );

            // Create the plaintext message
            var plaintext = Utils.Concat(
                detached_signature_A, _longterm_client_keypair.PublicKey
                );

            // Create the key from the network key and the shared secrets
            var box_key = Utils.Concat(
                _network_key, _shared_ab, _shared_aB
                );

            // A nonce consisting of 24 zeros
            var nonce = new byte[NONCE_SIZE];

            nonce.Initialize();

            var msg = SecretBox.Create(plaintext, nonce, CryptoHash.Sha256(box_key));

            return(msg);
        }
Beispiel #5
0
        /// <summary>
        ///   Given the keys obtained during the handshake generates a pair of
        ///   Boxer/Unboxer.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     TODO: Write about the process detailed in the spec
        ///   </para>
        /// </remarks>
        /// <param name="derived_secret">
        ///   The secret derived from the client long term key and the server's
        ///   ephemeral key (Ab).
        /// </param>
        /// <param name="foreing_pubkey">
        ///   The public key that identifies the other peer, that is, the server
        ///   public key if this is called from the client and vice versa.
        /// </param>
        /// <param name="self_pubkey">
        ///   The public key that identifies the entity calling this.
        /// </param>
        /// <param name="network_key">
        ///   The key that identifies the network, in the case of scuttlebutt is
        ///   the one posted in the scuttlebutt protocol
        ///   <see href="https://ssbc.github.io/scuttlebutt-protocol-guide/">
        ///     guide
        ///   </see>.
        /// </param>
        /// <param name="a">
        ///   The client's ephemeral public key used during the handshake.
        /// </param>
        /// <param name="b">
        ///   The server's ephemeral public key used during the handshake.
        /// </param>
        /// <returns>
        ///   The Boxer/Unboxer pair that a client or server can use to
        ///   communicate with the other.
        /// </returns>
        public static (Boxer, Unboxer) Build(
            byte[] derived_secret,
            byte[] foreing_pubkey,
            byte[] self_pubkey,
            byte[] network_key,
            byte[] a,
            byte[] b
            )
        {
            var common = CryptoHash.Sha256(CryptoHash.Sha256(derived_secret));

            var send_key = CryptoHash.Sha256(Utils.Concat(common, foreing_pubkey));
            var recv_key = CryptoHash.Sha256(Utils.Concat(common, self_pubkey));

            var send_nonce = new byte[24];
            var recv_nonce = new byte[24];

            var bhmac = SecretKeyAuth.Sign(b, network_key);
            var ahmac = SecretKeyAuth.Sign(a, network_key);

            Buffer.BlockCopy(send_nonce, 0, bhmac, 0, 24);
            Buffer.BlockCopy(recv_nonce, 0, ahmac, 0, 24);

            var boxer   = new Boxer(send_key, send_nonce);
            var unboxer = new Unboxer(recv_key, recv_nonce);

            return(boxer, unboxer);
        }
Beispiel #6
0
        /// <summary>
        ///   Checks for <paramref name="msg"/> length and validity, extracting
        ///   the client's long term public key upon success.
        /// </summary>
        /// <param name="msg">Client authenticate message</param>
        /// <exception cref="ArgumentException">
        ///   Thrown if the client Auth <paramref name="msg"/> fails to pass the
        ///   checks.
        /// </exception>
        public void AcceptAuth(byte[] msg)
        {
            if (msg.Length != 112)
            {
                throw new ArgumentException("Incorrect secretbox length");
            }

            // A nonce consisting of 24 zeros
            var nonce = new byte[NONCE_SIZE];

            nonce.Initialize();

            // Calculate the decryption key from the dervided keys
            var key = CryptoHash.Sha256(
                Utils.Concat(_network_key, _shared_ab, _shared_aB)
                );

            var opened_msg = SecretBox.Open(msg, nonce, key);

            if (opened_msg.Length != 96)
            {
                throw new ArgumentException("Invalid size of opened message");
            }

            // Extract the signature of the long term client's public key
            // signed with the derived secret
            var detached_signature = new byte[SIG_SIZE];

            Buffer.BlockCopy(opened_msg, 0, detached_signature, 0, SIG_SIZE);

            // Extract the long term client's public key
            var lt_cli_pk = new byte[PUB_KEY_SIZE];

            Buffer.BlockCopy(opened_msg, SIG_SIZE, lt_cli_pk, 0, PUB_KEY_SIZE);

            var shared_hashed = CryptoHash.Sha256(_shared_ab);
            // Concat network_key, server longterm pk and sha256 hashed shared_ab secret
            var to_verify = Utils.Concat(
                _network_key, _longterm_server_keypair.PublicKey, shared_hashed
                );

            if (!PublicKeyAuth.VerifyDetached(detached_signature, to_verify, lt_cli_pk))
            {
                throw new ArgumentException("Signature does not match");
            }

            detached_signature_A = detached_signature;
            _longterm_client_pk  = lt_cli_pk;
            this.DeriveAb();
        }
Beispiel #7
0
        private static byte[] SodiumHash(HashType hash, byte[] buffer)
        {
            switch (hash)
            {
            case HashType.Blake2B:
                return(Blake2B.ComputeHash(buffer));

            case HashType.SipHash24:
                return(ShortHash.Hash(buffer, SipHash24Key));

            case HashType.Sha256:
                return(CryptoHash.Sha256(buffer));

            case HashType.Sha512:
                return(CryptoHash.Sha512(buffer));

            case HashType.Md5:
            case HashType.Sha1:
            case HashType.Sha384:
            default:
                throw new NotSupportedException();
            }
        }
Beispiel #8
0
        public void CryptoHashSha256ArrayTest()
        {
            var actual = CryptoHash.Sha256(Encoding.UTF8.GetBytes("Adam Caudill"));

            CollectionAssert.AreEqual(Utilities.HexToBinary(SHA256_HASH), actual);
        }
Beispiel #9
0
        public void CryptoHashSha256StringTest()
        {
            var actual = CryptoHash.Sha256("Adam Caudill");

            CollectionAssert.AreEqual(Utilities.HexToBinary(SHA256_HASH), actual);
        }
Beispiel #10
0
 public static byte[] Sha256(this byte[] input)
 {
     return(CryptoHash.Sha256(input));
 }
        static void Main(string[] args)
        {
            var str = CryptoSecureString.ToSecureString(new[] { 'h', 'i', 'r', 'o' });

            char [] charArray = CryptoSecureString.CharacterData(str);

            string unsecure = CryptoSecureString.ConvertToUnsecureString(str);

            var rsaParameters = new CryptoRSAParameters();

            rsaParameters.GenerateKeys();

            Console.WriteLine($"Random {Convert.ToBase64String(CryptoRandom.Generate(32))}");

            Console.WriteLine("-------------------------------------------");

            var message      = "Hiro universe";
            var messageBytes = Encoding.UTF8.GetBytes(message);

            Console.WriteLine($"MD5 message: {message} hash: {Convert.ToBase64String(CryptoHash.Md5(messageBytes))}");
            Console.WriteLine($"SHA1 message: {message} hash: {Convert.ToBase64String(CryptoHash.Sha1(messageBytes))}");
            Console.WriteLine($"SHA256 message: {message} hash: {Convert.ToBase64String(CryptoHash.Sha256(messageBytes))}");
            Console.WriteLine($"SHA512 message: {message} hash: {Convert.ToBase64String(CryptoHash.Sha512(messageBytes))}");

            var key = CryptoRandom.Generate(32);

            Console.WriteLine($"HMAC MD5 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Md5(messageBytes, key))}");
            Console.WriteLine($"HMAC SHA1 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Sha1(messageBytes, key))}");
            Console.WriteLine($"HMAC SHA256 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Sha256(messageBytes, key))}");
            Console.WriteLine($"HMAC SHA512 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Sha512(messageBytes, key))}");

            Console.WriteLine("-------------------------------------------");
            Console.WriteLine("Passsword hash with salt");
            Console.WriteLine($"Password: {message}");
            Console.WriteLine($"Password hashed: {Convert.ToBase64String(CryptoHash.Password(messageBytes))}");

            Console.WriteLine("-------------------------------------------");
            var salt = CryptoRandom.Generate(32);

            Console.WriteLine("Passsword hash with salt - Based Key Derivation Function - PBKDF2");
            Console.WriteLine($"Password: {message}");
            Console.WriteLine($"Password hashed 100 rounds: {Convert.ToBase64String(CryptoHash.Password(messageBytes, salt, 100))}");
            Console.WriteLine($"Password hashed 1000 rounds: {Convert.ToBase64String(CryptoHash.Password(messageBytes, salt, 1000))}");
            Console.WriteLine($"Password hashed 10000 rounds: {Convert.ToBase64String(CryptoHash.Password(messageBytes, salt, 10000))}");

            Console.WriteLine("-------------------------------------------");
            var desKey = CryptoRandom.Generate(8);
            var desIv  = CryptoRandom.Generate(8);
            var desEncryptedMessage = CryptoDes.Encrypt(message, desKey, desIv);
            var desDecryptedMessage = CryptoDes.Decrypt(desEncryptedMessage, desKey, desIv);

            Console.WriteLine("DES Encryption");
            Console.WriteLine($"Text: {message}");
            Console.WriteLine($"Key: {Convert.ToBase64String(desKey)}");
            Console.WriteLine($"IV: {Convert.ToBase64String(desIv)}");
            Console.WriteLine($"Encrypted: {Convert.ToBase64String(desEncryptedMessage)}");
            Console.WriteLine($"Decrypted: {desDecryptedMessage}");

            Console.WriteLine("-------------------------------------------");
            var tripleDesKey = CryptoRandom.Generate(16);
            var tripleDesIv  = CryptoRandom.Generate(8);
            var tripleDesEncryptedMessage = CryptoTripleDes.Encrypt(message, tripleDesKey, tripleDesIv);
            var tripleDesDecryptedMessage = CryptoTripleDes.Decrypt(tripleDesEncryptedMessage, tripleDesKey, tripleDesIv);

            Console.WriteLine("Triple DES Encryption");
            Console.WriteLine($"Text: {message}");
            Console.WriteLine($"Key: {Convert.ToBase64String(tripleDesKey)}");
            Console.WriteLine($"IV: {Convert.ToBase64String(tripleDesIv)}");
            Console.WriteLine($"Encrypted: {Convert.ToBase64String(tripleDesEncryptedMessage)}");
            Console.WriteLine($"Decrypted: {tripleDesDecryptedMessage}");

            Console.WriteLine("-------------------------------------------");
            var aesKey = CryptoRandom.Generate(32);
            var aesIv  = CryptoRandom.Generate(16);
            var aesEncryptedMessage = CryptoAes.Encrypt(message, aesKey, aesIv);
            var aesDecryptedMessage = CryptoAes.Decrypt(aesEncryptedMessage, aesKey, aesIv);

            Console.WriteLine("AES Encryption");
            Console.WriteLine($"Text: {message}");
            Console.WriteLine($"Key: {Convert.ToBase64String(aesKey)}");
            Console.WriteLine($"IV: {Convert.ToBase64String(aesIv)}");
            Console.WriteLine($"Encrypted: {Convert.ToBase64String(aesEncryptedMessage)}");
            Console.WriteLine($"Decrypted: {aesDecryptedMessage}");


            Console.WriteLine("-------------------------------------------");
            var rsaEncryptedMessage = CryptoRsa.Encrypt(messageBytes, rsaParameters.publicKey);
            var rsaDecryptedMessage = CryptoRsa.Decrypt(rsaEncryptedMessage, rsaParameters.privateKey);

            Console.WriteLine("RSA Encryption");
            Console.WriteLine($"Text: {message}");
            Console.WriteLine($"Encrypted: {Convert.ToBase64String(rsaEncryptedMessage)}");
            Console.WriteLine($"Decrypted: {Encoding.Default.GetString(rsaDecryptedMessage)}");

            Console.WriteLine("-------------------------------------------");
            var hybridEncryptedPacket  = CryptoHybrid.Encrypt(message, rsaParameters.publicKey);
            var hybridDecryptedMessage = CryptoHybrid.Decrypt(hybridEncryptedPacket, rsaParameters.privateKey);

            Console.WriteLine("Hybrid Encryption using AES and RSA");
            Console.WriteLine($"Text: {message}");
            Console.WriteLine($"Encrypted: {Convert.ToBase64String(hybridEncryptedPacket.EncryptedData)}");
            Console.WriteLine($"Decrypted: {hybridDecryptedMessage}");

            Console.WriteLine("-------------------------------------------");
            var hashedMessage = CryptoHash.Sha256(messageBytes);
            var signature     = CryptoDigitalSignature.Sign(hashedMessage, rsaParameters.privateKey);
            var verify        = CryptoDigitalSignature.Verify(hashedMessage, signature, rsaParameters.publicKey);

            Console.WriteLine("Digital Signature");
            Console.WriteLine($"Text: {message}");
            Console.WriteLine($"Signature: {Convert.ToBase64String(signature)}");
            Console.WriteLine("Is Verified: " + (verify ? "true" : "false"));

            Console.WriteLine("-------------------------------------------");
            try {
                var hybridSignatureEncryptedPacket  = CryptoHybridIntegrity.Encrypt(message, rsaParameters);
                var hybridSignatureDecryptedMessage = CryptoHybridIntegrity.Decrypt(hybridSignatureEncryptedPacket, rsaParameters);
                Console.WriteLine("Hybrid encryption with digital signature");
                Console.WriteLine($"Text: {message}");
                Console.WriteLine($"Signature: {Convert.ToBase64String(hybridSignatureEncryptedPacket.Signature)}");
                Console.WriteLine($"Encrypted: {Convert.ToBase64String(hybridSignatureEncryptedPacket.EncryptedData)}");
                Console.WriteLine($"Decrypted: {hybridSignatureDecryptedMessage}");
            }
            catch (CryptographicException ex)
            {
                Console.WriteLine("Error : " + ex.Message);
            }
        }