Exemple #1
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")));
    }
        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();
            }
        }
 public void PosTest3()
 {
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     bool actualValue;
     actualValue = uEncoding.Equals(new TimeSpan());
     Assert.False(actualValue);
 }
Exemple #4
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="base64code">传入加密数据</param>
        /// <returns>返回解密数据</returns>
        static public string Decrypt(string base64code)
        {

            var a = new FileInfo("E:/100115_SignKey.pub").OpenRead();
            var b = new BufferedStream(a);
            //string c = 
            try
            {
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.FromXmlString("");

                RSAParameters rsaParameters = new RSAParameters();

                rsaParameters.Exponent = Convert.FromBase64String("AQAB");
                rsaParameters.Modulus =
                    Convert.FromBase64String(
                        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyq3xJ3jtuWSWk4nCCgysplqV3DyFGaF7iP7PO2vEUsgEq+vqKr+frlwji2n7A1TbpV7KhEGJIT9LW/9WCdBhlu6gnBdErtAA4Or43ol2K1BnY6VBcLWccloMd3YFHG8gOohCVIDbw863Wg0FNS27SM25U+XQfrNFaqBIa093WgAbwRIK06uzC01sW+soutvk+yAYBtbH7I7/1/dFixHKS2KN/7y3pvmXYBIRuBvn35IqwY3Gk0duEfbEr9F6wm2VKhS1zQG760FrHfhbXR+IN5nSTQBHBkw4QukLLvUqueKYfVdp2/2RCnY/At0bbOcA2tAPohDAfUDRdOZsFiTIMQID");

                byte[] encryptedData;
                byte[] decryptedData;

                encryptedData = Convert.FromBase64String(base64code);

                decryptedData = RSADeCrtypto(encryptedData, rsaParameters, true);
                return ByteConverter.GetString(decryptedData);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
Exemple #5
0
		static EncodingDetecingInputStream ()
		{
			StrictUTF8 = new UTF8Encoding (false, true);
			Strict1234UTF32 = new UTF32Encoding (true, false, true);
			StrictBigEndianUTF16 = new UnicodeEncoding (true, false, true);
			StrictUTF16 = new UnicodeEncoding (false, false, true);
		}
        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!        }
        }
Exemple #7
0
        private static string GenerateSaltValue()
        {
            UnicodeEncoding utf16 = new UnicodeEncoding();

            if (utf16 != null)
            {
                // Create a random number object seeded from the value
                // of the last random seed value. This is done
                // interlocked because it is a static value and we want
                // it to roll forward safely.

                Random random = new Random(unchecked((int)DateTime.Now.Ticks));

                if (random != null)
                {
                    // Create an array of random values.

                    byte[] saltValue = new byte[SaltValueSize];

                    random.NextBytes(saltValue);

                    // Convert the salt value to a string. Note that the resulting string
                    // will still be an array of binary values and not a printable string.
                    // Also it does not convert each byte to a double byte.

                    string saltValueString = utf16.GetString(saltValue);

                    // Return the salt value as a string.

                    return saltValueString;
                }
            }

            return null;
        }
        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();
                }
            }
        }
Exemple #9
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();
				}
			}
		}
Exemple #10
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();
                }
            }
        }
        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;
        }
Exemple #12
0
        private static void ConvertDataSetToXMLFile(DataSet xmlDS, string xmlFile)
        {
            MemoryStream stream = null;
            XmlTextWriter writer = null;
            try
            {
                stream = new MemoryStream();
                //从stream装载到XmlTextReader
                writer = new XmlTextWriter(stream, Encoding.Unicode);

                //用WriteXml方法写入文件.
                xmlDS.WriteXml(writer);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);

                //返回Unicode编码的文本
                UnicodeEncoding utf = new UnicodeEncoding();
                StreamWriter sw = new StreamWriter(xmlFile);
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sw.WriteLine(utf.GetString(arr).Trim());
                sw.Close();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }
Exemple #13
0
    /// 将 String 转成 byte[]
    public static string BytesToString(string fileName, byte[] input)
    {
        System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
        string inputString = converter.GetString(input);

        return(inputString);
    }
