Пример #1
0
        public static byte[] Pack(byte[] datas, IList <byte[]> serverKeys, bool seedCreated)
        {
            seedCreated = false;

            //先压缩 在加密
            var compress = true ? ZipFactory.GetZip().Compress(datas) : datas;

            var d = seedCreated ? CryptoFactory.GetCrypto(1).Encode(compress, serverKeys[0]) : compress;

            var cryptoByte = new byte[1];

            cryptoByte[0] = seedCreated ? (byte)128 : (byte)0;

            var zipByte = new byte[1];

            zipByte[0] = true ? (byte)128 : (byte)0;

            using (var stream = new MemoryStream())
            {
                stream.Write(BitConverter.GetBytes(d.Length + 6), 0, 4);
                stream.Write(zipByte, 0, 1);
                stream.Write(cryptoByte, 0, 1);
                stream.Write(d, 0, d.Length);

                return(stream.ToArray());
            }
        }
Пример #2
0
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSign_Click(object sender, EventArgs e)
        {
            btnSign.Enabled = false;
            try
            {
                var signData = "";
                if (cmbProviderType.Text == "哈希加密")
                {
                    var hashingProviderType = cmbEncryptType.Text;
                    var hashingProvider     = CryptoFactory.CreateHashing(hashingProviderType);
                    signData = hashingProvider.Signature(txtPost.Text, txtSecretKey.Text);
                }
                else //非对称加密
                {
                    var asymmetricProviderType = cmbEncryptType.Text;
                    var asymmetricProvide      = CryptoFactory.CreateAsymmetric(asymmetricProviderType);
                    asymmetricProvide.OutType = Vive.Crypto.Core.OutType.Hex;
                    signData = asymmetricProvide.SignData(txtPost.Text, txtprivateKey.Text);
                }
                txtResponse.Text = signData;
                //txtResponse.Text = "验名成功";

                INIHelper.Write(cmbEncryptType.Text + "_SignData.dat", signData);
                saveData();
            }
            catch (Exception ex) { txtResponse.Text = ex.ToString(); }
            btnSign.Enabled = true;
        }
        public void TestInvalidCertCreateCall()
        {
            var config = new CryptoConfig();

            Assert.Throws <ArgumentException>(
                () => CryptoFactory.CreateCert(config));
        }
        public void TestValidPbkdf2Sha256Key()
        {
            var config = new CryptoConfig
            {
                IsEncryptActive = true,
                IsPbeActive     = true,
                CipherAlgorithm = CipherAlgorithm.AES,
                KeySize         = 256,
                PbeAlgorithm    = PbeAlgorithm.PBKDF2,
                PbeDigest       = PbeDigest.SHA256,
                PbePassword     = "******".ToCharArray(),
                BlockMode       = BlockMode.CBC,
                Padding         = Padding.Pkcs7,
            };

            var pbeBuilder = CryptoFactory.CreatePbe(config);

            config = pbeBuilder.GenerateKeyBytes();

            var cipherBuilder = CryptoFactory.CreateCipher(config);

            config = cipherBuilder.EncryptTextToBytes("Hallo Welt");
            var decodedCipher = Convert.FromBase64String(config.Cipher);

            var result = cipherBuilder.DecryptBytesToText(decodedCipher);

            Assert.Equal("Hallo Welt", result);
        }
Пример #5
0
        /// <summary>
        /// Triggers processing of CryptoConfig object.
        /// Passes Config object to processing class constructors.
        /// </summary>
        /// <param name="plainText">string coming from MainView's TextEditor.</param>
        /// <param name="config">CryptoConfig object holding all config and cipher parameters.</param>
        /// <returns>updated CryptoConfig object</returns>
        public static CryptoConfig ProcessConfigOnSave(string plainText, CryptoConfig config)
        {
            if (config.IsEncryptActive)
            {
                if (config.IsPbeActive)
                {
                    var pbeBuilder = CryptoFactory.CreatePbe(config);
                    config = pbeBuilder.GenerateKeyBytes();
                }

                var cipherBuilder = CryptoFactory.CreateCipher(config);
                config = cipherBuilder.EncryptTextToBytes(plainText);
            }

            if (!config.IsIntegrityActive)
            {
                return(config);
            }

            if (config.Integrity == Integrity.Dsa)
            {
                var certBuilder = CryptoFactory.CreateCert(config);
                certBuilder.GenerateCerts();
                config = certBuilder.SignInput(config.Cipher);
            }
            else
            {
                var digestBuilder = CryptoFactory.CreateDigest(config);
                config = digestBuilder.SignInput(config.Cipher);
            }

            return(config);
        }
