GetBytes() private method

private GetBytes ( char chars, int charCount, byte bytes, int byteCount ) : int
chars char
charCount int
bytes byte
byteCount int
return int
Esempio n. 1
0
        public static string DecryptStringWith3DES(string data, string key, string iv)
        {
            UnicodeEncoding unicode = new UnicodeEncoding();
            Byte[] Bytes = Convert.FromBase64String(data);

            MemoryStream mem = new MemoryStream(100);
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            Byte[] KeyBytes = unicode.GetBytes(key);
            Byte[] tmpBytes = new Byte[16];
            Array.Copy(KeyBytes, tmpBytes, KeyBytes.Length < 16 ? KeyBytes.Length : 16);
            KeyBytes = tmpBytes;

            if(tdes.ValidKeySize(KeyBytes.Length*8))
                System.Diagnostics.Debug.WriteLine("Key size valid");
            if(TripleDESCryptoServiceProvider.IsWeakKey(KeyBytes))
                System.Diagnostics.Debug.WriteLine("Key weak");
            CryptoStream CrStream = new CryptoStream(mem, tdes.CreateDecryptor(KeyBytes, unicode.GetBytes(iv)), CryptoStreamMode.Write);

            for(int i = 0; i < Bytes.Length; i++)
                CrStream.WriteByte(Bytes[i]);

            CrStream.FlushFinalBlock();

            string result = unicode.GetString(mem.GetBuffer(), 0, (int)mem.Length);
            CrStream.Dispose();
            return result;
        }
Esempio n. 2
0
        string password_crypt(string password, string setting)
        {
            string _setting = setting.Substring(0, 12);
            if (_setting[0] != '$' || _setting[2] != '$')
                return null;

            int count_log2 = password_get_count_log2(setting);
            string salt = _setting.Substring(4, 8);
            if (salt.Length < 8)
                return null;
            int count = 1 << count_log2;
            SHA512 shaM = new SHA512Managed();
            Encoding unicode = new UnicodeEncoding(true, false);
            byte[] data = unicode.GetBytes(salt + password);
            byte[] pass = unicode.GetBytes(password);
            byte[] hash = shaM.ComputeHash(data);
            for (int c = 0; c < count; c++)
            {
                data = new byte[hash.Length + pass.Length];
                hash.CopyTo(data, 0);
                pass.CopyTo(data, hash.Length);
                hash = shaM.ComputeHash(data);
            }
            string output = setting + custom64(hash);
            return output.Substring(0, hash_length);
        }
Esempio n. 3
0
        public static string hashPassword(string password, string salt)
        {
            System.Text.UnicodeEncoding ue = new UnicodeEncoding();
            byte[] uePassword = ue.GetBytes(password);
            byte[] retVal = null;

            HMACSHA1 SHA1KeyedHasher = new HMACSHA1();
            SHA1KeyedHasher.Key = ue.GetBytes(salt);
            retVal = SHA1KeyedHasher.ComputeHash(uePassword);

            return Convert.ToBase64String(retVal);
        }
Esempio n. 4
0
 public static string Sha1(this string input)
 {
     var provider = new SHA1CryptoServiceProvider();
     var encoding = new UnicodeEncoding();
     var bytehash = provider.ComputeHash(encoding.GetBytes(input));
     return Convert.ToBase64String(bytehash);
 }
Esempio n. 5
0
        static void Main(string[] args)
        {
            Stopwatch start = Stopwatch.StartNew();
            FileStream fs;
            UnicodeEncoding uni = new UnicodeEncoding();
            //string stime = "";
            fs = new FileStream("./solution3.log", FileMode.Create);

            // for (int j = 1; j <= 50; j++)
            // {
            //int totalReset = 0;
            for (int i = 0; i < 50; i++)
            {
                start.Restart();
                Solver s = new Solver(3, @"C:\ULAVAL\IFT-4102\TP1\Question2\sudoku\base.txt", 810, 0.5, 0.8);
                string solution = s.Solve();
                //totalReset += reset;
                start.Stop();
                string stime = "Temps : " + start.ElapsedMilliseconds + "ms" + Environment.NewLine + solution + Environment.NewLine;
                Console.Write(stime);// + solution );
                fs.Write(uni.GetBytes(stime), 0, uni.GetByteCount(stime));
                // }
                // long total = start.ElapsedMilliseconds;
                // string timeTotal = total + "ms";
                // string timeMoyen = (total / 20.0) + "ms";
                // //stime = "With comparaison : " + (1 - 0.02 * j) + " took a total of " + timeTotal + " Moyen : " + timeMoyen + " and moyenReset " + totalReset / 20 + Environment.NewLine;
                // Console.Write(stime);
                //fs.Write(uni.GetBytes(stime), 0, uni.GetByteCount(stime));
            }

        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            try
            {
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                byte[] dataToEncrypt = ByteConverter.GetBytes("bbbbbbbb");
                byte[] encryptedData;
                byte[] decryptedData;
                char result;
                using(RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);
                    foreach (byte number in encryptedData)
                    {
                        result = Convert.ToChar(number);
                        Console.WriteLine($"number: {number} convert: {result}");
                    }
                    Console.WriteLine($"tam> {encryptedData.Length}");
                    decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);

                    Console.WriteLine($"1 - {ByteConverter.GetString(decryptedData)}");
                }
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("Encryption failed");
            }

            Console.ReadKey();
        }
Esempio n. 7
0
        public static KeyEncapsulation createKeyEncapsulation(string source, string destination, string keyRSAXml, int n)
        {
            Random random = new Random();
            UnicodeEncoding ByteConverter = new UnicodeEncoding();

            byte[] SessionKey = AESUtils.generateAESKey(GenerateChar(50));

            int nonce = random.Next();
            if (n != 0) { nonce = n; }
            byte[] encryptedKey;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(keyRSAXml);
                encryptedKey = RSAUtils.RSAEncrypt(SessionKey, RSA.ExportParameters(false), true);
            }

            XElement establishConnectionXml = new XElement("EstablishConnection",
                                                new XElement("EncryptedSessionKey", Convert.ToBase64String(encryptedKey)),
                                                new XElement("Nonce", nonce), //FIXME: Está à vista de todos....
                                                new XElement("Source", source),
                                                new XElement("Destination", destination)
                );
            string establishConnectionString = establishConnectionXml.ToString();

            string messageSign = RSAUtils.CreateSignPackage(establishConnectionString, RSAUtils.LoadPrivateKey(source));
            byte[] messageSignBytes = ByteConverter.GetBytes(messageSign);

            return new KeyEncapsulation(messageSignBytes, SessionKey, nonce);
        }