Exemple #14
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();
                }
               
            }
        public void SendMessage(string text)
        {
            var clientStream = _tcpClient.GetStream();
            var message = Encoding.UTF8.GetBytes(text);
            while (true)
            {
                int bytesRead;
                try
                {
                    bytesRead = clientStream.Read(message, 0, Size);
                }
                catch
                {
                    break;
                }

                if (bytesRead == 0)
                {
                    break;
                }

                var encoder = new UnicodeEncoding();
                var msg = encoder.GetString(message, 0, bytesRead);
                SentMessageEvent(this, new ClientSentMessageEventArgs(Name, msg));

                var result = Action(msg);
                Echo(result, encoder, clientStream);
            }
        }
Exemple #16
0
        internal static void WriteToLog(SPWeb web, string message)
        {
            ASCIIEncoding enc = new ASCIIEncoding();
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            string errors = message;

            SPFile files = web.GetFile("/" + DocumentLibraryName + "/" + LogFileName);

            if (files.Exists)
            {
                byte[] fileContents = files.OpenBinary();
                string newContents = enc.GetString(fileContents) + Environment.NewLine + errors;
                files.SaveBinary(enc.GetBytes(newContents));
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter sw = new StreamWriter(ms, uniEncoding))
                    {
                        sw.Write(errors);
                    }

                    SPFolder LogLibraryFolder = web.Folders[DocumentLibraryName];
                    LogLibraryFolder.Files.Add(LogFileName, ms.ToArray(), false);
                }
            }

            web.Update();
        }
 //将DataSet转换为xml对象字符串
 public static string ConvertDataSetToXML(DataSet xmlDS)
 {
     MemoryStream stream = null;
     XmlTextWriter writer = null;
     try
     {
         stream = new MemoryStream();
         //从stream装载到XmlTextReader
         writer = new XmlTextWriter(stream, Encoding.Unicode);
         //用WriteXml方法写入文件.
         xmlDS.WriteXml(writer);
         int count = (int)stream.Length;
         byte[] arr = new byte[count];
         stream.Seek(0, SeekOrigin.Begin);
         stream.Read(arr, 0, count);
         UnicodeEncoding utf = new UnicodeEncoding();
         return utf.GetString(arr).Trim();
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
     finally
     {
         if (writer != null) writer.Close();
     }
 }
Exemple #18
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)
            {

            }
        }
 public void PosTest1()
 {
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     actualValue = uEncoding.GetByteCount("");
     Assert.Equal(0, actualValue);
 }
Exemple #20
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();
        }
 public void PosTest1()
 {
     UnicodeEncoding expectedValue = new UnicodeEncoding(false, true);
     UnicodeEncoding actualValue;
     actualValue = new UnicodeEncoding();
     Assert.Equal(expectedValue, actualValue);
 }
        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);
            }
        }
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            string descriptor = bindingContext.ModelName;
            if (!String.IsNullOrEmpty(descriptor))
                descriptor = descriptor + ".";
            string availabilityContentDataType =
                GetValue(bindingContext, descriptor +"ContentDataType");
            ContentTypeEnums ContentDataType;
            if (availabilityContentDataType != null)
            {
                Enum.TryParse(availabilityContentDataType, out ContentDataType);
                IContentType model = null;
                UnicodeEncoding encoding = new UnicodeEncoding();
                switch (ContentDataType)
                {
                    case ContentTypeEnums.Text:
                        ContentTextVm tempModelText = new ContentTextVm();
                        tempModelText.ContentData = GetTextContent(bindingContext, descriptor);
                        model = tempModelText;
                        break;
                    case ContentTypeEnums.Image:
                        ContentImageVm tempModelImage = new ContentImageVm();
                        model = tempModelImage;
                        break;
                    default:
                        throw new NotImplementedException("Unknown content type: " + ContentDataType);
                }

                return model;
            }
            throw new NotImplementedException("Property ContentDataType not found");
        }
        /// <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);
        }
