Ejemplo n.º 1
0
        public void String_Encrypt4096Decrypt_GivesEqualString()
        {
            var keys = RsaEncryption.GenerateKeyPairs(RsaKeySizes.Rsa4096);

            var    plainText = Guid.NewGuid().ToString();
            string encrypted = RsaEncryption.Encrypt(plainText, keys.PublicKey);
            string decrypted = RsaEncryption.Decrypt(encrypted, keys.PrivateKey);

            Assert.Equal(plainText, decrypted);
        }
Ejemplo n.º 2
0
        public void TestPublicPrivateKeyConversation()
        {
            // alice sends message to bob
            // bob send message back to alica
            //
            // failures:
            //
            // charlie tries to read alices's message
            // charlie tries to read bob's message
            // alice tries to read a message she encrypted

            RsaEncryption alice   = new RsaEncryption();
            RsaEncryption bob     = new RsaEncryption();
            RsaEncryption charlie = new RsaEncryption();

            byte[] aliceToBobMessage       = alice.Encrypt(TestMessage, bob.PublicKey);
            byte[] decodedAliceMessage     = bob.Decrypt(aliceToBobMessage);
            string decodedAliceToBobString = System.Text.Encoding.Unicode.GetString(decodedAliceMessage);

            Assert.AreEqual(TestMessage, decodedAliceToBobString);
            Assert.AreNotEqual(Convert.ToBase64String(aliceToBobMessage), Convert.ToBase64String(decodedAliceMessage));

            byte[] bobToAliceMessage       = bob.Encrypt(TestMessageReply, alice.PublicKey);
            byte[] decodedBobMessage       = alice.Decrypt(bobToAliceMessage);
            string decodedBobToAliceString = System.Text.Encoding.Unicode.GetString(decodedBobMessage);

            Assert.AreEqual(TestMessageReply, decodedBobToAliceString);
            Assert.AreNotEqual(Convert.ToBase64String(bobToAliceMessage), Convert.ToBase64String(decodedBobMessage));

            try
            {
                charlie.Decrypt(aliceToBobMessage);
                Assert.Fail("charlie shouldnt be able to see alice's message to bob");
            }
            catch (System.Security.Cryptography.CryptographicException)
            {}

            try
            {
                charlie.Decrypt(bobToAliceMessage);
                Assert.Fail("charlie shouldnt be able to see bob's message to alice");
            }
            catch (System.Security.Cryptography.CryptographicException)
            {}

            try
            {
                alice.Decrypt(aliceToBobMessage);
                Assert.Fail("alice shouldnt be able to see her own message to bob - go figure!");
            }
            catch (System.Security.Cryptography.CryptographicException)
            {}
        }
Ejemplo n.º 3
0
    public void RsaEncrpytionTest()
    {
        var     rsa  = new RsaEncryption();
        RsaKeys keys = rsa.GenerateKeys();

        var data = Encoding.UTF8.GetBytes(testMessage);

        var encryptedData = rsa.Encrypt(data, keys.publicKey);
        var decryptedData = rsa.Decrypt(encryptedData, keys.privateKey);

        Assert.Equal(data, decryptedData);
    }
Ejemplo n.º 4
0
        public void ByteArray_EncryptDecrypt_GivesEqualByteArray()
        {
            var keys = RsaEncryption.GenerateKeyPairs();

            Guid plainText = Guid.NewGuid();

            byte[] encrypted = RsaEncryption.Encrypt(plainText.ToByteArray(), keys.PublicKey);
            byte[] decrypted = RsaEncryption.Decrypt(encrypted, keys.PrivateKey);
            Guid   result    = new Guid(decrypted);

            Assert.Equal(plainText, result);
        }
Ejemplo n.º 5
0
        public void Encrypt_Should_ThrowException_When_EncryptingToMuchData()
        {
            // Arrange
            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();
            var e1         = new RsaEncryption();

            // Act
            e1.GenerateNewKeyset(ref publicKey, ref privateKey);

            // Assert
            Assert.Throws <CryptographicException>(() => e1.Encrypt(new EncryptionData(_targetString), publicKey));
        }
Ejemplo n.º 6
0
        public void Encrypt_Should_ThrowException_When_DataIsNull()
        {
            // Arrange
            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();
            var e1         = new RsaEncryption();

            e1.GenerateNewKeyset(ref publicKey, ref privateKey);
            EncryptionData data = null;

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => e1.Encrypt(data, publicKey));
        }