Esempio n. 8
0
File: RSA.cs Progetto: hubro-xx/CRL2
        //RSA加密,随机生成公私钥对并作为出参返回
        public static string RSA_Encrypt(string str_Plain_Text, out string str_Public_Key, out string str_Private_Key)
        {
            str_Public_Key = "";
            str_Private_Key = "";
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] DataToEncrypt = ByteConverter.GetBytes(str_Plain_Text);
            try
            {
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
                str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));

                //OAEP padding is only available on Microsoft Windows XP or later.
                byte[] bytes_Cypher_Text = RSA.Encrypt(DataToEncrypt, false);
                str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
                str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
                string str_Cypher_Text = Convert.ToBase64String(bytes_Cypher_Text);
                return str_Cypher_Text;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            /*
                MD5: MD5CryptoServiceProvider
                RIPEMD-160: RIPEMD160Managed
                SHA: SHA1CryptoServiceProvider e SHA1Managed
                Keyed hash: HMAC e MACTripleDES
            */

            //geração de hash com SHA1
            StreamReader sr = new StreamReader("Arquivo.txt");

            String mensagem = sr.ReadToEnd();

            sr.Close();

            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            UnicodeEncoding ue = new UnicodeEncoding();

            byte[] bytes = ue.GetBytes(mensagem);

            byte[] hash = sha1.ComputeHash(bytes);

            Gravar(hash, sha1.GetType().Name);

            Process.Start("notepad", String.Format("{0}.hash", sha1.GetType().Name));
        }
Esempio n. 10
0
        public static void EncryptSomeText()
        {
            //Init keys
            GeneratePublicAndPrivateKeys();

            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes("My ultra secret message!");

            byte[] encryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(publicKeyXML);
                encryptedData = RSA.Encrypt(dataToEncrypt, false);
            }

            byte[] decryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(privateKeyXML);
                decryptedData = RSA.Decrypt(encryptedData, false);
            }

            string decryptedString = ByteConverter.GetString(decryptedData);
            Console.WriteLine(decryptedString);
        }
Esempio n. 11
0
        private void encryptFile(string inputFile, string cryptFile)
        {
            FileStream fsCrypt = null;
            CryptoStream cryptStream = null;

            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(TPW);
                fsCrypt = new FileStream(cryptFile, FileMode.Create);
                RijndaelManaged RMCrypto = new RijndaelManaged();
                cryptStream = new CryptoStream(fsCrypt,
                                                RMCrypto.CreateEncryptor(key, key),
                                                CryptoStreamMode.Write);

                byte[] inBytes = File.ReadAllBytes(inputFile);
                cryptStream.Write(inBytes, 0, inBytes.Length);

            }
            finally
            {
                if (cryptStream != null)
                    cryptStream.Close();

                if ( fsCrypt != null )
                    fsCrypt.Close();
            }
        }
Esempio n. 12
0
        public static void EncryptFile(string inputFile, string outputFile, string password)
        {
            try
            {
                //string password = @"myKey123"; // Your Key Here
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                string cryptFile = outputFile;
                FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                                                   RMCrypto.CreateEncryptor(key, key),
                                                   CryptoStreamMode.Write);

                FileStream fsIn = new FileStream(inputFile, FileMode.Open);

                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte) data);

                fsIn.Close();
                cs.Close();
                fsCrypt.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encryption failed! {0}", ex);
            }
        }
Esempio n. 13
0
        public void sendNotify(string notify)
        {
            try
            {
                client.Connect(serverName, port);

                stream = client.GetStream();
                UnicodeEncoding encoder = new UnicodeEncoding();
                byte[] buffer = encoder.GetBytes(notify);

                stream.Write(buffer, 0, buffer.Length);

            }
            catch (SocketException ex)
            {
                Trace.TraceError(String.Format("unClientClass says: {0}", ex.Message));
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (client.Connected)
                {
                    client.Close();
                }
            }
        }
Esempio n. 14
0
        static void EncryptSomeText()
        {
            string dataToBeEncrypted = "My secret text!";
            Console.WriteLine("Original: {0}", dataToBeEncrypted);

            var encryptedData = Encrypt(dataToBeEncrypted);
            Console.WriteLine("Cipher data: {0}", encryptedData.Aggregate<byte, string>("", (s, b) => s += b.ToString()));

            var decryptedString = Decrypt(encryptedData);

            Console.WriteLine("Decrypted:{0}", decryptedString);

            // As you can see, you first need to convert the data you want to encrypt to a byte sequence.
            // To encrypt the data, you need only the public key.
            // You then use the private key to decrypt the data.

            // Because of this, it’s important to store the private key in a secure location.
            // If you would store it in plain text on disk or even in a nonsecure memory location,
            // your private key could be extracted and your security would be compromised.

            // The .NET Framework offers a secure location for storing asymmetric keys in a key container.
            // A key container can be specific to a user or to the whole machine.
            // This example shows how to configure an RSACryptoServiceProvider to use a key container for saving and loading the asymmetric key.

            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes(dataToBeEncrypted);
            string containerName = "SecretContainer";
            CspParameters csp = new CspParameters() { KeyContainerName = containerName };

            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(csp))
            {
                var encryptedByteData = RSA.Encrypt(dataToEncrypt, false);
            }
        }
Esempio n. 15
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog opf = new OpenFileDialog();
                opf.Title = "";
                opf.ShowDialog();
                //string fc = System.IO.File.ReadAllText(opf.FileName);
                UnicodeEncoding ByteConverter = new UnicodeEncoding();
                byte[] dataToEncrypt = ByteConverter.GetBytes(System.IO.File.ReadAllText(opf.FileName));
                byte[] encryptedData;

                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    encryptedData = encryptionfuncs.RSADecrypt(dataToEncrypt, RSA.ExportParameters(true), false);

                }
                System.IO.File.WriteAllBytes(opf.FileName, encryptedData);
                MessageBox.Show("File decrypted.");
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// Hash the data and generate signature
        /// </summary>
        /// <param name="dataToSign"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string HashAndSignString(string dataToSign, RSAParameters key)
        {
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] signatureBytes = HashAndSignBytes(ByteConverter.GetBytes(dataToSign), key);

            return ByteConverter.GetString(signatureBytes);
        }
Esempio n. 17
0
 private static byte[] StringToByteArray(string str)
 {
     if (null == str)
         return null;
     System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
     return enc.GetBytes(str);
 }
Esempio n. 18
0
    private string convertToUnicode(char ch)
    {
        System.Text.UnicodeEncoding class1 = new System.Text.UnicodeEncoding();
        byte[] msg = class1.GetBytes(System.Convert.ToString(ch));

        return(fourDigits(msg[1] + msg[0].ToString("X")));
    }
Esempio n. 19
0
        public static void DecryptFile(string inputFile, string outputFile, string password)
        {
            {
                //string password = @"myKey123"; // Your Key Here

                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                                                   RMCrypto.CreateDecryptor(key, key),
                                                   CryptoStreamMode.Read);

                FileStream fsOut = new FileStream(outputFile, FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte) data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();

            }
        }
        public void Run()
        {
            var _exportKey = new RSACryptoServiceProvider();
            string publicKeyXML = _exportKey.ToXmlString(false);
            string privateKeyXML = _exportKey.ToXmlString(true);

            var ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes("My Secret Data!");

            byte[] encryptedData;
            using (var RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(publicKeyXML);
                encryptedData = RSA.Encrypt(dataToEncrypt, false);
            }

            byte[] decryptedData;
            using (var RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(privateKeyXML);
                decryptedData = RSA.Decrypt(encryptedData, false);
            }

            string decryptedString = ByteConverter.GetString(decryptedData);
            Console.WriteLine(decryptedString); // Displays: My Secret Data!        }
        }