Пример #6
0
        public void RijndaelEncrypt()
        {
            ICryptoHelper crytographyHelper = CryptoFactory.Create(CryptographyAlgorithm.Rijndael);

            crytographyHelper.Entropy = ENCRYPTION_VALID_PASSWORD;
            string encryptedString = crytographyHelper.Encrypt(ENCRYPTION_TEST_STRING, StringEncodingType.Hex);

            Assert.IsFalse(StringHelper.Match(encryptedString, ENCRYPTION_TEST_STRING, true), "Encrypted String Equals String Passed In");
        }
Пример #7
0
        private static CryptoFactory CreateCryptoFactory()
        {
            CryptoFactory factory = new CryptoFactory();

            factory.Add(() => new V2Aes256CryptoFactory());
            factory.Add(() => new V1Aes128CryptoFactory());

            return(factory);
        }
Пример #8
0
 public override int Save(UserModel model)
 {
     //UserModel model = (UserModel)userModel;
     if (model.UserPassword?.StartsWith("{ENC}") == false)
     {
         model.UserPassword = CryptoFactory.Encrypt(model.UserPassword);
     }
     return(base.Save(model));
 }
        public void TestInvalidPbeCreateCall()
        {
            var config = new CryptoConfig {
                PbePassword = "******".ToCharArray()
            };

            Assert.Throws <ArgumentException>(
                () => CryptoFactory.CreatePbe(config));
        }
Пример #10
0
        public void TestMethod1()
        {
            var text     = "hello world";
            var key      = "(C)StudioStoneCircle.Inc.";
            var encrypto = CryptoFactory <CryptorEngineAES128> .Encrypt(text, key);

            var decrypto = CryptoFactory <CryptorEngineAES128> .Decrypt(encrypto, key);

            Assert.AreEqual(text, decrypto);
        }
Пример #11
0
        public void CreateRemote(EndPoint destination)
        {
            if (_server == null || _server.Host == "")
            {
                throw new ArgumentException("No server configured");
            }

            encryptor = CryptoFactory.GetEncryptor(_server.Method, _server.Password);
            decryptor = CryptoFactory.GetEncryptor(_server.Method, _server.Password);
        }
Пример #12
0
 public AppUserClaimModel GetUserFromClaims(ClaimsPrincipal userClaims)
 {
     return(new AppUserClaimModel
     {
         Id = CryptoFactory.Decrypt(_appOptions.GoogleClientSecret, userClaims.FindFirst(nameof(AppUserClaimModel.Id)).Value),
         EmailAddress = userClaims.FindFirst(nameof(AppUserClaimModel.EmailAddress)).Value,
         FirstName = userClaims.FindFirst(nameof(AppUserClaimModel.FirstName)).Value,
         LastName = userClaims.FindFirst(nameof(AppUserClaimModel.LastName)).Value,
         IsAdmin = Convert.ToBoolean(userClaims.FindFirst(nameof(AppUserClaimModel.IsAdmin)).Value)
     });
 }
        public void TestInvalidCertCreateConfig()
        {
            var config = new CryptoConfig
            {
                IsIntegrityActive = true,
                Integrity         = Integrity.Digest
            };

            Assert.Throws <ArgumentException>(
                () => CryptoFactory.CreateCert(config));
        }