Ejemplo n.º 7
0
 public bool Login(string login, string password){
UserStore userStore = new UserStore();
RsaEncryption rsaEncryption = new RsaEncryption();
User myUser = userStore.Get(login);
if(myUser == null)
{
    return false;
}
if(myUser.Password == rsaEncryption.Encrypt(password){
return true;
}
return false;
 }
Ejemplo n.º 8
0
        public async Task <IActionResult> Create([Bind("Id,Name,LastName,Password,Birthdate,Phone,Email,ProfilePicture")] Person person)
        {
            if (ModelState.IsValid)
            {
                person.Username = person.Name + person.LastName + person.Birthdate;
                person.Password = rsa.Encrypt(person.Password);
                _context.Add(person);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(person));
        }
Ejemplo n.º 9
0
        public void Decrypt_Should_ReturnExpectedResult_When_UsingDefaultKeys()
        {
            // Arrange
            AddKeysToEnvironment();
            var e1 = new RsaEncryption();
            var e2 = new RsaEncryption();

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret));
            var decryptedData = e2.Decrypt(encryptedData);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);

            RemoveKeysToEnvironment();
        }
Ejemplo n.º 10
0
        public void Decrypt_Should_ReturnExpectedResult_When_KeyIsStoredInCertificate()
        {
            // Arrange
            var cert = $"{_assemblyPath}RsaEncrypt";

            var publicKey  = RsaPublicKey.LoadFromCertificateFile(cert + ".cer");
            var privateKey = RsaPrivateKey.LoadFromCertificateFile(cert + ".pfx", "password");

            var e1 = new RsaEncryption();
            var e2 = new RsaEncryption();

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);
        }
Ejemplo n.º 11
0
        public void Decrypt_Should_ReturnExpectedResult_When_UsingExplicitKeySizeAndGeneratedKeys()
        {
            // Arrange
            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();

            var e1 = new RsaEncryption(4096);
            var e2 = new RsaEncryption(4096);

            e1.GenerateNewKeyset(ref publicKey, ref privateKey);

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);
        }
Ejemplo n.º 12
0
        public void Decrypt_Should_ReturnExpectedResult_When_KeyIsStoredInXml()
        {
            // Arrange
            const string publicKeyXml = "<RSAKeyValue>" +
                                        "<Modulus>0D59Km2Eo9oopcm7Y2wOXx0TRRXQFybl9HHe/ve47Qcf2EoKbs9nkuMmhCJlJ" +
                                        "zrq6ZJzgQSEbpVyaWn8OHq0I50rQ13dJsALEquhlfwVWw6Hit7qRvveKlOAGfj8xdkaXJ" +
                                        "LYS1tA06tKHfYxgt6ysMBZd0DIedYoE1fe3VlLZyE=</Modulus>" +
                                        "<Exponent>AQAB</Exponent>" +
                                        "</RSAKeyValue>";

            const string privateKeyXml = "<RSAKeyValue>" +
                                         "<Modulus>0D59Km2Eo9oopcm7Y2wOXx0TRRXQFybl9HHe/ve47Qcf2EoKbs9nkuMmhCJlJ" +
                                         "zrq6ZJzgQSEbpVyaWn8OHq0I50rQ13dJsALEquhlfwVWw6Hit7qRvveKlOAGfj8xdkaXJ" +
                                         "LYS1tA06tKHfYxgt6ysMBZd0DIedYoE1fe3VlLZyE=</Modulus>" +
                                         "<Exponent>AQAB</Exponent>" +
                                         "<P>/1cvDks8qlF1IXKNwcXW8tjTlhjidjGtbT9k7FCYug+P6ZBDfqhUqfvjgLFF" +
                                         "/+dAkoofNqliv89b8DRy4gS4qQ==</P>" +
                                         "<Q>0Mgq7lyvmVPR1r197wnba1bWbJt8W2Ki8ilUN6lX6Lkk04ds9y3A0txy0ESya7dyg" +
                                         "9NLscfU3NQMH8RRVnJtuQ==</Q>" +
                                         "<DP>+uwfRumyxSDlfSgInFqh/+YKD5+GtGXfKtO4hu4xF+8BGqJ1YXtkL" +
                                         "+Njz2zmADOt5hOr1tigPSQ2EhhIqUnAeQ==</DP>" +
                                         "<DQ>M5Ofd28SOjCIwCHjwG+Q8v1qzz3CBNljI6uuEGoXO3ix" +
                                         "bkggVRfKcMzg2C6AXTfeZE6Ifoy9OyhvLlHTPiXakQ==</DQ>" +
                                         "<InverseQ>yQIJMLdL6kU4VK7M5b5PqWS8XzkgxfnaowRs9mhSEDdwwWPtUXO8aQ9G3" +
                                         "zuiDUqNq9j5jkdt77+c2stBdV97ew==</InverseQ>" +
                                         "<D>HOpQXu/OFyJXuo2EY43BgRt8bX9V4aEZFRQqrqSfHOp8VYASasiJzS+VTYupGAVqUP" +
                                         "xw5V1HNkOyG0kIKJ+BG6BpIwLIbVKQn/ROs7E3/vBdg2+QXKhikMz/4gY" +
                                         "x2oEsXW2kzN1GMRop2lrrJZJNGE/eG6i4lQ1/inj1Tk/sqQE=</D>" +
                                         "</RSAKeyValue>";

            var publicKey  = new RsaPublicKey(publicKeyXml);
            var privateKey = new RsaPrivateKey(privateKeyXml);

            var e1 = new RsaEncryption();
            var e2 = new RsaEncryption();

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);
        }