Esempio n. 21
0
        internal static void EncryptFile(string inputFile, string outputFile, string password)
        {

            try {
                var UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                string cryptFile = outputFile;
                var fsCrypt = new FileStream(cryptFile, FileMode.Create);

                var AesMngd = new AesManaged();

                var cs = new CryptoStream(fsCrypt,
                    AesMngd.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);

                using (var fsIn = new FileStream(inputFile, FileMode.Open)) {
                    int data;
                    while ((data = fsIn.ReadByte()) != -1)
                        cs.WriteByte((byte)data);
                }
                cs.Close();
                fsCrypt.Close();
            } catch {
                Shared.MSGBOX(Shared.GetRes("#D.02#","Error"),"Encryption failed!",System.Windows.Application.Current.MainWindow);
            }
        }
Esempio n. 22
0
        internal static void DecryptFile(string inputFile, string outputFile, string password)
        {

            {
                var UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                var fsCrypt = new FileStream(inputFile, FileMode.Open);

                var RMCrypto = new AesManaged();

                var cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

                var fsOut = new FileStream(outputFile, FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();

            }
        }
        public static string HashPassword(string password, string saltValue)
        {
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Password is null");

            var encoding = new UnicodeEncoding();
            var hash = new SHA256CryptoServiceProvider();

            if (saltValue == null)
            {
                saltValue = GenerateSaltValue();
            }

            byte[] binarySaltValue = Convert.FromBase64String(saltValue);
            byte[] valueToHash = new byte[SaltValueSize + encoding.GetByteCount(password)];
            byte[] binaryPassword = encoding.GetBytes(password);

            binarySaltValue.CopyTo(valueToHash, 0);
            binaryPassword.CopyTo(valueToHash, SaltValueSize);

            byte[] hashValue = hash.ComputeHash(valueToHash);
            var hashedPassword = String.Empty;
            foreach (byte hexdigit in hashValue)
            {
                hashedPassword += hexdigit.ToString("X2", CultureInfo.InvariantCulture.NumberFormat);
            }

            return hashedPassword;
        }
Esempio n. 24
0
        /// <summary>
        /// Passwort-Verschlüsselung
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Encrypt(string text)
        {
            if (text.Length < 1)
            {
                return text;
            }

            string code = "";

            System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
            byte[] bytes = enc.GetBytes(text);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(code, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            using (MemoryStream ms = new MemoryStream())
            {
                Rijndael alg = Rijndael.Create();
                alg.Key = pdb.GetBytes(32);
                alg.IV = pdb.GetBytes(16);

                using (CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytes, 0, bytes.Length);
                }

                bytes = ms.ToArray();
            }
            return Convert.ToBase64String(bytes);
        }
Esempio n. 25
0
        /// <summary>
        /// 哈希加密一个字符串
        /// </summary>
        /// <param name="Security"></param>
        /// <returns></returns>
        public static string HashEncoding(string Security)
        {
            byte[] Value;
            SHA512Managed Arithmetic = null;
            try
            {
                UnicodeEncoding Code = new UnicodeEncoding();
                byte[] Message = Code.GetBytes(Security);

                Arithmetic = new SHA512Managed();
                Value = Arithmetic.ComputeHash(Message);
                Security = "";
                foreach (byte o in Value)
                {
                    Security += (int)o + "O";
                }

                return Security;
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (Arithmetic!=null)
                {
                    Arithmetic.Clear();
                }
            }
        }
Esempio n. 26
0
		public static void DecryptFile(string inputFile, string outputFile, string password)
		{
			{
				var unicodeEncoding = new UnicodeEncoding();
				byte[] key = unicodeEncoding.GetBytes(FormatPassword(password));

				if (!File.Exists(inputFile))
				{
					File.Create(inputFile);
				}
				FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
				var rijndaelManaged = new RijndaelManaged();
				var cryptoStream = new CryptoStream(fsCrypt, rijndaelManaged.CreateDecryptor(key, key), CryptoStreamMode.Read);
				var fileStream = new FileStream(outputFile, FileMode.Create);

				try
				{
					int data;
					while ((data = cryptoStream.ReadByte()) != -1)
						fileStream.WriteByte((byte)data);
				}
				catch { throw; }
				finally
				{
					fsCrypt.Close();
					fileStream.Close();
					cryptoStream.Close();
				}
			}
		}
Esempio n. 27
0
        public bool CheckOnRegister(string email)
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, 8145);
            UnicodeEncoding encoding = new UnicodeEncoding();
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(remoteEndPoint);

            //encode from a string format to bytes ("our packages")
            Byte[] bufferOut = encoding.GetBytes(email);

            socket.Send(bufferOut);

            byte[] bytes = new byte[1024];
            int bytesRecieved = socket.Receive(bytes);

            string mess = encoding.GetString(bytes, 0, bytesRecieved);
            if (mess == "1")
            {
                return true;
            }
            else
            {
                return false;

            }
        }
Esempio n. 28
0
        public static void DoTest()
        {
            Console.WriteLine("MD5 测试!");

            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            string source = "Data to Encrypt  这个是一个用于测试MD5的文本信息!";

            byte[] dataToEncrypt = ByteConverter.GetBytes(source);

            Console.WriteLine("原始文本信息:{0}", source);
            Console.WriteLine("原始数据!");
            ByteArrayOutput.Print(dataToEncrypt);

            Console.WriteLine("MD5");
            ByteArrayOutput.Print(MD5hash(dataToEncrypt));

            Console.WriteLine("SHA256");
            ByteArrayOutput.Print(SHA256hash(dataToEncrypt));

            Console.WriteLine("SHA384");
            ByteArrayOutput.Print(SHA384hash(dataToEncrypt));

            Console.WriteLine("SHA512");
            ByteArrayOutput.Print(SHA512hash(dataToEncrypt));
        }
Esempio n. 29
0
        public override void Encrypt()
            {
                //RSA Rsa = new RSA();
                //base.Component.Text = Rsa.encode(base.Component.tp.Text);

                try
                {
                    UnicodeEncoding ByteConverter = new UnicodeEncoding();
                    byte[] encryptedData;
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSA.ImportParameters(RSA.ExportParameters(false));
  
                        
                        byte[] Data = ByteConverter.GetBytes(base.Component.tp.Text.ToString());
                        encryptedData = RSA.Encrypt(Data , false);
                    }
                    base.Component.Text = ByteConverter.GetString(encryptedData);
                }
                //Catch and display a CryptographicException  
                //to the console.
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    base.Component.Text = base.Component.tp.Text.ToString();
                }
               
            }
