Example #1
0
        private void ValidationComplete(UserCookieModel cookie)
        {
            if (cookie != null)
            {
                UserSettingsModel.Instance.Cookie = cookie.AuthCookie;
                byte[] publicKey = null, privateKey = null;

                if (publicKey == null)
                {
                    RsaEncryption.GenerateKeys(out publicKey, out privateKey);
                }

                UserSettingsModel.Instance.PrivateKey = privateKey;
                cookie.User.PublicKey = publicKey;
                UserSettingsModel.Instance.Save(cookie.User);

                YapperServiceProxy.Instance.UpdateUserPublicKey(
                    cookie.User,
                    delegate(bool success)
                {
                    if (!success)
                    {
                        // clear the private key if public key update fails
                        UserSettingsModel.Instance.PrivateKey = null;
                    }
                }
                    );
            }

            Messenger.Default.Send <VerificationCodeValidationCompleteEvent>(new VerificationCodeValidationCompleteEvent(cookie != null));
            this.IsValidating = false;
        }
Example #2
0
 /// <summary>
 /// 私钥加密
 /// </summary>
 /// <param name="privateKey"></param>
 /// <param name="bytes"></param>
 /// <returns></returns>
 public static byte[] PrivateEncrypt(string privateKey, byte[] bytes)
 {
     using (RsaEncryption rsa = new RsaEncryption()) {
         rsa.LoadPrivateFromXml(privateKey);
         return(rsa.PrivateEncryption(bytes));
     }
 }
Example #3
0
 /// <summary>
 /// 公钥解密
 /// </summary>
 /// <param name="publicKey"></param>
 /// <param name="bytes"></param>
 /// <returns></returns>
 public static byte[] PublicDecrypt(string publicKey, byte[] bytes)
 {
     using (RsaEncryption rsa = new RsaEncryption()) {
         rsa.LoadPublicFromXml(publicKey);
         return(rsa.PublicDecryption(bytes));
     }
 }
Example #4
0
        public string Decrypt(JweConfig config)
        {
            byte[] unwrappedKey = RsaEncryption.UnwrapSecretKey(config, Base64Utils.URLDecode(EncryptedKey), "SHA-256");
            if (unwrappedKey == null)
            {
                throw new EncryptionException(String.Format("Failed to unwrap key {0}", EncryptedKey));
            }

            string encryptionMethod = Header.Enc;

            byte[] plaintext;
            if (A256GCM.Equals(encryptionMethod))
            {
                plaintext = AesGcm.Decrypt(unwrappedKey, this);
            }
            else if (A128CBC_HS256.Equals(encryptionMethod))
            {
                plaintext = AesCbc.Decrypt(unwrappedKey, this);
            }
            else
            {
                throw new EncryptionException(String.Format("Encryption method {0} is not supported", encryptionMethod));
            }
            return(Encoding.UTF8.GetString(plaintext));
        }
Example #5
0
        public byte[] DecryptToBytes(Base64String privateKey)
        {
            var encryptedMessage = JsonConvert.DeserializeObject <EncryptedMessage>(EncryptedValue.DecodeToString());
            var decryptedAesKey  = Base64String.Encode
                                   (
                RsaEncryption.Decrypt
                (
                    encryptedMessage.EncryptedAesKeys.DecodeToBytes(),
                    privateKey.DecodeToBytes()
                )
                                   );
            var aesKeys = JsonConvert.DeserializeObject <AesKeysEnvelope>(decryptedAesKey.DecodeToString());

            using (var aes = new AesManaged())
            {
                using (var encryptor = aes.CreateDecryptor(aesKeys.Key.DecodeToBytes(), aesKeys.Iv.DecodeToBytes()))
                    using (var encryptedStream = new MemoryStream(encryptedMessage.EncryptedBody.DecodeToBytes()))
                        using (var cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Read))
                            using (var plainStream = new MemoryStream())
                            {
                                cryptoStream.CopyTo(plainStream);

                                var decryptedBytes = plainStream.ToArray();

                                return(decryptedBytes);
                            }
            }
        }
