Пример #1
0
    /// <summary>
    /// 创建随机秘钥
    /// </summary>
    /// <returns></returns>
    public static byte[] CreateKey()
    {
        DESCryptoServiceProvider desP = new DESCryptoServiceProvider();

        desP.GenerateKey();
        return(desP.Key);
    }
Пример #2
0
        string DESEncrypt(string data)
        {
            des.GenerateKey();
            des.GenerateIV();
            des.Padding = PaddingMode.Zeros;
            des.Mode    = CipherMode.CBC;
            string key = Encoding.Default.GetString(des.Key);
            string IV  = Encoding.Default.GetString(des.IV);


            ///??????
            rsa = (RSACryptoServiceProvider)certifikata.PublicKey.Key;
            //?????????


            byte[] byteKey      = rsa.Encrypt(des.Key, true);
            string encryptedKey = Convert.ToBase64String(byteKey);

            byte[] bytePlaintexti = Encoding.ASCII.GetBytes(data);


            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(bytePlaintexti, 0, bytePlaintexti.Length);
            cs.Close();

            byte[] byteCiphertexti = ms.ToArray();

            return(IV + "*" + encryptedKey + "*" + Convert.ToBase64String(byteCiphertexti));
        }
Пример #3
0
        /// <summary>
        /// 授权编码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        internal static String Encode(String text)
        {
            String xml = text;

#if ISMANAGE
            //签名。XCode生成的Lic文件不包含签名,防止私钥泄露
            xml += "$" + License.Sign(Encoding.UTF8.GetBytes(xml), PrivateKey);
#else
            xml += "$";
#endif
            //DES加密
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            //IV的明文
            String key = "mama shuo wo zhang da le";
            //加密IV
            des.GenerateIV();
            String iv = Convert.ToBase64String(Encrypt(des.IV, key));
            //生成一个Key
            des.GenerateKey();
            key = Convert.ToBase64String(des.Key);
            key = key + "|" + iv;
            //DES加密
            xml  = Encrypt(xml, key);
            xml += "@" + key;
            //RC4加密
            Byte[] bts = Encrypt(Encoding.UTF8.GetBytes(xml), InternalKey);
            return(Convert.ToBase64String(bts));
        }
Пример #4
0
Файл: test.cs Проект: mono/gert
	static int Main ()
	{
		string filename = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"encrypt.tmp");
		string data = "this is sensitive data";

		DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
		des.GenerateIV ();
		des.GenerateKey ();

		// -----------  WRITING ENCRYPTED SERIALIZED DATA ------------------
		Stream stream = new FileStream (filename, FileMode.Create, FileAccess.Write);
		stream = new CryptoStream (stream, des.CreateEncryptor (), CryptoStreamMode.Write);
		BinaryFormatter bformatter = new BinaryFormatter ();
		bformatter.Serialize (stream, data);
		stream.Close ();

		stream = null;
		bformatter = null;
		data = string.Empty;

		// -----------  READING ENCRYPTED SERIALIZED DATA ------------------
		stream = new FileStream (filename, FileMode.Open, FileAccess.Read);
		stream = new CryptoStream (stream, des.CreateDecryptor (), CryptoStreamMode.Read);
		bformatter = new BinaryFormatter ();
		data = (string) bformatter.Deserialize (stream);
		stream.Close ();

		//----------- CHECK RESULTS ----------------
		if (data != "this is sensitive data")
			return 1;

		return 0;
	}
Пример #5
0
 public DES()
 {
     desObj.GenerateKey();
     desObj.GenerateIV();
     desObj.Padding = PaddingMode.Zeros;
     desObj.Mode    = CipherMode.CBC;
 }