Esempio n. 30
0
        static void Main(string[] args)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            string publicKeyXML = rsa.ToXmlString(false);
            string privateKeyXML = rsa.ToXmlString(true);

            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes("My secret data!");
            Console.WriteLine("Encrypting: {0}", ByteConverter.GetString(dataToEncrypt));

            byte[] encryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(publicKeyXML);
                encryptedData = RSA.Encrypt(dataToEncrypt, false);
            }

            Console.WriteLine("Encrypted data: {0}", ByteConverter.GetString(encryptedData));

            byte[] decryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(privateKeyXML);
                decryptedData = RSA.Decrypt(encryptedData, false);
            }

            string decryptedString = ByteConverter.GetString(decryptedData);
            Console.WriteLine("Decrypted data: {0}", decryptedString);

            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }
Esempio n. 31
0
        // ===================================================================================================== Public static methods
        public static string GetCacheKey(string customCacheKey, string appNodePath, string portletClientId, bool cacheByPath, bool cacheByParams)
        {
            string key = string.Empty;
            if (!string.IsNullOrEmpty(customCacheKey))
            {
                // if custom cache key is explicitely given, it overrides any other logic, and cache key is explicitely set
                key = string.Concat(CacheKeyPrefix, customCacheKey);
            }
            else
            {
                // by default cache key consists of current application page path and portlet clientid
                key = String.Concat(CacheKeyPrefix, appNodePath, portletClientId);

                if (cacheByPath)
                {
                    // if cache by path is true, absoluteuri is also added to cache key
                    // added means: same content is requested, but presented with different application page the output will be cached independently
                    var absoluteUri = PortalContext.Current.RequestedUri.AbsolutePath;
                    key = String.Concat(key, absoluteUri);
                }

                if (cacheByParams)
                {
                    // if cachebyparams is true, url query params are also added to cache key
                    // added means: same parameters used, but different application page is requested the output will be cached independently
                    var queryPart = HttpContext.Current.Request.Url.GetComponents(UriComponents.Query, UriFormat.Unescaped);
                    key = String.Concat(key, queryPart);
                }
            }

            var sha = new SHA1CryptoServiceProvider();
            var encoding = new UnicodeEncoding();
            return Convert.ToBase64String(sha.ComputeHash(encoding.GetBytes(key)));
        }
Esempio n. 32
0
    /// 将 String 转成 byte[]
    public static byte[] StringToBytes(string fileName, string input)
    {
        System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
        byte[] inputBytes  = converter.GetBytes(input);
        string inputString = converter.GetString(inputBytes);

        return(inputBytes);
    }
 private void WriteToStream(Stream stream, string msg)
 {
     if (stream != null)
     {
         stream.Write(uniEncoding.GetBytes(msg),
                      0, uniEncoding.GetByteCount(msg));
     }
 }