Example #6
0
 public TelcoScoringEngine()
 {
     _extractorsContainer        = new ExtractorsContainer(String.Empty);
     _scoreCalculate             = new ScoreCalculator();
     _rsaEncryption              = new RsaEncryption();
     _initializeProcessScoreCard = new ManualResetEventSlim(true);
 }
Example #7
0
 /// <summary>
 /// 私钥加密
 /// </summary>
 /// <param name="privateKey"></param>
 /// <param name="EncryptString"></param>
 /// <returns></returns>
 public static string PrivateEncrypt(string privateKey, string EncryptString)
 {
     using (RsaEncryption rsa = new RsaEncryption()) {
         rsa.LoadPrivateFromXml(privateKey);
         var bs = Encoding.UTF8.GetBytes(EncryptString);
         return(Convert.ToBase64String(rsa.PrivateEncryption(bs)));
     }
 }
Example #8
0
 /// <summary>
 /// 公钥解密
 /// </summary>
 /// <param name="publicKey"></param>
 /// <param name="DecryptString"></param>
 /// <returns></returns>
 public static string PublicDecrypt(string publicKey, string DecryptString)
 {
     using (RsaEncryption rsa = new RsaEncryption()) {
         rsa.LoadPublicFromXml(publicKey);
         var bs = rsa.PublicDecryption(Convert.FromBase64String(DecryptString));
         return(Encoding.UTF8.GetString(bs));
     }
 }
Example #9
0
        protected void Application_Start()
        {
            // initialize the RSA encryption
            RsaEncryption.Setup();
            GlobalConfiguration.Configure(WebApiConfig.Register);

            // initialize the database
            Database.Initialize();
        }
Example #10
0
        public void GenerateNewKeyset_Should_ThrowException_When_PublicKeyIsNull()
        {
            // Arrange
            var          key        = new RsaEncryption();
            var          privateKey = new RsaPrivateKey();
            RsaPublicKey publicKey  = null;

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => key.GenerateNewKeyset(ref publicKey, ref privateKey));
        }
Example #11
0
        public void GenerteKey_GeneratesKeyPair()
        {
            var keys = RsaEncryption.GenerateKeyPairs();

            Assert.NotNull(keys);
            Assert.False(string.IsNullOrWhiteSpace(keys.PrivateKey?.Key));
            Assert.False(string.IsNullOrWhiteSpace(keys.PublicKey?.Key));

            Assert.True(keys.PrivateKey.Key.Length > keys.PublicKey.Key.Length);
        }
Example #12
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);
        }
Example #13
0
 public IHttpActionResult GetPublicKey()
 {
     try
     {
         return(Ok(RsaEncryption.GetPublicKeyString()));
     }
     catch (Exception e)
     {
         return(InternalServerError(e));
     }
 }
Example #14
0
        public void KeySizeStepBits_Should_ExpectedResult()
        {
            // Arrange
            const int expected = 8;

            // Act
            var rsa = new RsaEncryption();

            // Assert
            Assert.Equal(expected, rsa.KeySizeStepBits);
        }
    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);
    }
Example #16
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);
        }
Example #17
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)
            {}
        }
Example #18
0
        public void TestWrapUnwrapSecretKey_ShouldReturnTheOriginalKey()
        {
            // GIVEN
            var config           = TestUtils.GetTestFieldLevelEncryptionConfigBuilder().Build();
            var originalKeyBytes = Convert.FromBase64String("mZzmzoURXI3Vk0vdsPkcFw==");

            // WHEN
            var wrappedKeyBytes   = RsaEncryption.WrapSecretKey(config.EncryptionCertificate.GetRSAPublicKey(), originalKeyBytes, config.OaepPaddingDigestAlgorithm);
            var unwrappedKeyBytes = RsaEncryption.UnwrapSecretKey(config, wrappedKeyBytes, config.OaepPaddingDigestAlgorithm);

            // THEN
            Assert.IsTrue(originalKeyBytes.SequenceEqual(unwrappedKeyBytes));
        }