Пример #6
0
        static List <Triplet> GenerateDESDataset(int samples, int keySize = 64, int msgSize = 64)
        {
            Random rand = new Random();
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.KeySize = keySize;

            List <Triplet> triplets = new List <Triplet>(samples);

            for (int i = 0; i < samples; i++)
            {
                des.GenerateKey();
                byte[] key      = des.Key; // save this!
                byte[] original = new byte[msgSize];
                rand.NextBytes(original);
                ICryptoTransform encryptor = des.CreateEncryptor();
                byte[]           encrypted = encryptor.TransformFinalBlock(original, 0, msgSize);

                //ICryptoTransform decryptor = des.CreateDecryptor();
                //byte[] originalAgain = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);

                Triplet triplet = new Triplet(original, encrypted, key);
                triplets.Add(triplet);


                //string msg = "Original = " + System.Text.Encoding.UTF8.GetString(original) + '\n';
                //msg += "Encrypted = " + System.Text.Encoding.UTF8.GetString(encrypted) + '\n';
                //msg += "Key = " + System.Text.Encoding.UTF8.GetString(key) + '\n';
                //Console.WriteLine(msg);
                //Console.WriteLine(triplet.GetBytesForm());
            }
            return(triplets);
        }
Пример #7
0
        private string encrypt(string plaintext)
        {
            objDes.GenerateKey();
            objDes.GenerateIV();
            objDes.Padding = PaddingMode.Zeros;
            objDes.Mode    = CipherMode.CBC;
            string key = Encoding.Default.GetString(objDes.Key);
            string IV  = Encoding.Default.GetString(objDes.IV);


            objRsa = (RSACryptoServiceProvider)certifikata.PublicKey.Key;
            byte[] byteKey      = objRsa.Encrypt(objDes.Key, true);
            string encryptedKey = Convert.ToBase64String(byteKey);

            byte[] bytePlaintexti = Encoding.UTF8.GetBytes(plaintext);


            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, objDes.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(bytePlaintexti, 0, bytePlaintexti.Length);
            cs.Close();

            byte[] byteCiphertexti = ms.ToArray();

            return(IV + "." + encryptedKey + "." + Convert.ToBase64String(byteCiphertexti));
        }
Пример #8
0
    /// <summary>
    /// This function acts as a test for the mechanism by send a message hello and verifying its receiver and printing the message
    /// </summary>
    public static void TestRun()
    {
        RSAParameters parameters;

        RSAParameters publicParameters;

        RSACryptoServiceProvider encrypt = new RSACryptoServiceProvider(RSA_SIZE);

        parameters       = encrypt.ExportParameters(true);
        publicParameters = encrypt.ExportParameters(false);

        DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();

        dESCryptoServiceProvider.GenerateKey();
        dESCryptoServiceProvider.GenerateIV();

        string key = Convert.ToBase64String(dESCryptoServiceProvider.Key);
        string IV  = Convert.ToBase64String(dESCryptoServiceProvider.IV);

        string msg = GenerateMessage("Hello", parameters, key, IV);

        WriteLine("Encrypted message to be sent : " + msg);

        if (ReproduceMessage(msg, out msg, parameters, key, IV))
        {
            WriteLine("Successfully verified message with sender and message received is  : " + msg);
        }
        else
        {
            WriteLine("Failed to verify sender identity");
        }
    }
Пример #9
0
        private void btnGenerateKey_Click(object sender, EventArgs e)
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

            desCrypto.GenerateKey();
            tbKey.Text = Convert.ToBase64String(desCrypto.Key);
        }
Пример #10
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="input"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string Encrypt(string input, out string key, out string iv)
        {
            key = "";
            iv  = "";
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            byte[] bytes = Encoding.Default.GetBytes(input);
            provider.GenerateIV();
            provider.GenerateKey();
            iv  = new UnicodeEncoding().GetString(provider.IV);
            key = new UnicodeEncoding().GetString(provider.Key);
            MemoryStream stream  = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder sb     = new StringBuilder();
            var           sarray = stream.ToArray();

            foreach (var item in sarray)
            {
                sb.AppendFormat("{0:X2}", item);
            }
            stream.Close();
            stream2.Close();
            return(sb.ToString());
        }
Пример #11
0
        /// <summary>
        /// 生成随机密匙
        /// </summary>
        /// <returns></returns>
        public static byte[] GenDesKey()
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.GenerateKey();
            return(des.Key);
        }