Пример #14
0
 /// <summary>
 /// 解密码
 /// </summary>
 /// <param name="Password"></param>
 /// <returns></returns>
 public string GetPwd(string Password)
 {
     try
     {
         return(CryptoFactory.Create(CrytoType.TripleDES).Decrypt(Password));
     }
     catch (Exception ex)
     {
         WriteExceptionLog(ex);
         return("");
     }
 }
 public AppUserClaimModel GetUserFromClaims(ClaimsPrincipal userClaims)
 {
     return(new AppUserClaimModel
     {
         AppUserId = int.Parse(CryptoFactory.Decrypt(_appOptions.GoogleClientSecret, userClaims.FindFirst(nameof(AppUserClaimModel.AppUserId)).Value)),
         Username = userClaims.FindFirst(nameof(AppUserClaimModel.Username)).Value,
         FirstName = userClaims.FindFirst(nameof(AppUserClaimModel.FirstName)).Value,
         LastName = userClaims.FindFirst(nameof(AppUserClaimModel.LastName)).Value,
         CanViewRecipe = Convert.ToBoolean(userClaims.FindFirst(nameof(AppUserClaimModel.CanViewRecipe)).Value),
         CanEditRecipe = Convert.ToBoolean(userClaims.FindFirst(nameof(AppUserClaimModel.CanEditRecipe)).Value),
         IsAdmin = Convert.ToBoolean(userClaims.FindFirst(nameof(AppUserClaimModel.IsAdmin)).Value)
     });
 }
Пример #16
0
        private void OnBaseAcceptorClientConnect(object sender, Socket acceptedSocket)
        {
            TCPPacketConnection connection = new TCPPacketConnection(acceptedSocket);

            connection.Logger = Logger;

            if (!connection.InitializeCrypto(CryptoFactory.CreateCrypto(Crypto, false), CryptoHandshakeTimeout))
            {
                return;
            }

            SecureConnectionEstablished.Invoke(this, connection);
        }
Пример #17
0
        public void RijndaelDecryptValidPassword()
        {
            ICryptoHelper crytographyHelper = CryptoFactory.Create(CryptographyAlgorithm.Rijndael);

            crytographyHelper.Entropy = ENCRYPTION_VALID_PASSWORD;
            string encryptedString = crytographyHelper.Encrypt(ENCRYPTION_TEST_STRING, StringEncodingType.Hex);

            ICryptoHelper crytographyHelper2 = CryptoFactory.Create(CryptographyAlgorithm.Rijndael);

            crytographyHelper2.Entropy = ENCRYPTION_VALID_PASSWORD;
            string decriptedString = crytographyHelper2.Decrypt(encryptedString, StringEncodingType.Hex);

            Assert.AreEqual(ENCRYPTION_TEST_STRING, decriptedString);
        }
Пример #18
0
        protected override TCPPacketConnection InitializeConnection(Socket connectedSocket)
        {
            TCPPacketConnection connection = new TCPPacketConnection(connectedSocket);

            connection.Logger = Logger;

            Logger.Log(LogLevel.Information, MessageInitiatingHandshake);
            if (!connection.InitializeCrypto(CryptoFactory.CreateCrypto(Crypto, true), TimeoutCryptoHandshake))
            {
                throw new ConnectException(MessageHandshakeFailed);
            }

            return(connection);
        }
Пример #19
0
        /// <summary>
        /// 获取公钥 私钥
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGenerateKeyPair_Click(object sender, EventArgs e)
        {
            btnGenerateKeyPair.Enabled = false;
            try
            {
                if (cmbProviderType.Text == "对称加密")
                {
                    var symmetricProviderType = cmbEncryptType.Text.Split('-')[0];
                    var symmetricProvider     = CryptoFactory.CreateSymmetric(symmetricProviderType);

                    var keypair = symmetricProvider.CreateKey();

                    txtSecretKey.Text = keypair.Key;
                    if (txtprivateKey.Enabled)
                    {
                        txtprivateKey.Text = keypair.IV;
                    }
                    else
                    {
                        txtprivateKey.Text = "";
                    }
                }
                else if (cmbProviderType.Text == "哈希加密")
                {
                    if (cmbEncryptType.Text.StartsWith("HMAC"))
                    {
                        txtSecretKey.Text = Vive.Crypto.Core.Internals.RandomStringGenerator.Generate(32);
                    }
                    else
                    {
                        txtSecretKey.Text = "";
                    }
                    txtprivateKey.Text = "";
                }
                else //非对称加密
                {
                    var asymmetricProviderType = cmbEncryptType.Text;
                    var asymmetricProvide      = CryptoFactory.CreateAsymmetric(asymmetricProviderType);
                    var keypair = asymmetricProvide.CreateKey();

                    txtSecretKey.Text  = keypair.PublickKey;
                    txtprivateKey.Text = keypair.PrivateKey;
                }

                saveData();
            }
            catch (Exception ex) { txtResponse.Text = ex.ToString(); }
            btnGenerateKeyPair.Enabled = true;
        }
        public void TestEmptyPasswordConfig()
        {
            var config = new CryptoConfig
            {
                IsEncryptActive = true,
                CipherAlgorithm = CipherAlgorithm.AES,
                KeySize         = 256,
                PbeDigest       = PbeDigest.GCM,
                BlockMode       = BlockMode.GCM,
                IsPbeActive     = true
            };

            Assert.Throws <ArgumentException>(
                () => CryptoFactory.CreatePbe(config));
        }
