GetString() публичный Метод

public GetString ( byte bytes, int index, int count ) : string
bytes byte
index int
count int
Результат string
Пример #1
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();
        }
Пример #2
0
        static void Main(string[] args)
        {
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes("My secret data!");
            Console.WriteLine("Encrypting: {0}", ByteConverter.GetString(dataToEncrypt));
            string containerName = "SecretContainer";
            CspParameters csp = new CspParameters() { KeyContainerName = containerName };
            byte[] encryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(csp))
            {
                encryptedData = RSA.Encrypt(dataToEncrypt, false);
            }

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

            byte[] decryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(csp))
            {
                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();
        }
Пример #3
0
        static void RSAEncrypt()
        {
            UnicodeEncoding bytConvertor = new UnicodeEncoding();
            byte[] plainData = bytConvertor.GetBytes("Sample data");
            RSACryptoServiceProvider RSAServiceProvider = new RSACryptoServiceProvider();

            byte[] enData = Encrypt(plainData, RSAServiceProvider.ExportParameters(false));
            Console.WriteLine("Encrypted Output: {0}", bytConvertor.GetString(enData));

            byte[] deData = Decrypt(enData, RSAServiceProvider.ExportParameters(true));
            Console.WriteLine("Decrypted Output: {0}", bytConvertor.GetString(deData));
        }
Пример #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;
            }
        }
Пример #5
0
        /// <summary>
        /// Reads a string. It is assumed that a MTF_MEDIA_ADDRESS structure is next in the stream.
        /// </summary>
        public string ReadString(long StartPosition, EStringType Type)
        {
            long oldpos = BaseStream.Position;

            ushort sz  = ReadUInt16();
            long   off = StartPosition + ReadUInt16();

            BaseStream.Seek(off, System.IO.SeekOrigin.Begin);
            string str;

            if (Type == EStringType.ANSI)
            {
                byte[] bytes = ReadBytes(sz);
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                str = encoding.GetString(bytes);
            }
            else if (Type == EStringType.Unicode)
            {
                byte[] bytes = ReadBytes(sz);
                System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                str = encoding.GetString(bytes);
            }
            else
            {
                str = "";
            }

            BaseStream.Seek(oldpos + 4, System.IO.SeekOrigin.Begin);

            return(str);
        }
Пример #6
0
        /// <summary>This version of DecryptData takes the encrypted message, password
        /// and IV as strings and decrypts the message, returning the plain text as a string.
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key that was used to encrypt the message</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used in encrypting the message</param>
        /// <param name="keySize">The key size used in encrypting the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param>
        /// <param name="messageAsHex">Whether the encrypted message was returned as Hex</param>
        public static string DecryptData(string message, string password,
                                         string initialisationVector, BlockSize blockSize,
                                         KeySize keySize, EncryptionMode cryptMode, bool messageAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // Dont do any work is the message is empty
            if (message.Length <= 0)
            {
                return("");
            }

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

            // Was message supplied in Hex or as simple string
            if (messageAsHex)
            {
                messageData = HexToBytes(message);
            }
            else
            {
                messageData = encoderUnicode.GetBytes(message);
            }

            // Convert key and IV to byte arrays
            passwordData = encoderUnicode.GetBytes(password);
            vectorData   = encoderUnicode.GetBytes(initialisationVector);

            // Return the decrypted plain test as a string
            return(encoderUnicode.GetString(DecryptData(messageData, passwordData,
                                                        vectorData, blockSize, keySize, cryptMode)));
        }
Пример #7
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();
        }
Пример #8
0
        /// <summary>This version of EncryptData takes the message, password
        /// and IV as strings and encrypts the message, returning the encrypted text as a string.
        /// </summary>
        /// <param name="message">The plain text message</param>
        /// <param name="password">The password/key to encrypt the message with</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used to encrypt the message</param>
        /// <param name="keySize">The key size used to encrypt the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param>
        /// <param name="returnAsHex">Whether the encrypted message is to be returned as Hex</param>
        public static string EncryptData(string message, string password,
                                         string initialisationVector, BlockSize blockSize,
                                         KeySize keySize, EncryptionMode cryptMode, bool returnAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // If message is empty dont bother doing any work
            if (message.Length <= 0)
            {
                return("");
            }

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

            // Convert message, key and IV to byte arrays
            messageData  = encoderUnicode.GetBytes(message);
            passwordData = encoderUnicode.GetBytes(password);
            vectorData   = encoderUnicode.GetBytes(initialisationVector);

            // Return encrypted message as string (hex version of bytes if required)
            if (returnAsHex)
            {
                return(BytesToHex(EncryptData(messageData, passwordData,
                                              vectorData, blockSize, keySize, cryptMode)));
            }
            else
            {
                return(encoderUnicode.GetString(EncryptData(messageData, passwordData,
                                                            vectorData, blockSize, keySize, cryptMode)));
            }
        }