Exemple #25
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;

            }
        }
        //*********************************************************************
        //
        // Security.Encrypt() Method
        //
        // The Encrypt method encrypts a clean string into a hashed string
        //
        //*********************************************************************
        public static string Encrypt(string cleanString)
        {
            Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString);
            Byte[] hashedBytes = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

            return BitConverter.ToString(hashedBytes);
        }
 private static EMFFont Process(byte[] RecordData)
 {
     //put the Data into a stream and use a binary reader to read the data
     MemoryStream _ms = null;
     BinaryReader _br = null;
     try
     {
         _ms = new MemoryStream(RecordData);
         _br = new BinaryReader(_ms);
         UInt32 Version = _br.ReadUInt32();
         Single EmSize = _br.ReadSingle();
         UInt32 SizeUnit = _br.ReadUInt32();
         Int32 FontStyleFlags = _br.ReadInt32();
         _br.ReadUInt32();
         UInt32 NameLength = _br.ReadUInt32();
         char[] FontFamily = new char[NameLength]; 
         System.Text.UnicodeEncoding d = new System.Text.UnicodeEncoding();
         d.GetChars(_br.ReadBytes((int)NameLength * 2),0,(int)NameLength * 2,FontFamily,0);                
         Font aFont = new Font(new String(FontFamily), EmSize, (FontStyle)FontStyleFlags, (GraphicsUnit)SizeUnit);
         EMFFont ThisFont = new EMFFont();
         ThisFont.myFont = aFont;
         return ThisFont;
     }
     finally
     {
         if (_br != null)
             _br.Close();               
         if (_ms != null)
             _ms.Dispose();            
     }
 }
		static Encoding GetEncoding (XmlNode section, string att, string enc)
		{
			Encoding encoding = null;
			try {
				switch (enc.ToLower ()) {
				case "utf-16le":
				case "utf-16":
				case "ucs-2":
				case "unicode":
				case "iso-10646-ucs-2":
					encoding = new UnicodeEncoding (false, true);
					break;
				case "utf-16be":
				case "unicodefffe":
					encoding = new UnicodeEncoding (true, true);
                                        break;
				case "utf-8":
				case "unicode-1-1-utf-8":
				case "unicode-2-0-utf-8":
				case "x-unicode-1-1-utf-8":
				case "x-unicode-2-0-utf-8":
					encoding = new UTF8Encoding (false, false);
					break;
				default:
					encoding = Encoding.GetEncoding (enc);
					break;
				}
			} catch {
				EncodingFailed (section, att, enc);
				encoding = new UTF8Encoding (false, false);
			}

			return encoding;
		}
Exemple #29
0
        public string mEncriptar(string strToEncrypt)
        {
            string Key = ppKeyEncriptar;
            string IV = ppIVEncriptar;

            MemoryStream output = new MemoryStream();
            byte[] byteData = new UnicodeEncoding().GetBytes(strToEncrypt);

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            byte[] desKey = new byte[Key.Length / 2];

            for (int i = 0; i < Key.Length; i += 2)
            {
                desKey[i / 2] = byte.Parse(Key.Substring(i, 2), NumberStyles.HexNumber);
            }

            byte[] desIV = new byte[IV.Length / 2];
            for (int i = 0; i < IV.Length; i += 2)
            {
                desIV[i / 2] = byte.Parse(IV.Substring(i, 2), NumberStyles.HexNumber);
            }

            CryptoStream crypt = new CryptoStream(output, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
            crypt.Write(byteData, 0, byteData.Length);
            crypt.Close(); output.Close();

            byte[] bin = output.ToArray();
            return Convert.ToBase64String(bin);
        }
 private static byte[] StringToByteArray(string str)
 {
     if (null == str)
         return null;
     System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
     return enc.GetBytes(str);
 }
        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));
        }
Exemple #32
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);
        }
Exemple #33
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);
    }
Exemple #34
0
 private static byte[] StringToByteArray(string str)
 {
     if (null == str)
     {
         return(null);
     }
     System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
     return(enc.GetBytes(str));
 }
Exemple #35
0
 private static string ByteArrayToString(byte[] arr)
 {
     if (null == arr)
     {
         return(null);
     }
     System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
     return(enc.GetString(arr));
 }
        public static int Main(string[] args)
        {
            ms_appName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            System.Text.UnicodeEncoding encode = new System.Text.UnicodeEncoding();

            ms_appNameBytes  = encode.GetBytes(ms_appName);
            ms_outputLogName = ApplicationName + OUTPUTEXT;
            try
            {
                ms_cmdLineArg.Parse(args);

                switch (ms_cmdLineArg.Action)
                {
                case Action.none:
                    WriteToConsole("Command line arguments are required. Use /? or /help to see the usage.");
                    break;

                // print the usage text
                case Action.help:
                    break;

                // Install the NT Service
                case Action.install:
                    NTService.Install(ms_cmdLineArg.NTServiceName, ms_cmdLineArg.UserName, ms_cmdLineArg.Password);
                    break;

                // Uninstall the NT Service
                case Action.uninstall:
                    NTService.Uninstall(ms_cmdLineArg.NTServiceName);
                    break;

                // the program is being run and not installed/uninstalled
                case Action.run:
                    //if the External Activation is started as a NT service
                    if (ms_cmdLineArg.IsService)
                    {
                        NTService.MainFunction(ms_cmdLineArg.NTServiceName);
                    }
                    // if started from the Console or as an Application
                    else
                    {
                        BootExternalActivator();
                    }
                    break;

                default:
                    throw new EAException("Unexpected action", Error.unexpectedError);
                }
                return(0);
            }
            catch (Exception e)
            {
                DoHardKill(e);
                return(0);
            }
        }
Exemple #37
0
        public new FileModel ToLib()
        {
            FileModel f = new FileModel(Name, Size, Hash, StringEnum.GetStringValue(Type),
                                        Uploaded, Modified);

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            f.Data = encoding.GetBytes(Contents);

            return(f);
        }
        /// <summary>
        /// Generates the keys and calls JEE service (recursive function)
        /// </summary>
        public static void GenKeys(char[] set, string content, string key, int n, int k, string name, MSG msg)
        {
            if (Utils.FOUND_SECRET == false)
            {
                if (k == 0)
                {
                    if (Utils.FOUND_SECRET == false)
                    {
                        string         r   = Decrypt(content, key);
                        JEEService.msg res = Utils.ToJEEMessage(msg);
                        System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                        byte[] rr = encoding.GetBytes(r);
                        //sbyte[] x = (sbyte[])Array.ConvertAll(rr, b => unchecked((sbyte)b));
                        string rrr = "";
                        for (int i = 0; i < rr.Length; i++)
                        {
                            if (i == rr.Length - 1)
                            {
                                rrr += rr[i].ToString();
                            }
                            else
                            {
                                rrr += rr[i].ToString() + ",";
                            }
                        }


                        res.data = new object[] { name, rrr, key };

                        try {
                            Console.WriteLine(key);
                            svc.fileCheck(res);
                        } catch (FaultException ex) {
                            Console.WriteLine(ex);
                        }
                    }

                    return;
                }

                /*for (int i=0; i<n; i++) {
                 *  if (Utils.FOUND_SECRET) break;
                 *  string newPrefix = key + set[i];
                 *  GenKeys(set, content, newPrefix, n, k - 1, name, msg);
                 * }*/
                Parallel.For(0, n, (i, state) => {
                    if (Utils.FOUND_SECRET)
                    {
                        state.Break();
                    }
                    string newPrefix = key + set[i];
                    GenKeys(set, content, newPrefix, n, k - 1, name, msg);
                });
            }
        }
Exemple #39
0
        /// <summary>Utility function to convert a byte array to a string</summary>
        public static string BytesToString(byte[] message)
        {
            if (message.Length <= 0)
            {
                return("");
            }

            System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding();

            return(encoderUnicode.GetString(message));
        }
Exemple #40
0
        /// <summary>Utility function to convert a string to a byte array</summary>
        public static byte[] StringToBytes(string message)
        {
            if (message.Length <= 0)
            {
                return(new byte[0]);
            }

            System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding();

            return(encoderUnicode.GetBytes(message));
        }
Exemple #41
0
        public string UnicodeToCharacter(string text)
        {
            text.Replace(" ", "");
            byte[] arr = HexStringToByteArray(text);

            System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();

            string str = converter.GetString(arr);

            return(str);
        }
Exemple #42
0
        public static string EncryptWithMD5(string ClearString)
        {
            System.Text.UnicodeEncoding objUE = new System.Text.UnicodeEncoding();

            byte[] bytClearString = objUE.GetBytes(ClearString);

            MD5CryptoServiceProvider objProv = new MD5CryptoServiceProvider();

            byte[] hash = objProv.ComputeHash(bytClearString);
            return(Convert.ToBase64String(hash));
        }
Exemple #43
0
        public static string GenerarSHA(string sCadena)
        {
            System.Text.UnicodeEncoding ueCodigo = new System.Text.UnicodeEncoding();

            byte[] ByteSourceText = ueCodigo.GetBytes(sCadena);

            SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();

            byte[] ByteHash = SHA.ComputeHash(ueCodigo.GetBytes(sCadena));

            return(Convert.ToBase64String(ByteHash));
        }
Exemple #44
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();
        }
    }
Exemple #45
0
        public static string EncryptSHA(string Password)
        {
            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte[] hashBytes = encoding.GetBytes(Password);

            //Compute the SHA-1 hash
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            byte[] cryptPassword = sha1.ComputeHash(hashBytes);

            return(BitConverter.ToString(cryptPassword));
        }
Exemple #46
0
    IEnumerator StartGetNetTable()
    {
        string url = @"http://ooform.ooroom.com/NetItem.txt";

        Debug.Log(url);
        WWW www = new WWW(url);

        yield return(www);

        System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
        mFormArray = OOFormArray.GetForm(converter.GetString(www.bytes));
    }