Esempio n. 34
0
    public static void  Main(System.String[] argv)
    {
        int i, predict_probability = 0;

        // parse options
        for (i = 0; i < argv.Length; i++)
        {
            if (argv[i][0] != '-')
            {
                break;
            }
            ++i;
            switch (argv[i - 1][1])
            {
            case 'b':
                predict_probability = atoi(argv[i]);
                break;

            default:
                System.Console.Error.Write("unknown option\n");
                exit_with_help();
                break;
            }
        }
        if (i >= argv.Length)
        {
            exit_with_help();
        }
        try
        {
            //UPGRADE_TODO: Expected value of parameters of constructor 'java.io.BufferedReader.BufferedReader' are different in the equivalent in .NET. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092"'
            System.IO.StreamReader input  = new System.IO.StreamReader(argv[i]);                                                          // Input file
            System.IO.BinaryWriter output = new System.IO.BinaryWriter(new System.IO.FileStream(argv[i + 2], System.IO.FileMode.Create)); // Output file

            TextReader reader = File.OpenText(argv[i + 1]);
            reader.ReadToEnd();
            System.Text.UnicodeEncoding unicodeEncoding = new System.Text.UnicodeEncoding();
            byte[] sBytes = unicodeEncoding.GetBytes(reader.ToString());

            svm_model model = svm.svm_load_model(sBytes); // Model file
            predict(input, output, model, predict_probability);
        }
        catch (System.IO.FileNotFoundException e)
        {
            string message = e.Message;
            exit_with_help();
        }
        catch (System.IndexOutOfRangeException e)
        {
            string message = e.Message;
            exit_with_help();
        }
    }
 static public int GetBytes__String(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         System.String a1;
         checkType(l, 2, out a1);
         var ret = self.GetBytes(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Esempio n. 36
0
        /// <summary>
        /// Encode data given as string, return as Base64d byte array
        /// </summary>
        /// <param name="plainText">The string to be encoded</param>
        /// <returns>The resulting encoded string</returns>
        public string EncryptStringToBase64(string plainText)
        {
            byte [] theBytes = unienc.GetBytes(plainText);

            string encryptedString = null;

            try
            {
                encryptedString = System.Convert.ToBase64String(Encrypt(theBytes, null));
            }
            catch (System.Exception caught)
            {
                Log.Write(caught);
            }
            return(encryptedString);
        }
Esempio n. 37
0
        public static string GetMD5Hash(string rawString)
        {
            System.Text.UnicodeEncoding encode = new System.Text.UnicodeEncoding();
            Byte[] passwordBytes = encode.GetBytes(rawString);
            Byte[] hash;
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            hash = md5.ComputeHash(passwordBytes);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (byte outputByte in hash)
            {
                sb.Append(outputByte.ToString("x2").ToUpper());
            }

            return(sb.ToString());
        }
Esempio n. 38
0
        void Button1Click(object sender, EventArgs e)
        {
            string con = textBox1.Text.Trim();

            if (con == "")
            {
                MessageBox.Show("请输入要解码的字符!");
            }
            else
            {
                try{
                    System.Text.UnicodeEncoding uncode = new System.Text.UnicodeEncoding();
                    byte[] enstr  = uncode.GetBytes(con);
                    string hexstr = "";
                    int    i      = 1;
                    int    len    = enstr.Length;
                    foreach (byte letter in enstr)
                    {
                        int value = Convert.ToInt32(letter);
                        if (i == len)
                        {
                            hexstr += String.Format("{0:X}", value);
                        }
                        else
                        {
                            hexstr += String.Format("{0:X}", value) + " ";
                        }
                        i++;
                    }
                    //MessageBox.Show(hexstr);
                    string[] hexvalue = hexstr.Split(' ');
                    string   mstr     = "";
                    //char charValue;
                    foreach (String hex in hexvalue)
                    {
                        int value = Convert.ToInt32(hex, 16);
                        mstr += Char.ConvertFromUtf32(value);
                        //charValue+=
                    }
                    textBox2.Text = mstr;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("发生异常错误!" + ex.Message);
                }
            }
        }
Esempio n. 39
0
        public static string GetSHA512(string text)
        {
            System.Text.UnicodeEncoding UE = new System.Text.UnicodeEncoding();
            byte[] hashValue;
            byte[] message = UE.GetBytes(text);

            System.Security.Cryptography.SHA512Managed hashString = new System.Security.Cryptography.SHA512Managed();
            string hex = "";

            hashValue = hashString.ComputeHash(message);

            foreach (byte x in hashValue)
            {
                hex += String.Format("{0:x2}", x);
            }
            return(hex);
        }
Esempio n. 40
0
        public static byte[] CreateEncryptedAnswerBlob(string answer, List <Direction> moveSequence)
        {
            byte[] key = MoveSequenceToKey(moveSequence);

            AesManaged aes = new AesManaged();

            aes.Key = key;
            aes.IV  = PuzzleIV;
            ICryptoTransform encryptor = aes.CreateEncryptor();

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte[] answerBuffer = encoding.GetBytes(answer);

            byte[] encAnswer = new byte[answerBuffer.Length];
            encryptor.TransformBlock(answerBuffer, 0, answerBuffer.Length, encAnswer, 0);

            return(encAnswer);
        }
Esempio n. 41
0
        /// <summary>
        /// 取HTML格式的报表
        /// </summary>
        /// <param name="_reportItem"></param>
        /// <returns></returns>
        private byte[] GetSinoSZDefineReport_HTML(MD_ReportItem _reportItem)
        {
            int    actual  = 0;
            string _resStr = "";

            using (OracleConnection cn = OracleHelper.OpenConnection())
            {
                OracleCommand _cmd = new OracleCommand();
                _cmd.CommandText = "select BBJG_C from TJ_ZDYBBFJXXB where  BBMC = :BBMC AND TJDW=:TJDW AND KSRQ=:KSRQ AND JZRQ=:JZRQ ";
                _cmd.CommandType = CommandType.Text;
                _cmd.Connection  = cn;
                _cmd.Parameters.Add(":BBMC", _reportItem.ReportName.ReportName);
                _cmd.Parameters.Add(":TJDW", _reportItem.ReportDWID);
                _cmd.Parameters.Add(":KSRQ", _reportItem.StartDate);
                _cmd.Parameters.Add(":JZRQ", _reportItem.EndDate);

                using (OracleDataReader myOracleDataReader = _cmd.ExecuteReader())
                {
                    myOracleDataReader.Read();

                    OracleClob myOracleClob = myOracleDataReader.IsDBNull(0) ? null : myOracleDataReader.GetOracleClob(0);
                    if (myOracleClob == null)
                    {
                        return(null);
                    }

                    StreamReader streamreader = new StreamReader(myOracleClob, System.Text.Encoding.Unicode);

                    // step 3: get the CLOB data using the Read() method
                    char[] cbuffer = new char[100];
                    while ((actual = streamreader.Read(cbuffer, 0 /*buffer offset*/, cbuffer.Length /*count*/)) > 0)
                    {
                        _resStr += new string(cbuffer, 0, actual);
                    }

                    myOracleDataReader.Close();
                }
                cn.Close();
                System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
                byte[] returnBytes = converter.GetBytes(_resStr);

                return(returnBytes);
            }
        }
Esempio n. 42
0
        private string String2Unicode(string st)
        {
            string uni = "";

            try
            {
                System.Text.UnicodeEncoding u = new System.Text.UnicodeEncoding();
                byte[] ba = u.GetBytes(st);
                for (int n = 0; n <= ba.GetUpperBound(0); n += 2)
                {
                    uni += string.Format("%{0:X2}%{1:X2}", ba[n + 1], ba[n]);
                }
            }
            catch (Exception ex)
            {
                uni = "Error:" + ex.Message.ToString();
            }
            return(uni);
        }
 static public int GetBytes__A_Char__Int32__Int32(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         System.Char[] a1;
         checkArray(l, 2, out a1);
         System.Int32 a2;
         checkType(l, 3, out a2);
         System.Int32 a3;
         checkType(l, 4, out a3);
         var ret = self.GetBytes(a1, a2, a3);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Esempio n. 44
0
        public String Md5Encryption(String src)
        {
            System.Text.UnicodeEncoding encode = new System.Text.UnicodeEncoding();
            System.Text.Decoder         decode = encode.GetDecoder();
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] password      = new byte[encode.GetByteCount(src)];
            char[] char_password = new char[encode.GetCharCount(password)];
            password = encode.GetBytes(src);
            password = md5.ComputeHash(password);
            int length = encode.GetByteCount(src);

            if (length > 16)
            {
                length = 16;
            }
            decode.GetChars(password, 0, length, char_password, 0);
            return(new String(char_password));
        }
Esempio n. 45
0
        static protected byte[] EncodeString(string s, ushort PlatID, ushort EncID)
        {
            byte[] buf = null;

            if (PlatID == 0) // unicode
            {
                System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(true, false);
                buf = ue.GetBytes(s);
            }
            else if (PlatID == 1)  // Mac
            {
                int nCodePage = MacEncIdToCodePage(EncID);
                if (nCodePage != -1)
                {
                    buf = GetCodePageBufFromUnicodeStr(s, nCodePage);
                }
            }
            else if (PlatID == 3) // MS
            {
                if (EncID == 0 || // symbol - strings identified as symbol encoded strings
                                  // aren't symbol encoded, they're unicode encoded!!!
                    EncID == 1 || // unicode
                    EncID == 10)  // unicode with surrogate support for UCS-4
                {
                    System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(true, false);
                    buf = ue.GetBytes(s);
                }
                else if (EncID >= 2 || EncID <= 6)
                {
                    int nCodePage = MSEncIdToCodePage(EncID);
                    if (nCodePage != -1)
                    {
                        buf = GetCodePageBufFromUnicodeStr(s, nCodePage);
                    }
                }
                else
                {
                    //Debug.Assert(false, "unsupported text encoding");
                }
            }

            return(buf);
        }
Esempio n. 46
0
        /// <summary>
        /// Updates the configuration file with data from configurationData.
        /// </summary>
        public static async Task UpdateConfigurationFile()
        {
            if (BridgeInformation.demoMode)
            {
                return;
            }

            //Creates a json string from the data.
            JsonObject jsonObject = new JsonObject();

            if (configurationData.useTelemetry != null)
            {
                jsonObject["useTelemetry"] = JsonValue.CreateBooleanValue((bool)configurationData.useTelemetry);
            }
            else
            {
                jsonObject["useTelemetry"] = JsonValue.CreateNullValue();
            }

            string jsonString = jsonObject.Stringify();

            //Encodes the string to UTF8.
            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte[] encodedString = encoding.GetBytes(jsonString);

            //Writes the decoded bytes to the configuration file.
            configurationFile = await storageFolder.GetFileAsync(configurationFileName);

            using (var stream = await configurationFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                stream.Size = 0;
                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        dataWriter.WriteBytes(encodedString);
                        await dataWriter.StoreAsync();
                    }
                }
            }
        }