Пример #9
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 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!        }
        }
Пример #11
0
        //generates a random salt value based on the timestamp
        public static string GenerateSaltValue()
        {
            UnicodeEncoding utf16 = new UnicodeEncoding();

            if (utf16 != null)
            {
                // Create a random number object

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

                if (random != null)
                {
                    // create random values in an array

                    byte[] saltValue = new byte[16];

                    random.NextBytes(saltValue);

                    // Convert the salt value to a string

                    string saltValueString = utf16.GetString(saltValue);

                    // Return the salt value as a string

                    return saltValueString;
                }
            }

            return null;
        }
Пример #12
0
 //将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();
     }
 }
Пример #13
0
        public static string ReadUnicodeString(byte[] b, int pos, int length)
        {
            string s;

            System.Text.UnicodeEncoding Encoder = null;
            if (length <= 0)
            {
                return("");
            }
            if (length * 2 + pos > b.Length)
            {
                return("");
            }
            Encoder = new System.Text.UnicodeEncoding();
            try
            {
                s = Encoder.GetString(b, pos, length * 2);
                s = s.Replace("\r", " ");
                s = s.Replace("\n", " ");
            }
            catch (Exception)
            {
                return("");
            }
            return(s);
        }
Пример #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();
                }
               
            }
        /// <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);
        }
Пример #16
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;

            }
        }
Пример #17
0
        public static string DecryptStringFromBytes_RSA(byte[] cipherText, RSAParameters RsaParameters)
        {
            var byteConventer = new System.Text.UnicodeEncoding();
            var decryptedData = RSAEncrypt(cipherText, RsaParameters, false);

            return(byteConventer.GetString(decryptedData));
        }
Пример #18
0
        private void AddTextFileToDynamicData(string key, HttpPostedFileBase file)
        {
            var buffer = new byte[file.ContentLength];

            file.InputStream.Read(buffer, 0, file.ContentLength);
            System.Text.Encoding enc;
            string s = null;

            if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)
            {
                enc = new System.Text.ASCIIEncoding();
                s   = enc.GetString(buffer, 3, buffer.Length - 3);
            }
            else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
            {
                enc = new System.Text.UnicodeEncoding();
                s   = enc.GetString(buffer, 2, buffer.Length - 2);
            }
            else
            {
                enc = new System.Text.ASCIIEncoding();
                s   = enc.GetString(buffer);
            }

            pythonModel.DictionaryAdd(key, s);
        }
Пример #19
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);
        }
Пример #20
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);
    }
Пример #21
0
        public string Decrypt(byte[] cipher)
        {
            ICryptoTransform transform = Rijndael.CreateDecryptor();

            byte[] decryptedValue = transform.TransformFinalBlock(cipher, 0, cipher.Length);
            return(UnicodeEncoding.GetString(decryptedValue));
        }
Пример #22
0
        public string Decrypt(string base64code)
        {
            try
            {
                //Create a UnicodeEncoder to convert between byte array and string.
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                //Create a new instance of RSACryptoServiceProvider to generate
                //public and private key data.
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.FromXmlString(privateKey);

                byte[] encryptedData;
                byte[] decryptedData;
                encryptedData = Convert.FromBase64String(base64code);

                //Pass the data to DECRYPT, the private key information
                //(using RSACryptoServiceProvider.ExportParameters(true),
                //and a boolean flag specifying no OAEP padding.
                decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);

                //Display the decrypted plaintext to the console.
                return ByteConverter.GetString(decryptedData);
            }
            catch (Exception exc)
            {
                //Exceptions.LogException(exc);
                Console.WriteLine(exc.Message);
                return "";
            }
        }
Пример #23
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();
            }
        }