Ejemplo n.º 13
0
        public void Decrypt_Should_ReturnExpectedResult_When_KeyIsStoredInConfig()
        {
            // Arrange
            AddKeysToEnvironment();

            var publicKey  = RsaPublicKey.LoadFromEnvironment();
            var privateKey = RsaPrivateKey.LoadFromEnvironment();

            var e1 = new RsaEncryption();
            var e2 = new RsaEncryption();

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);

            RemoveKeysToEnvironment();
        }
Ejemplo n.º 14
0
        public static EncryptedString Encrypt(Base64String publicKey, byte[] bytesToEncrypt)
        {
            if (string.IsNullOrWhiteSpace(publicKey?.ToString()))
            {
                throw new ArgumentException("Should be not empty string", nameof(publicKey));
            }

            if (bytesToEncrypt == null)
            {
                return(null);
            }

            using (var aes = new AesManaged())
            {
                aes.GenerateKey();
                aes.GenerateIV();

                var aesKeys           = new AesKeysEnvelope(aes.Key.EncodeToBase64(), aes.IV.EncodeToBase64());
                var serializedAesKeys = JsonConvert.SerializeObject(aesKeys).ToBase64();

                var encryptedAesKeys = RsaEncryption.Encrypt(serializedAesKeys.DecodeToBytes(), publicKey.DecodeToBytes());

                using (var encryptor = aes.CreateEncryptor())
                    using (var encryptedStream = new MemoryStream())
                        using (var cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(bytesToEncrypt, 0, bytesToEncrypt.Length);

                            cryptoStream.Flush();
                            cryptoStream.Close();

                            var encryptedBody              = encryptedStream.ToArray();
                            var encryptedMessage           = new EncryptedMessage(encryptedAesKeys.EncodeToBase64(), encryptedBody.EncodeToBase64());
                            var serializedEncryptedMessage = JsonConvert.SerializeObject(encryptedMessage).ToBase64();

                            return(new EncryptedString(serializedEncryptedMessage));
                        }
            }
        }