Пример #12
0
        } //compute hash from arguments and return hash value as string

        private static string GetDESHash(string text)
        {
            //create variables for computing hash and making it a string
            UnicodeEncoding UniCode = new UnicodeEncoding();

            byte[] HashResult;
            byte[] msg        = UniCode.GetBytes(text);
            DES    hashString = new DESCryptoServiceProvider();

            //generate a weak KEY and Initialization Vector for the hash algorithm
            hashString.GenerateKey();
            hashString.GenerateIV();
            ICryptoTransform encryptor = hashString.CreateEncryptor(hashString.Key, hashString.IV);
            string           Str       = "";

            //compute hash with DES module and format output as string
            //convert bytes in HashResult to string values
            HashResult = encryptor.TransformFinalBlock(msg, 0, msg.Length);
            foreach (byte x in HashResult)
            {
                Str += String.Format("{0:x2}", x);
            }

            //clear excess resource usage
            hashString.Clear();
            return(Str);
        } //compute hash from arguments and return hash value as string
        /// <summary>
        /// Event that fires when the des encrypt button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDESEncrypt_Click(object sender, RoutedEventArgs e)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.KeySize = ((ListItem)this.cboDESKeySize.SelectedItem).Value;
            des.Mode    = (CipherMode)((ListItem)this.cboDESMode.SelectedItem).Value;
            des.Padding = (PaddingMode)((ListItem)this.cboDESPadding.SelectedItem).Value;
            //des.BlockSize = ;

            des.GenerateIV();
            this.txtDESIV.Text = Convert.ToBase64String(des.IV);

            //generate the key and insert it into the text box
            des.GenerateKey();
            this.txtDESPassword.Text = Convert.ToBase64String(des.Key);

            byte[] byteInputText = encoding.GetBytes(this.txtDESInput.Text);

            byte[] cipherText;
            using (ICryptoTransform crypto = des.CreateEncryptor())
            {
                cipherText = crypto.TransformFinalBlock(byteInputText, 0, byteInputText.Length - 1);
                des.Clear();
            }

            this.txtDESOutput.Text = Convert.ToBase64String(cipherText);
        }
Пример #14
0
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string Encrypt(string Text, out string key, out string iv)
        {
            key = "";
            iv  = "";
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.GenerateIV();
            des.GenerateKey();
            iv  = new UnicodeEncoding().GetString(des.IV);
            key = new UnicodeEncoding().GetString(des.Key);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream           cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();

            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return(ret.ToString());
        }
Пример #15
0
        static void Main(string[] args)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.GenerateKey();
            des.GenerateIV();
            WriteKeyAndIV(des);
            ICryptoTransform encryptor = des.CreateEncryptor();

            FileStream inFile  = new FileStream(@"Bloops.txt", FileMode.Open);
            FileStream outFile = new FileStream(@"BloopsEnc.txt", FileMode.Create);
            int        inSize  = encryptor.InputBlockSize;
            int        outSize = encryptor.OutputBlockSize;

            byte [] inBytes = new byte[inSize];
            byte [] outBytes = new byte[outSize];
            int     numBytesRead, numBytesOutput;

            do
            {
                numBytesRead = inFile.Read(inBytes, 0, inSize);
                if (numBytesRead == inSize)
                {
                    numBytesOutput = encryptor.TransformBlock(inBytes, 0, numBytesRead, outBytes, 0);
                    outFile.Write(outBytes, 0, numBytesOutput);
                }
                else if (numBytesRead > 0)
                {
                    byte [] final = encryptor.TransformFinalBlock(inBytes, 0, numBytesRead);
                    outFile.Write(final, 0, final.Length);
                }
            } while (numBytesRead > 0);
            inFile.Close();
            outFile.Close();
        }
Пример #16
0
        /// <summary>
        /// 获取加密和解密时用的key和iv
        /// </summary>
        /// <param name="providerType">算法类型</param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        public static void GenerateCryptKeyAndIV(CryptProviderType providerType, out byte[] key, out byte[] iv)
        {
            key = null;
            iv  = null;
            switch (providerType)
            {
            case CryptProviderType.AES:
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                aes.GenerateKey();
                aes.GenerateIV();
                key = aes.Key;
                iv  = aes.IV;
                return;

            case CryptProviderType.DES:
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.GenerateKey();
                des.GenerateIV();
                key = des.Key;
                iv  = des.IV;
                return;

            case CryptProviderType.TripleDES:
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.GenerateKey();
                tdes.GenerateIV();
                key = tdes.Key;
                iv  = tdes.IV;
                return;

            default:
                return;
            }
        }