Пример #24
0
        private void SaveAsHTMLData(byte[] _reportBytes)
        {
            string _hz = "html";

            System.Text.Encoding        _encode   = System.Text.Encoding.Default;
            System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
            string reportString = converter.GetString(_reportBytes);
            string _lx          = reportString.Substring(0, 5);

            if (_lx == "MIME-")
            {
                _hz = "mht";
            }


            string _tempDir = Utils.ExeDir + "ReportTemp\\";

            if (!Directory.Exists(_tempDir))
            {
                Directory.CreateDirectory(_tempDir);
            }
            TempFileName = _tempDir + string.Format("temp{0}.{1}", Guid.NewGuid().ToString(), _hz);



            StreamWriter sw = new StreamWriter(TempFileName, false, _encode);

            sw.Write(reportString);
            sw.Close();
        }
Пример #25
0
        /// <summary>
        /// Triple DES Descrypt
        /// </summary>
        /// <param name="input">String to decrypt</param>
        /// <param name="key">Encryption Key</param>
        /// <returns></returns>
        public static string Decrypt(string input, string key)
        {
            TripleDESCryptoServiceProvider crp =new TripleDESCryptoServiceProvider();
            System.Text.UnicodeEncoding uEncode = new UnicodeEncoding();
            System.Text.ASCIIEncoding aEncode =new ASCIIEncoding();

            Byte[] bytCipherText = System.Convert.FromBase64String(input);
            MemoryStream stmPlainText =new MemoryStream();
            MemoryStream stmCipherText = new MemoryStream(bytCipherText);

            Byte[] slt= {0x12};

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, slt);
            Byte[] bytDerivedKey = pdb.GetBytes(24);
            crp.Key = bytDerivedKey;

            crp.IV = pdb.GetBytes(8);
            CryptoStream csDecrypted = new CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read);

            StreamWriter sw = new StreamWriter(stmPlainText);
            StreamReader sr = new StreamReader(csDecrypted);
            sw.Write(sr.ReadToEnd());

            sw.Flush();

            crp.Clear();

            return uEncode.GetString(stmPlainText.ToArray());
        }
Пример #26
0
 public static string AsSha512(string text)
 {
     var encode = new UnicodeEncoding();
     var bytPassword = encode.GetBytes(text);
     var hash = new SHA512Managed().ComputeHash(bytPassword);
     return encode.GetString(hash);
 }
        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);
            }
        }
Пример #28
0
 public void HashPassword()
 {
     const string password = "******";
     var algorithm = new SHA256Cng();
     var unicoding = new UnicodeEncoding();
     var hash = unicoding.GetString(algorithm.ComputeHash(unicoding.GetBytes(password)));
     Log(hash);
 }
Пример #29
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);
    }
Пример #30
0
        private String ReadUnicodeString()
        {
            int    len = ReadInt();
            String s   = UTF16.GetString(mBuffer, mBufferIndex, len);

            mBufferIndex += len;
            return(s);
        }
Пример #31
0
 //RSA的解密函数  string
 public string RSADecrypt(string privateKey, string m_strDecryptString)
 {
     UnicodeEncoding encoding = new UnicodeEncoding();
     RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
     provider.FromXmlString(privateKey);
     byte[] rgb = FromHex(m_strDecryptString);//Convert.FromBase64String(m_strDecryptString);
     byte[] bytes = provider.Decrypt(rgb, false);
     return encoding.GetString(bytes);
 }
Пример #32
0
//public static string ToUnicodetest(string str)
//    {
//        string temp1 = "";
//        string temp2 = "";
//        for (int i = 1; i < str.Length; i++)
//        {
//            temp2=Conversion.
//        }

//        for (int i = 0; i < bts.Length; i += 2) r += "\\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
//        return r;
//    }

    public static string test(string data)
    {
        string str = data;

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

        str = encodingUNICODE.GetString(new UnicodeEncoding().GetBytes(str));
        return(str);
    }
Пример #33
0
 public static void TextAndByte()
 {
     Console.WriteLine("text and byte");
     UnicodeEncoding converter = new UnicodeEncoding();
     string inputString = "hello world!!!";
     byte[] inputBytes = converter.GetBytes(inputString);
     string str = converter.GetString(inputBytes);
     string str64 = Convert.ToBase64String(inputBytes);
 }