Exemple #47
0
        public bool Open(Dictionary <string, string> processingInstruction, string file)
        {
            TextReader reader = new StreamReader(file, Encoding.UTF8); //read the file. Here in 1.txt you need to put your data in single line
            string     all    = reader.ReadToEnd();
            Encoding   iso    = Encoding.GetEncoding("unicode");

            byte[] isoBytes = iso.GetBytes(all);

            string contents = new System.Text.UnicodeEncoding().GetString(((byte[])(isoBytes)));

            return(ParseXMLString(processingInstruction, contents));
        }
 static public int ctor_s(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding o;
         o = new System.Text.UnicodeEncoding();
         pushValue(l, true);
         pushValue(l, o);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static public int GetPreamble(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         var ret = self.GetPreamble();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #50
0
        /// <summary>
        /// Encrypts the SHA.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        public static string EncryptSHA(string content)
        {
            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();

            byte[] hashBytes = encoding.GetBytes(content);

            //Compute the SHA-1 hash
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            byte[] result = sha1.ComputeHash(hashBytes);

            return(BitConverter.ToString(result));
        }
Exemple #51
0
        public static string SHA512(string text)
        {
            byte[] passHash;
            var    byteConverter = new System.Text.UnicodeEncoding();
            var    bytes         = byteConverter.GetBytes(text);

            using (SHA512 shaM = new SHA512Managed())
            {
                passHash = shaM.ComputeHash(bytes);
            }

            return(Convert.ToBase64String(passHash));
        }
Exemple #52
0
    private static string GetVerificationHash(string Email, string Password)
    {
        System.Security.Cryptography.SHA256Managed m = new System.Security.Cryptography.SHA256Managed();
        byte[] buffer = new System.Text.UnicodeEncoding().GetBytes(String.Format("{0}{1}{2}", "b7079d7d-80e6-4206-8e92-97c63fd201d1", Email, Password));
        byte[] bArr   = m.ComputeHash(buffer);
        string retVal = "";

        foreach (byte b in bArr)
        {
            retVal += b.ToString("X");
        }
        return(retVal);
    }
Exemple #53
0
        string SendHttpPost(string requeststring, string url)
        {
            HttpWebRequest _webreq = (HttpWebRequest)WebRequest.Create(url);

            _webreq.Credentials = new NetworkCredential(UserName, Password);

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            string postdata = requeststring;

            byte[] data = encoding.GetBytes(postdata);
            _webreq.Method        = "POST";
            _webreq.ContentType   = "application/x-www-form-urlencoded";
            _webreq.ContentLength = data.Length;

            /*
             * string _respstring = null;
             * try
             * {
             *  using (Stream stream = _webreq.GetRequestStream())
             *  {
             *      stream.Write(data, 0, data.Length);
             *  }
             * }
             * catch (Exception ex)
             * {
             *  _respstring = ex.Message;
             * }
             */
            string _respstring = "";

            _webreq.ContentLength = requeststring.Length;

            using (var sw = new StreamWriter(_webreq.GetRequestStream(), Encoding.ASCII))
            {
                sw.Write(requeststring);
            }

            try
            {
                HttpWebResponse _webresp = (HttpWebResponse)_webreq.GetResponse();
                using (StreamReader _reader = new StreamReader(_webresp.GetResponseStream(), System.Text.Encoding.UTF8))
                {
                    _respstring = _reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                _respstring = ex.Message;
            }
            return(_respstring);
        }
        /// <summary>
        /// Decrypts the file
        /// </summary>
        public static string Decrypt(string content, string key)
        {
            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte[] contentBytes = encoding.GetBytes(content);
            byte[] keyBytes     = encoding.GetBytes(key);
            byte[] resultBytes  = new byte[contentBytes.Length];

            for (int i = 0; i < contentBytes.Length; i++)
            {
                resultBytes[i] = (byte)(contentBytes[i] ^ keyBytes[i % keyBytes.Length]);
            }

            return(encoding.GetString(resultBytes));
        }
        /// <summary>
        /// 从字符串获取unicode码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static public int String2Unicode(string str)
        {
            System.Text.UnicodeEncoding unicodeEncodeing = new System.Text.UnicodeEncoding();
            byte[] bs = unicodeEncodeing.GetBytes(str);
            int    ts = 0;

            for (int i = 0; i < bs.Length; i++)
            {
                int sub    = bs[i];
                int addSub = (int)Math.Pow(256, i) * sub;
                ts += addSub;
            }
            return(ts);
        }
 static public int GetMaxCharCount(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         System.Int32 a1;
         checkType(l, 2, out a1);
         var ret = self.GetMaxCharCount(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static new public int Equals(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         System.Object a1;
         checkType(l, 2, out a1);
         var ret = self.Equals(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static public int GetByteCount__A_Char(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         System.Char[] a1;
         checkArray(l, 2, out a1);
         var ret = self.GetByteCount(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
        public bool UnitTest()
        {
            string data0 = @"To Sherlock Holmes she is always the woman. I have seldom heard him mention her under any other name. In his eyes she eclipses and predominates the whole of her sex. It was not that he felt any emotion akin to love for Irene Adler. All emotions, and that one particularly, were abhorrent to his cold, precise but admirably balanced mind. He was, I take it, the most perfect reasoning and observing machine that the world has seen, but as a lover he would have placed himself in a false position. He never spoke of the softer passions, save with a gibe and a sneer. They were admirable things for the observer—excellent for drawing the veil from men’s motives and actions. But for the trained reasoner to admit such intrusions into his own delicate and finely adjusted temperament was to introduce a distracting factor which might throw a doubt upon all his mental results. Grit in a sensitive instrument, or a crack in one of his own high-power lenses, would not be more disturbing than a strong emotion in a nature such as his. And yet there was but one woman to him, and that woman was the late Irene Adler, of dubious and questionable memory.";

            var encoder = new System.Text.UnicodeEncoding();

            var b  = EncryptBuffer(encoder.GetBytes(data0), keys.PublicKey);
            var b2 = DecryptBuffer(b, keys.PrivateKey);

            var data1 = encoder.GetString(b2);

            var r = data0 == data1;

            return(r);
        }
Exemple #60
0
 public static string HashEncoding(string Security)
 {
     System.Text.UnicodeEncoding unicodeEncoding = new System.Text.UnicodeEncoding();
     byte[] bytes = unicodeEncoding.GetBytes(Security);
     System.Security.Cryptography.SHA512Managed sHA512Managed = new System.Security.Cryptography.SHA512Managed();
     byte[] array = sHA512Managed.ComputeHash(bytes);
     Security = "";
     byte[] array2 = array;
     for (int i = 0; i < array2.Length; i++)
     {
         byte b = array2[i];
         Security = Security + (int)b + "O";
     }
     return(Security);
 }