Esempio n. 47
0
        /// <summary>
        /// 指定内容获取指定的长度,超过指定长度用“..”代替
        /// 通常用于显示文章最新几条,指定了文章字符长度。
        /// </summary>
        /// <param name="content">文章标题</param>
        /// <param name="len">指定长度</param>
        /// <param name="adddot">是否需要用..来代替超长的字符,如果需要True,不需要False</param>
        /// <returns>返回处理后的字符串</returns>
        public static string LimitString(object content, int len, bool adddot)
        {
            string originalNews = content.ToString().Trim();

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte[] newsBytes = encoding.GetBytes(originalNews);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            int narrowChars = 0;
            int widthChars  = 0;

            for (int i = 1; i < newsBytes.Length; i += 2)
            {
                if (widthChars == len)
                {
                    break;
                }
                byte[] temp = new byte[] { newsBytes[i - 1], newsBytes[i] };
                sb.Append(System.Text.Encoding.Unicode.GetString(temp));
                if ((int)newsBytes[i] == 0)
                {
                    narrowChars++;
                    if (narrowChars == 2)
                    {
                        narrowChars = 0;
                        widthChars++;
                    }
                }
                else
                {
                    widthChars++;
                }
            }
            if (adddot && sb.ToString() != content.ToString())
            {
                return(sb.ToString() + "..");
            }
            return(sb.ToString());
        }
Esempio n. 48
0
        /// <summary>
        /// Méthode réalisant l'envoi de données
        /// <summary>
        public void SendString(String data)
        {
            try
            {
                System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();

                Byte[] values = new Byte[Byte.MaxValue];
                values = encoding.GetBytes(data + "Chr(1)");
                int nextBuf, totalSent = 0;

                if (NS.CanWrite)
                {
                    for (int indx = 0; indx < (values.GetLength(0)); indx += MAX_PACKET_SIZE)
                    {
                        try
                        {
                            //Ecriture des données.
                            NS.Write(values, indx, nextBuf = indx + MAX_PACKET_SIZE < values.GetLength(0) ? MAX_PACKET_SIZE : values.GetLength(0) - indx);
                            totalSent += nextBuf;
                        }
                        catch (Exception e)
                        {
                            // Console.WriteLine("Impossible d'écrire");
                            throw e;
                        }
                    }
                }
                else
                {
                    Trace.WriteDebug(" L'écriture dans le buffer TCP d'un des testers à échoué");
                }

                values = null;
            }
            catch (Exception e)
            {
                Trace.WriteError("Erreur lors de l'envois de données");
                throw e;
            }
        }
        public void WhenRequest_ThenHeadersOk()
        {
            ClientsPoolProvider.ClearDefaults();
            // Arrange
            using (SimpleServer.Create(TestHelpers.BaseUrl, EventHandler))
            {
                var    encoding      = new System.Text.UnicodeEncoding();
                byte[] secretKey     = encoding.GetBytes("DummyKey");
                int    applicationId = 1;
                IHMAC  hmac          = new TestHMAC();
                var    client        = new YouScribeClient(TestHelpers.BaseUrl, YousScribeHMACHttpClientDecorator.GetBaseClientFactory(secretKey, applicationId, hmac));
                YousScribeHMACHttpClientDecorator httpClient = (YousScribeHMACHttpClientDecorator)((DisposableClient)client.clientFactory()).Client;

                // Act
                httpClient.GetAsync(TestHelpers.BaseUrl);

                // Assert
                Assert.NotNull(httpClient.BaseClient.DefaultRequestHeaders.Authorization);
                Assert.NotNull(httpClient.BaseClient.DefaultRequestHeaders.Date);
                Assert.NotNull(httpClient.BaseClient.DefaultRequestHeaders.GetValues(ApiUrls.HMACAuthenticateRandomKeyHeader));
            }
        }
Esempio n. 50
0
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="inputString">要被截取的字符串</param>
        /// <param name="len">长度</param>
        /// <returns>截取后的字符串</returns>
        public static string CutString(string inputString, int len)
        {
            if (string.IsNullOrEmpty(inputString))
            {
                return(string.Empty);
            }
            if (inputString.Length * 2 <= len)
            {
                return(inputString);
            }
            if (inputString.Length > len)
            {
                inputString = inputString.Substring(0, len);
            }

            System.Text.UnicodeEncoding unicode = new System.Text.UnicodeEncoding();
            byte[] s       = unicode.GetBytes(inputString);
            int    realLen = 0;
            int    i       = 0;

            for (i = 0; i < inputString.Length; i++)
            {
                if (s[i * 2 + 1] == 0 && s[i * 2] <= 127)
                {
                    realLen += 1;
                }
                else
                {
                    realLen += 2;
                }

                if (realLen > len)
                {
                    break;
                }
            }
            return(inputString.Substring(0, i));
        }
Esempio n. 51
0
        /// <summary>
        /// Change the working directory for a given process
        /// </summary>
        /// <param name="proc">Handle (as IntPtr from marshalling) to the process to update</param>
        /// <param name="dir">The directory to apply as the cwd of the target process</param>
        static void SetProcessDir(IntPtr proc, string dir)
        {
            // Copy the unicode version of the string to a byte array.
            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            Byte[] bytes = encoding.GetBytes(dir);

            // Allocate enough memory in the target process to copy the entire string over.
            IntPtr ptr = VirtualAllocEx(proc, (IntPtr)0, (uint)bytes.Length, MEM_COMMIT, PAGE_READWRITE);


            if (ptr != null)
            {
                // Copy the string to the target process.
                IntPtr bytesWritten;
                WriteProcessMemory(proc, ptr, bytes, (UIntPtr)bytes.Length, out bytesWritten);

                // Get a pointer to SetCurrentDirectoryW from kernel32.dll
                IntPtr kernel32            = LoadLibrary("kernel32.dll");
                IntPtr setCurrentDirectory = GetProcAddress(kernel32, "SetCurrentDirectoryW");

                // Call SetCurrentDirectoryW in a new thread in the target process, and pass it the pointer to the buffer that was allocated
                // in its process.

                // This takes advantage of the fact that SetCurrentDirectoryW has the exact same C function signature as a thread process
                // and, since it's a kernel function, it exists in the target process.
                IntPtr threadHandle = CreateRemoteThread(proc, (IntPtr)0, 0, setCurrentDirectory, ptr, 0, (IntPtr)0);

                if (threadHandle != (IntPtr)0)
                {
                    // Wait for it to finish.  The directory is now changed.
                    WaitForSingleObject(threadHandle, INFINITE);
                    CloseHandle(threadHandle);
                }

                // Free our memory, that's all we needed.
                VirtualFreeEx(proc, ptr, (UIntPtr)0, MEM_RELEASE);
            }
        }
    //每次编译时生成一个版本号
    public static void GenerateVersionFile()
    {
        DateTime dt         = DateTime.Now;
        var      timestring = dt.Ticks.ToString();// ToString("yyyy-MM-dd-HH-mm-ss");

        string versionfilepath = Application.streamingAssetsPath + "/version.bytes";

        if (File.Exists(versionfilepath))
        {
            File.Delete(versionfilepath);
        }
        FileStream fs = new FileStream(versionfilepath, FileMode.CreateNew);

        System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
        byte[] inputBytes = converter.GetBytes(timestring);


        BinaryWriter bw = new BinaryWriter(fs);

        bw.Write(inputBytes);
        bw.Close();
        fs.Close();
    }