Пример #21
0
        public void TestInvalidCtsInput()
        {
            var config = new CryptoConfig
            {
                IsEncryptActive = true,
                BlockMode       = BlockMode.CTS,
                CipherAlgorithm = CipherAlgorithm.AES,
                KeySize         = 128,
                Padding         = Padding.Pkcs7
            };

            var cipherBuilder = CryptoFactory.CreateCipher(config);

            Assert.Throws <Org.BouncyCastle.Crypto.DataLengthException>(
                () => cipherBuilder.EncryptTextToBytes("Hallo Welt"));
        }
        public void TestMissingPrivateKeyDsa256()
        {
            var config = new CryptoConfig
            {
                IsIntegrityActive = true,
                Integrity         = Integrity.Dsa,
                IntegrityOptions  = IntegrityOptions.Sha256
            };

            var certBuilder  = CryptoFactory.CreateCert(config);
            var bytes        = Encoding.UTF8.GetBytes("Hallo Welt");
            var base64String = Convert.ToBase64String(bytes);

            Assert.Throws <ArgumentException>(
                () => certBuilder.SignInput(base64String));
        }
Пример #23
0
    public static Aes ReadMetadataAndInitializeAlgorithm(Stream inputStream, string password)
    {
        byte[] iv;

        using (BinaryReader br = new BinaryReader(inputStream, Encoding.UTF8, true)) {
            int ivLength = br.ReadInt32();
            iv = new byte[ivLength];

            int readBytes = br.Read(iv, 0, iv.Length);
            if (readBytes != iv.Length)
            {
                throw new InvalidDataException($"Unable to read IV: expected to read {iv.Length} bytes, but got {readBytes}");
            }
        }

        return(CryptoFactory.CreateCrypto(password, iv));
    }
Пример #24
0
        /// <summary>
        /// Triggers processing of CryptoConfig object.
        /// Passes Config object to processing class constructors.
        /// Also verifies integrity of cipher if used.
        /// </summary>
        /// <param name="config">config state after loading all files from disk.</param>
        /// <returns>decrypted cipher in string representation.</returns>
        public static string ProcessConfigOnLoad(CryptoConfig config)
        {
            if (config.IsIntegrityActive)
            {
                if (config.Integrity == Integrity.Dsa)
                {
                    var certBuilder = CryptoFactory.CreateCert(config);
                    certBuilder.GenerateCerts();
                    config = certBuilder.SignInput(config.Cipher);

                    var result = certBuilder.VerifySign(config.Signature, config.Cipher);
                    Console.WriteLine($"Signature verified: {result}");
                }
                else
                {
                    var certBuilder = CryptoFactory.CreateDigest(config);
                    config = certBuilder.SignInput(config.Cipher);

                    var result = certBuilder.VerifySign(config.Signature, config.Cipher);
                    Console.WriteLine($"Digest verified: {result}");
                }
            }

            if (config.IsPbeActive)
            {
                var pbeBuilder = CryptoFactory.CreatePbe(config);
                config = pbeBuilder.GenerateKeyBytes();
            }

            var cipherBuilder = CryptoFactory.CreateCipher(config);

            try
            {
                return(cipherBuilder.DecryptBytesToText(Convert.FromBase64String(config.Cipher)));
            }
            catch (Org.BouncyCastle.Crypto.InvalidCipherTextException e)
            {
                Console.WriteLine(e);
                return("GCM mac error.");
            }
            catch (FormatException e)
            {
                Console.WriteLine(e);
                return("Format error.");
            }
        }
Пример #25
0
        public void TestValidRc4Cipher()
        {
            var config = new CryptoConfig
            {
                IsEncryptActive = true,
                CipherAlgorithm = CipherAlgorithm.RC4,
                KeySize         = 2048
            };

            var cipherBuilder = CryptoFactory.CreateCipher(config);

            config = cipherBuilder.EncryptTextToBytes("Hallo Welt");
            var decodedCipher = Convert.FromBase64String(config.Cipher);

            var result = cipherBuilder.DecryptBytesToText(decodedCipher);

            Assert.Equal("Hallo Welt", result);
        }
Пример #26
0
        private string CreateUserToken(AppUser appUser)
        {
            var claims = new List <Claim>
            {
                new Claim(nameof(AppUserClaimModel.Id), CryptoFactory.Encrypt(_appOptions.GoogleClientSecret, appUser.Id)),
                new Claim(nameof(AppUserClaimModel.EmailAddress), appUser.EmailAddress),
                new Claim(nameof(AppUserClaimModel.FirstName), appUser.FirstName),
                new Claim(nameof(AppUserClaimModel.LastName), appUser.LastName),
                new Claim(nameof(AppUserClaimModel.IsAdmin), appUser.IsAdmin.ToString())
            };

            var key         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appOptions.GoogleClientSecret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(null, null, claims, null, _dateTimeService.GetTokenExpireTime(1), credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Пример #27
0
 public void WriteString(string data, bool withEncrypt = false, string algorithm = "AES", string password = "******")
 {
     using (FileStream fs = new FileStream(this.FileName, FileMode.OpenOrCreate, FileAccess.Write))
         using (StreamWriter swr = new StreamWriter(fs))
         {
             if (withEncrypt)
             {
                 Symmetric sym = new Symmetric(CryptoFactory.GetSymmetricInstance(algorithm, password));
                 swr.Write(sym.EncryptString(data));
                 swr.Flush();
             }
             else
             {
                 swr.Write(data);
                 swr.Flush();
             }
         }
 }
        public void TestValidAesCmac()
        {
            var config = new CryptoConfig
            {
                IsIntegrityActive = true,
                Integrity         = Integrity.Digest,
                IntegrityOptions  = IntegrityOptions.AesCmac
            };

            var cipherBuilder = CryptoFactory.CreateDigest(config);
            var bytes         = Encoding.UTF8.GetBytes("Hallo Welt");
            var base64String  = Convert.ToBase64String(bytes);

            config = cipherBuilder.SignInput(base64String);

            var result = cipherBuilder.VerifySign(config.Signature, base64String);

            Assert.True(result);
        }
Пример #29
0
        public void ResetPassword(UserModel model)
        {
            if (model.UserPassword.StartsWith("{ENC}"))
            {
                throw new Exception("password must in plain text");
            }
            var password = CryptoFactory.Encrypt(model.UserPassword);

            model = (UserModel)Find(model, "UserName");
            model.UserPassword       = password;
            model.LastChangePassword = DateTime.Now;
            Save(model);

            CntrlAU.RegisterEvent(new AuditModel()
            {
                UserName      = model.UserName,
                EventComments = "password reset for user : " + model.UserName
            });
        }
Пример #30
0
        public string ReadString(bool withEncrypt = false, string algorithm = "AES", string password = "******")
        {
            string data = "";

            using (FileStream fs = new FileStream(this.FileName, FileMode.Open, FileAccess.Read))
                using (StreamReader srd = new StreamReader(fs))
                {
                    if (withEncrypt)
                    {
                        Symmetric sym = new Symmetric(CryptoFactory.GetSymmetricInstance(algorithm, password));
                        data = sym.DecryptString(srd.ReadToEnd());
                    }
                    else
                    {
                        data = srd.ReadToEnd();
                    }
                }
            return(data);
        }