Ejemplo n.º 15
0
        public void TestPublicPrivateKeyConversationRehydratedKey()
        {
            // same as above , but also use serialized key to rehydrate alice and bob
            RsaEncryption alice = new RsaEncryption();
            RsaEncryption bob   = new RsaEncryption();

            byte[] aliceToBobMessage   = alice.Encrypt(TestMessage, bob.PublicKey);
            byte[] decodedAliceMessage = bob.Decrypt(aliceToBobMessage);
            Assert.AreEqual(TestMessage, System.Text.Encoding.Unicode.GetString(decodedAliceMessage));

            byte[] bobToAliceMessage = bob.Encrypt(TestMessageReply, alice.PublicKey);
            byte[] decodedBobMessage = alice.Decrypt(bobToAliceMessage);
            Assert.AreEqual(TestMessageReply, System.Text.Encoding.Unicode.GetString(decodedBobMessage));

            // rehydrate bob
            RsaEncryption alice2 = new RsaEncryption(alice.PrivatePublicKey);
            RsaEncryption bob2   = new RsaEncryption(bob.PrivatePublicKey);

            Assert.AreEqual(alice.PrivatePublicKey, alice2.PrivatePublicKey);
            Assert.AreEqual(bob.PrivatePublicKey, bob2.PrivatePublicKey);

            aliceToBobMessage   = alice2.Encrypt(TestMessage, bob2.PublicKey);
            decodedAliceMessage = bob2.Decrypt(aliceToBobMessage);
            Assert.AreEqual(TestMessage, System.Text.Encoding.Unicode.GetString(decodedAliceMessage));

            bobToAliceMessage = bob2.Encrypt(TestMessageReply, alice2.PublicKey);
            decodedBobMessage = alice2.Decrypt(bobToAliceMessage);
            Assert.AreEqual(TestMessageReply, System.Text.Encoding.Unicode.GetString(decodedBobMessage));

            // decrypt with old objects
            decodedAliceMessage = bob.Decrypt(aliceToBobMessage);
            Assert.AreEqual(TestMessage, System.Text.Encoding.Unicode.GetString(decodedAliceMessage));

            decodedBobMessage = alice.Decrypt(bobToAliceMessage);
            Assert.AreEqual(TestMessageReply, System.Text.Encoding.Unicode.GetString(decodedBobMessage));
        }
Ejemplo n.º 16
0
        public void SslLikeConversationUseStory()
        {
            // use story: alice send a file (encypted) to bob using run-time generated keys
            //
            // sequence:
            //
            // 1.  alice generated rsa private/public key pair
            // 2.  bob generates rsa private/private key pair
            // 3.  alice generates symmetrical aes key and iv
            // 4.  alice encryptes file with aes symmetric key and iv (3)
            // 5.  alice encrypts aes symmetrical key and iv (3) with bob's public key (2)
            // 6.  alice sends encrypted aes key and iv (5) to bob
            // 7.  alice sends encrypted file (4) to bob
            // 8.  bob decrypts aes key and iv (6) with his private rsa key
            // 9.  bob generates symmetrical key [aes] with decrypted aes key and iv
            // 10. bob decrypts file (7) with aes key (8)
            //

            // 1. 3.
            AesEncryption aliceAes = new AesEncryption();
            RsaEncryption aliceRsa = new RsaEncryption();

            // 2.
            RsaEncryption bobRsa = new RsaEncryption();

            // 4.
            aliceAes.EncryptFile(TestFile, TestFileEncrypted);

            // 5.
            byte[] rsaEncryptedAesKey = aliceRsa.Encrypt(aliceAes.Key, bobRsa.PublicKey);
            byte[] rsaEncryptedAesIV  = aliceRsa.Encrypt(aliceAes.IV, bobRsa.PublicKey);

            // 6. 7.
            // some over aether somehow, usually tcp/ip sockets

            // 8.
            byte[] decryptedAesKey = bobRsa.Decrypt(rsaEncryptedAesKey);
            byte[] decryptedAesIV  = bobRsa.Decrypt(rsaEncryptedAesIV);

            // 9.
            AesEncryption bobAes = new AesEncryption(decryptedAesKey, decryptedAesIV);

            // 10.
            bobAes.DecryptFile(TestFileEncrypted, TestFileDecrypted);

            // assert keys
            Assert.AreNotEqual(Convert.ToBase64String(rsaEncryptedAesKey), Convert.ToBase64String(decryptedAesKey));
            Assert.AreNotEqual(Convert.ToBase64String(rsaEncryptedAesIV), Convert.ToBase64String(decryptedAesIV));

            // assert files
            Hashing h = new Hashing();

            byte[] b     = h.Sha512HashFile(TestFile);
            string hash1 = Convert.ToBase64String(b);

            Console.WriteLine(hash1);

            b = h.Sha512HashFile(TestFileEncrypted);
            string hash2 = Convert.ToBase64String(b);

            Console.WriteLine(hash2);

            b = h.Sha512HashFile(TestFileDecrypted);
            string hash3 = Convert.ToBase64String(b);

            Console.WriteLine(hash3);

            Assert.AreEqual(hash1, hash3);
            Assert.AreNotEqual(hash1, hash2);
        }