Example #19
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));
        }
Example #20
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;
 }
Example #21
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));
        }
Example #22
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();
        }
    public void RsaSigningTest()
    {
        var     rsa  = new RsaEncryption();
        RsaKeys keys = rsa.GenerateKeys();

        var hmacKey = Encoding.UTF8.GetBytes("HMAC KEY");
        var hmac    = new HmacAuthentication(hmacKey);

        var data = Encoding.UTF8.GetBytes(testMessage);
        var hash = hmac.ComputeHash(data);

        var signature = rsa.SignData(hash, keys.privateKey);
        var isValid   = rsa.VerifySignature(hash, signature, keys.publicKey);

        Assert.True(isValid);
    }
Example #24
0
        public void TestUnwrapSecretKey_InteroperabilityTest_OaepSha512()
        {
            // GIVEN
            var config = TestUtils.GetTestFieldLevelEncryptionConfigBuilder()
                         .WithOaepPaddingDigestAlgorithm("SHA-512")
                         .Build();
            const string wrappedKey      = "RuruMYP5rG6VP5vS4kVznIrSOjUzXyOhtD7bYlVqwniWTvxxZC73UDluwDhpLwX5QJCsCe8TcwGiQRX1u+yWpBveHDRmDa03hrc3JRJALEKPyN5tnt5w7aI4dLRnLuNoXbYoTSc4V47Z3gaaK6q2rEjydx2sQ/SyVmeUJN7NgxkhtHTyVWTymEM1ythL+AaaQ5AaXedhpWKhG06XYZIX4KV7T9cHEn+See6RVGGB2RUPHBJjrxJo5JoVSfnWN0gkTMyuwbmVaTWfsowbvh8GFibFT7h3uXyI3b79NiauyB7scXp9WidGues3MrTx4dKZrSbs3uHxzPKmCDZimuKfwg==";
            var          wrappedKeyBytes = Convert.FromBase64String(wrappedKey);

            // WHEN
            var unwrappedKeyBytes = RsaEncryption.UnwrapSecretKey(config, wrappedKeyBytes, config.OaepPaddingDigestAlgorithm);

            // THEN
            var expectedKeyBytes = Convert.FromBase64String("mZzmzoURXI3Vk0vdsPkcFw==");

            Assert.IsTrue(expectedKeyBytes.SequenceEqual(unwrappedKeyBytes));
        }
Example #25
0
        public void TestUnwrapSecretKey_InteroperabilityTest_OaepSha256()
        {
            // GIVEN
            var config = TestUtils.GetTestFieldLevelEncryptionConfigBuilder()
                         .WithOaepPaddingDigestAlgorithm("SHA-256")
                         .Build();
            const string wrappedKey      = "ZLB838BRWW2/BtdFFAWBRYShw/gBxXSwItpxEZ9zaSVEDHo7n+SyVYU7mayd+9vHkR8OdpqwpXM68t0VOrWI8LD8A2pRaYx8ICyhVFya4OeiWlde05Rhsk+TNwwREPbiw1RgjT8aedRJJYbAZdLb9XEI415Kb/UliHyvsdHMb6vKyYIjUHB/pSGAAmgds56IhIJGfvnBLPZfSHmGgiBT8WXLRuuf1v48aIadH9S0FfoyVGTaLYr+2eznSTAFC0ZBnzebM3mQI5NGQNviTnEJ0y+uZaLE/mthiKgkv1ZybyDPx2xJK2n05sNzfIWKmnI/SOb65RZLlo1Q+N868l2m9g==";
            var          wrappedKeyBytes = Convert.FromBase64String(wrappedKey);

            // WHEN
            var unwrappedKeyBytes = RsaEncryption.UnwrapSecretKey(config, wrappedKeyBytes, config.OaepPaddingDigestAlgorithm);

            // THEN
            var expectedKeyBytes = Convert.FromBase64String("mZzmzoURXI3Vk0vdsPkcFw==");

            Assert.IsTrue(expectedKeyBytes.SequenceEqual(unwrappedKeyBytes));
        }
Example #26
0
        public void Encrypt_Should_ReturnSamePassword_When_ExplicitPasswordProvidedAndPasswordWithNonUTF8Password()
        {
            // Arrange
            var password          = new EncryptionData("A really long simple password", System.Text.Encoding.ASCII);
            var encrypt           = new ASymmetricEncryption(_publicKey, password);
            var encryptedPassword = new EncryptionData(new byte[256]);

            // Act
            var encryptedBytes = encrypt.Encrypt(_targetData);

            Buffer.BlockCopy(encryptedBytes.Bytes, 0, encryptedPassword.Bytes, 0, 256);

            var decryptedPassword = new RsaEncryption().Decrypt(encryptedPassword, _privateKey);

            // Assert
            Assert.True(decryptedPassword.Text == password.Text);
        }
Example #27
0
        public void Encrypt_Should_ReturnSamePassword_When_ExplicitPasswordProvidedAndPasswordLenghtLessThan16()
        {
            // Arrange
            var password          = new EncryptionData("password");
            var encrypt           = new ASymmetricEncryption(_publicKey, password);
            var encryptedPassword = new EncryptionData(new byte[256]);

            // Act
            var encryptedBytes = encrypt.Encrypt(_targetData);

            Buffer.BlockCopy(encryptedBytes.Bytes, 0, encryptedPassword.Bytes, 0, 256);

            var decryptedPassword = new RsaEncryption().Decrypt(encryptedPassword, _privateKey);

            // Assert
            Assert.True(decryptedPassword.Text == password.Text);
        }
Example #28
0
        public void Encrypt_Should_ReturnA32BytePassword()
        {
            // Arrange
            var encrypt           = new ASymmetricEncryption(_publicKey);
            var encryptedPassword = new EncryptionData(new byte[256]);
            var rsa = new RsaEncryption();

            // Act
            var encryptedBytes = encrypt.Encrypt(_targetData);

            Buffer.BlockCopy(encryptedBytes.Bytes, 0, encryptedPassword.Bytes, 0, 256);

            var password = rsa.Decrypt(encryptedPassword, _privateKey);

            // Assert
            Assert.True(password.Bytes.Length == 32);
        }
Example #29
0
        public void Verify_Should_ReturnTrue_When_ValidatingUnChangedSignedData()
        {
            // Arrange
            var secretData = new EncryptionData(Secret);

            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();
            var e1         = new RsaEncryption();

            e1.GenerateNewKeyset(ref publicKey, ref privateKey);

            // Act
            var signature = e1.Sign(secretData, privateKey);
            var actual    = e1.Verify(secretData, signature, publicKey);

            // Assert
            Assert.True(actual);
        }
Example #30
0
        public static string Encrypt(JweConfig config, String payload, JweHeader header)
        {
            byte[] cek = AesEncryption.GenerateCek(256);
            byte[] encryptedSecretKeyBytes = RsaEncryption.WrapSecretKey(config.EncryptionCertificate.GetRSAPublicKey(), cek, "SHA-256");
            string encryptedKey            = Base64Utils.URLEncode(encryptedSecretKeyBytes);

            byte[] iv           = AesEncryption.GenerateIV();
            byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);

            string headerString  = header.Json.ToString();
            string encodedHeader = Base64Utils.URLEncode(Encoding.UTF8.GetBytes(headerString));

            byte[] aad = Encoding.ASCII.GetBytes(encodedHeader);

            var encrypted = AesGcm.Encrypt(cek, iv, payloadBytes, aad);

            return(Serialize(encodedHeader, encryptedKey, Base64Utils.URLEncode(iv), Base64Utils.URLEncode(encrypted.Ciphertext), Base64Utils.URLEncode(encrypted.AuthTag)));
        }