Esempio n. 53
0
        /// <summary>
        /// Triple DES decrypt
        /// </summary>
        /// <param name="input">String to Encrypt</param>
        /// <param name="key">Encryption Key</param>
        /// <returns></returns>
        public static string Encrypt(string input, string key)
        {
            TripleDESCryptoServiceProvider crp = new TripleDESCryptoServiceProvider();

            System.Text.UnicodeEncoding uEncode = new System.Text.UnicodeEncoding();
            System.Text.ASCIIEncoding   aEncode = new System.Text.ASCIIEncoding();

            Byte[]       bytPlainText  = uEncode.GetBytes(input);
            MemoryStream stmCipherText = new MemoryStream();

            Byte[] slt = { 0x12 };
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, slt);

            Byte[] bytDerivedKey = pdb.GetBytes(24);
            crp.Key = bytDerivedKey;
            crp.IV  = pdb.GetBytes(8);
            CryptoStream csEncrypted = new CryptoStream(stmCipherText, crp.CreateEncryptor(), CryptoStreamMode.Write);

            csEncrypted.Write(bytPlainText, 0, bytPlainText.Length);
            csEncrypted.FlushFinalBlock();

            return(System.Convert.ToBase64String(stmCipherText.ToArray()));
        }
Esempio n. 54
0
        /// <summary>
        /// 计算一个字符串的长度

        /// </summary>
        /// <param name = "strFldValue"></param>
        /// <returns></returns>
        public int iCaluFldLength(string strFldValue)
        {
            //如果是ascii码,如字母、数值等,长度为1
            //否则为2
            if (strFldValue.Length > 100)
            {
                strFldValue = strFldValue.Substring(0, 99);
            }
            System.Text.UnicodeEncoding ueFldValueEn = new System.Text.UnicodeEncoding();

            char[] cFldValue  = new char[1];
            int    iFldLength = 0;

            for (int i = 0; i < strFldValue.Length; i++)
            {
                cFldValue[0] = strFldValue[i];
                Byte[] bTemp = new Byte[2];
                try
                {
                    bTemp = ueFldValueEn.GetBytes(cFldValue, 0, 1);
                }
                catch
                {
                    ;
                }

                if (bTemp[0] <= 127 && bTemp[1] == 0)
                {
                    iFldLength += 1;
                }
                else
                {
                    iFldLength += 2;
                }
            }
            return(iFldLength);
        }
Esempio n. 55
0
 public static byte[] CastToBinary(string s)
 {
     System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
     return(encoding.GetBytes(s));
 }
Esempio n. 56
0
        private static byte[] StringToByteArray(string str)
        {
            var enc = new System.Text.UnicodeEncoding();

            return(enc.GetBytes(str));
        }
Esempio n. 57
0
        private bool FragmentProcess()
        {
            int             index, offset;
            List <UuidUrl>  url = new List <UuidUrl>(1);
            List <Fragment> fragments;

            _fragmentJpx = new FragmentJpxStructure();

            //Get Input Jpeg 2000 file name
            _fragmentJpx.inJPG2FileName = _txtInputFile.Text;

            //Get Output Jpeg 2000 file name
            _fragmentJpx.outJPG2FileName = _txtOutputFile.Text;

            //Get Stream file name
            _fragmentJpx.streamFileName = _txtCodeStreamsFiles.Text;

            try
            {
                _fileInformation = (Jpeg2000FileInformation)_mainParentForm.Jpeg2000Eng.GetFileInformation(_fragmentJpx.inJPG2FileName);
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
                return(false);
            }

            //if(_fileInformation.Format != Jpeg2000FileFormat.LeadJpx || _fileInformation.FragmentTable.Length > 0)
            if (_fileInformation.Format != Jpeg2000FileFormat.LeadJpx || _fileInformation.FragmentTable != null)
            {
                Messager.ShowError(this, "The input file is not in JPX format or already fragmented");
                return(false);
            }

            UuidUrl UuidUrlItem = new UuidUrl();

            UuidUrlItem.Flag    = new byte[3];
            UuidUrlItem.Flag[0] = 0;
            UuidUrlItem.Flag[1] = 0;
            UuidUrlItem.Flag[2] = 0;
            UuidUrlItem.Version = 0;

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte [] filename = encoding.GetBytes(_fragmentJpx.streamFileName);
            UuidUrlItem.Location = new byte[filename.Length + 2];
            Array.Copy(filename, UuidUrlItem.Location, filename.Length);
            UuidUrlItem.Location[filename.Length]     = 0; //null termination
            UuidUrlItem.Location[filename.Length + 1] = 0; //null termination
            url.Add(UuidUrlItem);

            fragments = new List <Fragment>();

            for (index = 0, offset = 0; index < _fileInformation.CodeStream.Length; index++)
            {
                Fragment fragmenItem = new Fragment();
                fragmenItem.UrlIndex        = 1;
                fragmenItem.CodeStreamIndex = Convert.ToInt32(index);
                fragmenItem.Offset          = offset;
                offset += Convert.ToInt32(_fileInformation.CodeStream[index].DataSize);
                fragments.Add(fragmenItem);
            }

            try
            {
                _mainParentForm.Jpeg2000Eng.FragmentJpxFile(_fragmentJpx.inJPG2FileName, _fragmentJpx.outJPG2FileName, url, fragments);
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
                return(false);
            }

            FragmentSaveStreamFile(_fragmentJpx.streamFileName, _fragmentJpx.inJPG2FileName, _fileInformation);

            return(true);
        }