Пример #17
0
        /// <summary>
        /// Generate new encryption key
        /// </summary>
        /// <param name="algId"></param>
        /// <returns></returns>
        public string GenerateKey(EncryptionAlgorithm algId)
        {
            byte[] NewKey = null;

            // Pick the provider.
            switch (algId)
            {
            case EncryptionAlgorithm.Des:
            {
                DES des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                des.GenerateKey();
                NewKey = des.Key;
                des    = null;
                break;
            }

            case EncryptionAlgorithm.TripleDes:
            {
                TripleDES des3 = new TripleDESCryptoServiceProvider();
                des3.Mode = CipherMode.CBC;
                des3.GenerateKey();
                NewKey = des3.Key;
                des3   = null;
                break;
            }

            case EncryptionAlgorithm.Rc2:
            {
                RC2 rc2 = new RC2CryptoServiceProvider();
                rc2.Mode = CipherMode.CBC;
                rc2.GenerateKey();
                NewKey = rc2.Key;
                rc2    = null;
                break;
            }

            case EncryptionAlgorithm.Rijndael:
            {
                Rijndael rijndael = new RijndaelManaged();
                rijndael.Mode      = CipherMode.CBC;
                rijndael.Padding   = PaddingMode.PKCS7;
                rijndael.KeySize   = 256;
                rijndael.BlockSize = 256;
                rijndael.GenerateKey();
                NewKey   = rijndael.Key;
                rijndael = null;
                break;
            }

            default:
            {
                throw new CryptographicException("Algorithm ID '" + algId +
                                                 "' not supported.");
            }
            }

            return(Encoding.ASCII.GetString(NewKey));
        }
Пример #18
0
        static void Main(string[] args)
        {
            // Исходная строка
            string source_str = "It is string!";

            Console.WriteLine(source_str);


            // Получаем из строки набор байт, которые будем шифровать
            byte[] source_data = Encoding.UTF8.GetBytes(source_str);

            DES des = new DESCryptoServiceProvider();

            // Генерируем IV и Key
            des.GenerateIV();
            des.GenerateKey();

            // Сохраняем ключи
            byte[] IVByteArray  = des.IV;
            byte[] KeyByteArray = des.Key;


            // Поток выходных данных
            MemoryStream ms_in = new MemoryStream();
            // Шифрованный поток
            CryptoStream cs_in =
                new CryptoStream(ms_in,
                                 des.CreateEncryptor(KeyByteArray,
                                                     IVByteArray),
                                 CryptoStreamMode.Write);

            cs_in.Write(source_data, 0, source_data.Length);
            cs_in.Close();
            // Получаем зашифрованную строку
            string crypt_str = Convert.ToBase64String(ms_in.ToArray());

            // Выводим зашифрованную строку
            Console.WriteLine(crypt_str);


            // Получаем массив байт
            byte[] crypt_data = Convert.FromBase64String(crypt_str);
            // Поток выходных данных
            MemoryStream ms_out = new MemoryStream(crypt_data);
            // Поток для расшифровки
            CryptoStream cs_out =
                new CryptoStream(ms_out,
                                 des.CreateDecryptor(KeyByteArray,
                                                     IVByteArray),
                                 CryptoStreamMode.Read);
            // Читаем выходную строку
            StreamReader sr_out     = new StreamReader(cs_out);
            string       source_out = sr_out.ReadToEnd();

            // Выводим расшифрованную строку
            Console.WriteLine(source_out);

            Console.ReadLine();
        }
Пример #19
0
 /// <summary>
 /// 创建key
 /// </summary>
 /// <returns></returns>
 public static string GenerateKey()
 {
     using (var des = new DESCryptoServiceProvider())
     {
         des.GenerateKey();
         return(Encoding.ASCII.GetString(des.Key));
     }
 }
Пример #20
0
 private static void createDes()
 {
     objDes = new DESCryptoServiceProvider();
     objDes.GenerateIV();
     objDes.Padding = PaddingMode.Zeros;
     objDes.Mode    = CipherMode.CBC;
     objDes.GenerateKey();
 }