Пример #34
0
 private static string ByteArrayToString(byte[] arr)
 {
     if (null == arr)
     {
         return(null);
     }
     System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
     return(enc.GetString(arr));
 }
        /// <summary>
        /// 测试 生成非对称密钥.
        /// </summary>
        public static void DoTest()
        {
            // Generate a public/private key pair.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            // 每当创建不对称算法类的新实例时,都生成一个公钥/私钥对。创建该类的新实例后,可以用以下两种方法之一提取密钥信息:
            // ToXMLString 方法,它返回密钥信息的 XML 表示形式。
            Console.WriteLine("仅仅包含公钥的情况!");
            Console.WriteLine(RSA.ToXmlString(false));

            Console.WriteLine("同时包含公钥与私钥的情况!");
            Console.WriteLine(RSA.ToXmlString(true));

            // ExportParameters 方法,它返回保存密钥信息的 RSAParameters 结构。
            // 将使用 RSACryptoServiceProvider 创建的密钥信息导出为 RSAParameters 对象。
            RSAParameters RSAKeyInfo = RSA.ExportParameters(false);

            // 取得目标的  公钥的  XML 信息.
            string xmlString = RSA.ToXmlString(false);

            // Create a UnicodeEncoder to convert between byte array and string.
            UnicodeEncoding ByteConverter = new UnicodeEncoding();

            string source = "Data to Encrypt  这个是一个用于测试加密的文本信息!";

            //Create byte arrays to hold original, encrypted, and decrypted data.
            byte[] dataToEncrypt = ByteConverter.GetBytes(source);
            byte[] encryptedData;

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

            // 这里创建一个新的  RSACryptoServiceProvider
            RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider();

            // 通过 XML 字符串中的密钥信息初始化 RSA 对象。
            RSA2.FromXmlString(xmlString);

            // 公钥加密.
            encryptedData = RSAEncrypt(dataToEncrypt, RSA2.ExportParameters(false), false);

            Console.WriteLine("公钥加密后的数据!");
            ByteArrayOutput.Print(encryptedData);

            byte[] decryptedData;

            // 解密
            decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);

            Console.WriteLine("私钥解密后的数据!");
            ByteArrayOutput.Print(decryptedData);

            // 输出.
            Console.WriteLine("私钥解密后的文本: {0}", ByteConverter.GetString(decryptedData));
        }
Пример #36
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));
        }
Пример #37
0
        /// <summary>
        /// Decrypts message
        /// </summary>
        /// <param name="cipher"></param>
        /// <returns></returns>
        public string Decrypt(byte[] cipher)
        {
            if (cipher is null)
            {
                throw new ArgumentNullException(nameof(cipher));
            }

            using ICryptoTransform transform = rijndael.CreateDecryptor();
            byte[] decryptedValue = transform.TransformFinalBlock(cipher, 0, cipher.Length);
            return(unicodeEncoding.GetString(decryptedValue));
        }
Пример #38
0
        private void ListenforBroadcasts()
        {
            while (true)
            {
                Byte [] array = udpClient.Receive(ref ep);

                UnicodeEncoding encoder = new UnicodeEncoding();
                System.Console.WriteLine(encoder.GetString(array));

            }
        }
Пример #39
0
    static void Main(string[] args)
    {
        IiopClientChannel channel = new IiopClientChannel();

        ChannelServices.RegisterChannel(channel, false);
        CorbaInit     init    = CorbaInit.GetInit();
        NamingContext context = init.GetNameService("MYLICSRV", 30000);

        NameComponent[] names = new NameComponent[] { new NameComponent("B1LicenseInfo") };
        ILicenseInfo    li    = (ILicenseInfo)context.resolve(names);

        byte[] hwKey;
        byte[] instNum;
        li.GetHardwareKey(out hwKey);
        li.GetInstallationNumberList(out instNum);
        Encoding encoding = new System.Text.UnicodeEncoding(false, false, true);

        Console.WriteLine(encoding.GetString(hwKey));
        Console.WriteLine(encoding.GetString(instNum));
    }
Пример #40
0
        static string Decrypt(byte[] encryptedData)
        {
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(privateKeyXML);
                byte[] decryptedData = RSA.Decrypt(encryptedData, false);

                UnicodeEncoding ByteConverter = new UnicodeEncoding();
                return ByteConverter.GetString(decryptedData);
            }
        }
Пример #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);
        }
Пример #42
0
        public static string ConvertAweString( IntPtr aweStr, bool shouldDestroy = false )
        {
            byte[] stringBytes = new byte[ awe_string_get_length( aweStr ) * 2 ];
            Marshal.Copy( awe_string_get_utf16( aweStr ), stringBytes, 0, (int)awe_string_get_length( aweStr ) * 2 );

            if ( shouldDestroy )
                awe_string_destroy( aweStr );

            UnicodeEncoding unicodeEncoding = new UnicodeEncoding();

            return unicodeEncoding.GetString( stringBytes );
        }
Пример #43
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));
    }
Пример #44
0
 /// <summary>
 /// Base64����
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public string DecodeBase64(string data)
 {
     try
     {
         UnicodeEncoding ByteConverter = new UnicodeEncoding();
         byte[] bytes = Convert.FromBase64String(data);
         return ByteConverter.GetString(bytes);
     }
     catch
     {
         return string.Empty;
     }
 }
Пример #45
0
        private static void RSAEncrypt2()
        {
            // RSA examples
            RSA rsa = new RSA();

            RSACryptoServiceProvider serviceProvider =
                new RSACryptoServiceProvider();
            //Export the key information to an RSAParameters object.
            //Pass false to export the public key information or pass
            //true to export public and private key information.
            //RSAParameters RSAParams = RSA.ExportParameters(false);

            //Encrypt data
            UnicodeEncoding bytConvertor = new UnicodeEncoding();
            byte[] plainData = bytConvertor.GetBytes("Sample data");

            byte[] enData = rsa.Encrypt(plainData, serviceProvider.ExportParameters(false));
            Console.WriteLine("Encrypted Output: {0}", bytConvertor.GetString(enData));

            byte[] deData = rsa.Decrypt(enData, serviceProvider.ExportParameters(true));
            Console.WriteLine("Decrypted Output: {0}", bytConvertor.GetString(deData));
        }
Пример #46
0
        public void PosTest3()
        {
            Char[] srcChars = GetCharArray(10);
            Char[] desChars = new Char[10];
            Byte[] bytes = new Byte[20];
            UnicodeEncoding uEncoding = new UnicodeEncoding();
            int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
            String expectedValue = "";
            String actualValue;

            actualValue = uEncoding.GetString(bytes, 0, 0);
            Assert.Equal(expectedValue, actualValue);
        }
Пример #47
0
        /// <summary>
        /// Décryptage des données
        /// </summary>
        /// <param name="strCipherText">Text crypté</param>
        /// <param name="strPrivateKey">Private key (décryption)</param>
        /// <returns>Retourne le texte décrypté</returns>
        public static string Decrypt(string strCipherText, string strPrivateKey)
        {
            // Decrypt a string using the private key
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            Byte[] bytPlainText;
            Byte[] bytCipherText;
             UnicodeEncoding uEncode = new UnicodeEncoding();
            rsa.FromXmlString(strPrivateKey);
            bytPlainText = uEncode.GetBytes(strCipherText);
            bytCipherText = rsa.Encrypt(bytPlainText, false);

            return (uEncode.GetString(bytPlainText));
        }
Пример #48
0
 public string ReadString(int Address, int length, bool isUnicode)
 {
     if (isUnicode)
     {
         UnicodeEncoding enc = new UnicodeEncoding();
         return enc.GetString(Read(Address, length));
     }
     else
     {
         ASCIIEncoding enc = new ASCIIEncoding();
         return enc.GetString(Read(Address, length));
     }
 }
Пример #49
0
        /// <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));
        }
Пример #50
0
 public static string GetPokemonString(byte[] ba)
 {
     System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
     byte[] stringb = new byte[1];
     for (int i = 0; i < ba.Length - 1; i += 2)
     {
         if (ba[i] == 0xff && ba[i + 1] == 0xff)
         {
             Array.Resize(ref stringb, i);
             Array.Copy(ba, stringb, i);
             break;
         }
     }
     return(enc.GetString(stringb));
 }
 static public int GetString__A_Byte(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         System.Byte[] a1;
         checkArray(l, 2, out a1);
         var ret = self.GetString(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);
        }
Пример #53
0
        public static string GetAnswer(List <Direction> moveSequence)
        {
            byte[] key = MoveSequenceToKey(moveSequence);

            AesManaged aes = new AesManaged();

            aes.Key = key;
            aes.IV  = PuzzleIV;
            ICryptoTransform decryptor = aes.CreateDecryptor();

            byte[] output = new byte[PuzzleAnswer.Length];
            decryptor.TransformBlock(PuzzleAnswer, 0, PuzzleAnswer.Length, output, 0);

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            return(encoding.GetString(output));
        }
Пример #54
0
        public unsafe void ByteArraySystemTextEncoding(Int32 numberIterations)
        {
            System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding();
            const int arraySize            = 8;
            byte *    b = stackalloc byte[arraySize];

            for (int i = 0; i < numberIterations; ++i)
            {
                int k = ChangeableStringParamStackParam(b, arraySize / 2);

                byte[] outBytes = new byte[arraySize];
                Marshal.Copy(new IntPtr(b), outBytes, 0, arraySize);

                string s = ue.GetString(outBytes);
            }
        }
Пример #55
0
        /// <summary>
        /// Decode encrypted data provided as Base64 string
        /// </summary>
        /// <param name="cypherText">The encoded data</param>
        /// <returns>The original string</returns>
        public string DecryptBase64AsString(string cypherText)
        {
            byte [] theBytes = System.Convert.FromBase64String(cypherText);

            string decryptedString = null;

            try
            {
                decryptedString = unienc.GetString(Decrypt(theBytes, null));
            }
            catch (System.Exception caught)
            {
                Log.Write(caught);
            }
            return(decryptedString);
        }
Пример #56
0
        private async void CreateButton_Click(object sender, RoutedEventArgs e)
        {
            byte[] bytesRead = new byte[totalBytes];
            using (MemoryStream memStream = new MemoryStream(totalBytes))
            {
                await memStream.WriteAsync(bytesToWrite, 0, bytesToWrite.Length);

                DataWriter writer = new DataWriter(memStream.AsOutputStream());
                writer.WriteBytes(bytesToAdd);
                await writer.StoreAsync();

                memStream.Seek(0, SeekOrigin.Begin);

                DataReader reader = new DataReader(memStream.AsInputStream());
                await reader.LoadAsync((uint)totalBytes);

                reader.ReadBytes(bytesRead);
                Results.Text = ue.GetString(bytesRead, 0, bytesRead.Length);
            }
        }
Пример #57
0
        /// <summary>
        /// Read text result from field-level xml
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadText(string filePath)
        {
            XDocument xDoc  = XDocument.Load(filePath);
            var       ns    = xDoc.Root.GetDefaultNamespace();
            var       field = xDoc.Root.Element(ns + "field");

            var    value  = field.Element(ns + "value");
            string result = value.Value;

            var xEncoding = value.Attribute("encoding");

            if (xEncoding != null && xEncoding.Value.ToLower() == "base64")
            {
                byte[] bytes = Convert.FromBase64String(result);

                System.Text.Encoding encoding = new System.Text.UnicodeEncoding();
                result = encoding.GetString(bytes);
            }

            return(result);
        }
Пример #58
0
        static protected string DecodeString(ushort PlatID, ushort EncID, byte [] EncodedStringBuf)
        {
            string s = null;

            if (PlatID == 0) // unicode
            {
                System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(true, false);
                s = ue.GetString(EncodedStringBuf);
            }
            else if (PlatID == 1) // Mac
            {
                int nMacCodePage = MacEncIdToCodePage(EncID);
                if (nMacCodePage != -1)
                {
                    s = GetUnicodeStrFromCodePageBuf(EncodedStringBuf, nMacCodePage);
                }
            }
            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);
                    s = ue.GetString(EncodedStringBuf);
                }
                else if (EncID >= 2 && EncID <= 6)
                {
                    int nCodePage = MSEncIdToCodePage(EncID);
                    s = GetUnicodeStrFromCodePageBuf(EncodedStringBuf, nCodePage);
                }
                else
                {
                    //Debug.Assert(false, "unsupported text encoding");
                }
            }

            return(s);
        }
Пример #59
0
        /// <summary>
        /// Reads a string. It is assumed that string bytes is next in the stream.
        /// </summary>
        public string ReadFixedSizeString(int Size, EStringType Type)
        {
            string str;

            if (Type == EStringType.ANSI)
            {
                byte[] bytes = ReadBytes(Size);
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                str = encoding.GetString(bytes);
            }
            else if (Type == EStringType.Unicode)
            {
                byte[] bytes = ReadBytes(Size);
                System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                str = encoding.GetString(bytes);
            }
            else
            {
                str = "";
            }

            return(str);
        }
Пример #60
0
    public void FillFromBytes(SqlBytes value)
    {
        if (value.IsNull)
        {
            m_fNotNull   = false;
            m_firstline  = SqlString.Null;
            m_secondline = SqlString.Null;
            return;
        }

        System.Text.UnicodeEncoding e = new System.Text.UnicodeEncoding();
        string str = e.GetString(value.Buffer);

        string[] twolines  = new string[2];
        char[]   seperator = { '|' };
        twolines = str.Split(seperator);

        m_firstline  = twolines[0];
        m_secondline = twolines.Length > 1 ? twolines[1] : SqlString.Null;
        m_fNotNull   = true;

        return;
    }