Esempio n. 58
0
        void bg_SaveWork(object sender, DoWorkEventArgs e)
        {
            for (int iDLL = 0; iDLL < vDLLs.Count; iDLL++)
            {
                // skip resources.dll
                if (iDLL == 0)
                {
                    continue;
                }

                try
                {
                    AddLog("Making backup " + vDLLs[iDLL].path + ".orig");
                    File.Copy(vDLLs[iDLL].path, vDLLs[iDLL].path + ".orig", true);

                    AddLog("Writing " + vDLLs[iDLL].path);
                    IntPtr hUpdate = BeginUpdateResource(vDLLs[iDLL].path, true);
                    if (hUpdate == IntPtr.Zero)
                    {
                        throw new Exception("Unable to open file " + vDLLs[iDLL].path + " errcode = " + Marshal.GetLastWin32Error());
                    }

                    for (int resId = 0; resId < 0x10000; resId++)
                    {
                        int iIDS = (iDLL * 0x10000) + resId;
                        // If we have an infocard xml resource then write it out.
                        if (infocards.ContainsKey(iIDS) &&
                            !infocards[iIDS].is_string_name)
                        //&& !infocards[iIDS].has_error)
                        {
                            UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                            byte[]          textbuf  = encoding.GetBytes(infocards[iIDS].text);

                            byte[] buf = new byte[textbuf.Length + 6];
                            Buffer.BlockCopy(textbuf, 0, buf, 2, textbuf.Length);
                            buf[0] = 0xFF;
                            buf[1] = 0xFE;
                            buf[buf.Length - 4] = 0x0A;
                            buf[buf.Length - 3] = 0x00;
                            buf[buf.Length - 2] = 0x0A;
                            buf[buf.Length - 1] = 0x00;

                            IntPtr ptr = Marshal.AllocHGlobal(buf.Length);
                            Marshal.Copy(buf, 0, ptr, buf.Length);
                            if (UpdateResource(hUpdate, 23, resId, (1 << 10 | 0x09), ptr, buf.Length) == 0)
                            {
                                throw new Exception("Update resource failed on file " + vDLLs[iDLL].path + " errcode = " + Marshal.GetLastWin32Error());
                            }
                            Marshal.FreeHGlobal(ptr);
                        }

                        // Write to the string table.
                        if ((resId % 16) == 0)
                        {
                            // Build the string buffer which might contain up to 16 unicode strings
                            // with the length in the first two bytes.
                            int    pos = 0;
                            byte[] buf = new byte[0x10000];
                            for (int subId = 0; subId < 16; subId++)
                            {
                                if (infocards.ContainsKey(iIDS + subId) &&
                                    infocards[iIDS + subId].is_string_name)
                                //&& !infocards[iIDS + subId].has_error)
                                {
                                    UnicodeEncoding encoding = new System.Text.UnicodeEncoding(false, false, true);
                                    string          text     = infocards[iIDS + subId].text;

                                    byte[] textbuf = encoding.GetBytes(text);
                                    buf[pos++] = (byte)(text.Length & 0xFF);
                                    buf[pos++] = (byte)(text.Length >> 8);
                                    Buffer.BlockCopy(textbuf, 0, buf, pos, textbuf.Length);
                                    pos += textbuf.Length;
                                }
                                else
                                {
                                    buf[pos++] = 0x00;
                                    buf[pos++] = 0x00;
                                }
                            }

                            if (pos > 32) // non empty resource
                            {
                                IntPtr ptr = Marshal.AllocHGlobal(pos);
                                Marshal.Copy(buf, 0, ptr, pos);
                                if (UpdateResource(hUpdate, 6, (resId / 16) + 1, (1 << 10 | 0x09), ptr, pos) == 0)
                                {
                                    throw new Exception("Update resource failed on file " + vDLLs[iDLL].path + " errcode = " + Marshal.GetLastWin32Error());
                                }
                                Marshal.FreeHGlobal(ptr);
                            }
                        }
                    }
                    if (EndUpdateResource(hUpdate, false) == 0)
                    {
                        throw new Exception("End update resource failed on file " + vDLLs[iDLL].path + " errcode = " + Marshal.GetLastWin32Error());
                    }
                }
                catch (Exception ex)
                {
                    AddLog("ERROR: " + ex.Message);
                    try { File.Copy(vDLLs[iDLL].path + ".orig", vDLLs[iDLL].path, true); }
                    catch { }
                }
            }
            AddLog("Done");
        }
Esempio n. 59
0
 internal void SetTagUnicodeStringData(MsvBox.SegmentType type, string stringData, int lengthDelta)
 {
     System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(true, false);
     byte[] dataBytes = encoding.GetBytes(stringData + '\x00');
     this.SetTagData(type, dataBytes, lengthDelta);
 }
Esempio n. 60
0
        public override void Execute()
        {
            base.Execute();
            PassFailInContext(m_onPass, m_onFail, out m_onPass, out m_onFail);
            m_log.isNotNull(m_of, makeNameTag() + " 'of' file name is null");
            m_log.isNotNull(m_to, makeNameTag() + " 'to' file name is null");
            m_log.isFalse(m_of == "", makeNameTag() + " 'of' file name is empty");
            m_log.isFalse(m_to == "", makeNameTag() + " 'to' file name is empty");
            m_baseStr   = Utilities.evalExpr(m_of);
            m_targetStr = Utilities.evalExpr(m_to);
            // m_baseStr and m_targetStr can be null
            MD5 md5Hasher = MD5.Create();

            try{ Application.Process.WaitForInputIdle(); }
            catch (Win32Exception e)
            { m_log.paragraph(makeNameTag() + " WaitForInputIdle: " + e.Message); }

            string[] ext      = m_baseStr.Split('.');
            int      lastSub  = ext.Length;
            string   fileType = ext[lastSub - 1];
            string   content1 = null;
            string   content2 = null;

            try
            {
                content1 = System.IO.File.ReadAllText(m_baseStr);
                content2 = System.IO.File.ReadAllText(m_targetStr);
            }
            catch (FileNotFoundException e) { m_log.fail(makeNameTag() + e.FileName + " not found"); }
            catch (DirectoryNotFoundException e) { m_log.fail(makeNameTag() + e.ToString() + " not found"); }

            if (fileType.ToLower() == "pdf")
            {             // Cut out date and crc file integrity hashes - they always change
                // obj 0a 3c 3c 2f Producer(PrimoPDF)           0a 3e 3e 0a
                // trailer 0a 3c 3c 20            0a 3e 3e 0a
                m_log.paragraph(makeNameTag() + " comparing PDF files: " + m_of + " and " + m_to);
                Regex  rx       = null;
                Regex  rx2      = null;
                string pattern  = "(<</Producer\\(PrimoPDF\\)[^>]*>>)";
                string pattern2 = "(trailer[\\s\\S]<<[\\s\\S]*>>)";
                try { rx  = new Regex(pattern, System.Text.RegularExpressions.RegexOptions.Multiline);
                      rx2 = new Regex(pattern2, System.Text.RegularExpressions.RegexOptions.Multiline); }
                catch (ArgumentException e)
                { m_log.paragraph(makeNameTag() + e.Message); }
                FileComp       fc  = new FileComp();
                MatchEvaluator cut = new MatchEvaluator(fc.cutMatch);
                if (!rx.IsMatch(content1))
                {
                    m_log.paragraph(makeNameTag() + " no match in PDF file for pattern: " + pattern);
                }
                content1 = rx.Replace(content1, cut);
                content2 = rx.Replace(content2, cut);
                if (!rx2.IsMatch(content1))
                {
                    m_log.paragraph(makeNameTag() + " no match in PDF file for pattern2: " + pattern2);
                }
                content1 = rx2.Replace(content1, cut);
                content2 = rx2.Replace(content2, cut);
            }
            System.Text.Encoding encoding = new System.Text.UnicodeEncoding();
            byte[] hash1 = md5Hasher.ComputeHash(encoding.GetBytes(content1));
            byte[] hash2 = md5Hasher.ComputeHash(encoding.GetBytes(content2));

            string shash1 = getString(hash1);
            string shash2 = getString(hash2);

            m_Result  = shash1 == shash2;
            m_message = null;

            m_log.paragraph(makeNameTag() + "hashOf = " + shash1 + " hashTo = " + shash2);
            if (m_message != null)
            {
                m_log.paragraph(makeNameTag() + "Message is not null");
            }
            Finished = true;             // tell do-once it's done

            if ((m_onPass == "assert" && m_Result == true) ||
                (m_onFail == "assert" && m_Result == false))
            {
                if (m_message != null)
                {
                    m_log.fail(makeNameTag() + m_message.Read());
                }
                else
                {
                    m_log.fail(makeNameTag() + "File-Comp Assert: Result = '" + m_Result + "', on-pass='******', on-fail='" + m_onFail + "', hashOf='"
                               + shash1 + "', hashTo='" + shash2 + "'");
                }
            }
            m_log.result(this);
        }