Пример #21
0
 /// <summary>
 /// DES算法构造函数(KEY和IV随机生成)
 /// </summary>
 public DES()
 {
     des = new DESCryptoServiceProvider();
     des.GenerateKey();
     des.GenerateIV();
     Key = Convert.ToBase64String(des.Key);
     IV  = Convert.ToBase64String(des.IV);
 }
Пример #22
0
    public void getKeys()
    {
        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

        provider.GenerateIV();
        provider.GenerateKey();
        Key1 = Convert.ToBase64String(provider.Key);
        Key2 = Convert.ToBase64String(provider.IV);
    }
        /// <summary>
        /// 生成随机的Key和初始化向量
        /// </summary>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        public static void GenerateKeyIV(out string key, out string iv)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.GenerateKey();
            des.GenerateIV();
            key = Encoding.UTF8.GetString(des.Key);
            iv  = Encoding.UTF8.GetString(des.IV);
        }
Пример #24
0
 TripleDESKeyGeneratorApp()
 {
     provider         = new DESCryptoServiceProvider();
     provider.KeySize = 64;
     provider.GenerateIV();
     provider.GenerateKey();
     provider.Mode    = CipherMode.CBC;
     provider.Padding = PaddingMode.ISO10126;
 }
Пример #25
0
        public void GenerateKey(EncoderType type)
        {
            switch (type)
            {
            case EncoderType.AES:
                using (AesCryptoServiceProvider csp = new AesCryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.DES:
                using (DESCryptoServiceProvider csp = new DESCryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.RC2:
                using (RC2CryptoServiceProvider csp = new RC2CryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.TripleDES:
                using (TripleDESCryptoServiceProvider csp = new TripleDESCryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.RSA:
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    IV  = "";
                    Key = csp.ToXmlString(true);
                }
                break;

            default:
                break;
            }
        }
Пример #26
0
 public void GenerateKey(out string key, out string iv)
 {
     key = "";
     iv  = "";
     using (DESCryptoServiceProvider des_o = new DESCryptoServiceProvider())
     {
         des_o.GenerateIV();
         des_o.GenerateKey();
         iv  = Convert.ToBase64String(des_o.IV);
         key = Convert.ToBase64String(des_o.Key);
     }
 }
Пример #27
0
        /// <summary>
        /// Initilaizes an instance of the DESCryptography class.
        /// </summary>
        private DESCryptography()
        {
            Id = new Random().Next();

            _DES         = new DESCryptoServiceProvider();
            _DES.Padding = PaddingMode.PKCS7;
            _DES.Mode    = CipherMode.ECB;
            _DES.GenerateKey();

            _encryptor = _DES.CreateEncryptor();
            _decryptor = _DES.CreateDecryptor();
        }
Пример #28
0
        /// <summary> 创建类的实例,并随机创建一对密匙和向量 </summary>
        public DESCrypto()
        {
            // 每次创建加密示例,创建一个密码和向量。
            DES des = new DESCryptoServiceProvider();

            des.GenerateKey();
            des.GenerateIV();
            deskey = des.Key;
            desiv  = des.IV;
            des.Clear();
            des = null;
        }
Пример #29
0
        public static (string Key, string IV) Generate()
        {
            var provider = new DESCryptoServiceProvider();

            provider.GenerateKey();
            provider.GenerateIV();

            return(
                Key : Convert.ToBase64String(provider.Key),
                IV : Convert.ToBase64String(provider.IV)
                );
        }
Пример #30
0
        public IActionResult HandleGet([FromUri] VulnQuery query)
        {
            var ret           = new List <string>();
            var ACCESS_KEY_ID = "AKIA2E0A8F3B244C9986";
            var SECRET_KEY    = "7CE556A3BC234CC1FF9E8A5C324C0BB70AA21B6D";

            var login      = query.Login;
            var password   = query.Password;
            var keeponline = query.Keeponline != null;


            var sql = new SQLiteCommand("SELECT * FROM USER WHERE login = '******' AND PASSWORD = '******'",
                                        DatabaseUtils._con);

            var reader = sql.ExecuteReader();

            if (reader.Read())
            {
                var user = new User(
                    reader["fname"].ToString(),
                    reader["lname"].ToString(),
                    reader["passportnum"].ToString(),
                    reader["address1"].ToString(),
                    reader["address2"].ToString(),
                    reader["zipcode"].ToString());

                var option = new CookieOptions();
                option.MaxAge = TimeSpan.Parse("864000");
                option.Path   = "/";
                Response.Cookies.Append("login", login, option);

                Logger.Info($"User {user} successfully logged in");


                var provider = new DESCryptoServiceProvider();
                provider.GenerateKey();
                provider.GenerateIV();

                var creditinfo = reader["creditinfo"].ToString();
                EncryptString(provider, creditinfo);

                var msg = $"User {user} credit info is {creditinfo}";
                ret.Append(msg);
                Logger.Info(msg);

                return(LocalRedirect("fwd"));
            }

            Logger.Info($"User {login} failed to sign in");
            return(new JsonResult($"User {login} failed to sign in"));
        }
Пример #31
0
        public static NCryptoParms EncryptCode(string decData, string spKey)
        {
            NCryptoParms     parms = new NCryptoParms();
            ICryptoTransform encryptor;
            CryptoStream     cStream;
            MemoryStream     mStream = new MemoryStream();

            try {
                // Generate a new RSA public/private key pair
                // This key will be used to signature the DES IV and Key.
                RSACryptoServiceProvider jRsa = new RSACryptoServiceProvider();

                byte[] signature = jRsa.SignData(sign, new MD5CryptoServiceProvider());

                parms.jpbkey =
                    Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(false)));
                parms.jprkey =
                    Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(true)));
                parms.signature = Convert.ToBase64String(signature);
                jRsa.Clear();

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(
                    Encoding.ASCII.GetString(Convert.FromBase64String(spKey)));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.GenerateIV();
                des.GenerateKey();

                parms.key = Convert.ToBase64String(rsa.Encrypt(des.Key, false));
                parms.iv  = Convert.ToBase64String(rsa.Encrypt(des.IV, false));

                encryptor = des.CreateEncryptor(des.Key, des.IV);
                cStream   = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write);

                byte[] bytesIn = Encoding.ASCII.GetBytes(decData);

                cStream.Write(bytesIn, 0, bytesIn.Length);
                cStream.FlushFinalBlock();
                cStream.Close();

                byte[] bytesOut = mStream.ToArray();
                mStream.Close();

                parms.enc = Convert.ToBase64String(bytesOut);
            } catch {
                mStream.Close();
            }
            return(parms);
        }
    static Boolean Test()
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7}; //, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 1};
        Byte[]  IV = {1, 1, 1, 1, 1, 1, 1, 1};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
		des.Padding = PaddingMode.PKCS7;


		
		int depth = 10;


        Stream[] encStream_arr = new Stream[depth];
        Stream[] decStream_arr = new Stream[depth];
        ICryptoTransform[] decTrans_array = new ICryptoTransform[depth];

        encStream_arr[0] = new MemoryStream();
        decStream_arr[0] = new MemoryStream();

        for (int i=1; i<depth; i++) {
            des.GenerateKey();
            des.GenerateIV();
            encStream_arr[i] = new CryptoStream(encStream_arr[i-1],des.CreateEncryptor(),CryptoStreamMode.Write);
            decTrans_array[i] = des.CreateDecryptor();
        }

        for (int j=1; j<depth; j++) {
            decStream_arr[j] = new CryptoStream(decStream_arr[j-1],decTrans_array[depth-j],CryptoStreamMode.Write);
        }


        Console.WriteLine("DES default key size = " + des.KeySize);
        Console.WriteLine("SSE mode = " + des.Mode);

        encStream_arr[depth-1].Write(PlainText,0,PlainText.Length);
        ((CryptoStream)encStream_arr[depth-1]).FlushFinalBlock();
        byte[] CipherText = ((MemoryStream)encStream_arr[0]).ToArray();
        encStream_arr[depth-1].Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

        Console.WriteLine("SSD mode = " + des.Mode);

        decStream_arr[depth-1].Write(CipherText,0,CipherText.Length);
        ((CryptoStream)decStream_arr[depth-1]).FlushFinalBlock();
        byte[] NewPlainText = ((MemoryStream)decStream_arr[0]).ToArray();
        decStream_arr[depth-1].Close();

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }