/// <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))); } }
/// <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))); }
public ActionResult LoginSubmit(String email, String password) { if (Session["user"] == null) { var unicodeCoder = new System.Text.UnicodeEncoding(); var byteEncodedPassword = unicodeCoder.GetBytes(password); var byteHashPassword = new System.Security.Cryptography.SHA256Managed().ComputeHash(byteEncodedPassword); password = Convert.ToBase64String(byteHashPassword); User user = db.Users.SingleOrDefault(s => s.Email == email && s.Password == password && s.Status == true); if (user != null) { Session["user"] = user; Session["role"] = user.Role; Session["email"] = user.Email; Session["userId"] = user.Id; Session["username"] = user.FirstName; } else { return(RedirectToAction("Login")); } } return(RedirectToAction("Index")); }
private static string convertToUnicode(char ch) { System.Text.UnicodeEncoding class1 = new System.Text.UnicodeEncoding(); byte[] msg = class1.GetBytes(System.Convert.ToString(ch)); return(fourDigits(msg[1] + msg[0].ToString("X"))); }
/** * Constructor * * @param pw the password */ public PasswordRecord(string pw) : base(Type.PASSWORD) { password = pw; if (pw == null) { data = new byte[2]; IntegerHelper.getTwoBytes(0, data, 0); } else { // System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding(); System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] passwordBytes = encoder.GetBytes(pw); int passwordHash = 0; for (int a = 0; a < passwordBytes.Length; a++) { int shifted = rotLeft15Bit(passwordBytes[a], a + 1); passwordHash ^= shifted; } passwordHash ^= passwordBytes.Length; passwordHash ^= 0xCE4B; data = new byte[2]; IntegerHelper.getTwoBytes(passwordHash, data, 0); } }
public void AddTo(CodeGen code_gen, PEAPI.MetaDataElement elem) { System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); foreach (DictionaryEntry entry in permissionset_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key; SSPermissionSet ps = (SSPermissionSet)entry.Value; code_gen.PEFile.AddDeclSecurity(sec_action, ue.GetBytes(ps.ToXml().ToString()), elem); } if (permissionset20_table == null) { return; } foreach (DictionaryEntry entry in permissionset20_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key; MIPermissionSet ps = (MIPermissionSet)entry.Value; code_gen.PEFile.AddDeclSecurity(sec_action, ps.Resolve(code_gen), elem); } }
/// <summary> /// Allocates a string on the uWebKit memory paging system /// </summary> public static int AllocateString(string value, ref int size) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); Byte[] bytes = encoding.GetBytes(value); Byte[] nbytes = new Byte[bytes.Length + 2]; Array.Copy(bytes, nbytes, bytes.Length); nbytes[bytes.Length] = 0; nbytes[bytes.Length + 1] = 0; GCHandle pinned = GCHandle.Alloc(nbytes, GCHandleType.Pinned); int i = UWK_AllocateAndCopy(pinned.AddrOfPinnedObject(), nbytes.Length); pinned.Free(); size = nbytes.Length; if (i < 0) { throw new Exception("Error Allocating String"); } return(i); }
/// <summary> /// A function that is called when pressing "Save txt" button. /// It starts an new windows object of type SaveFileDialog. /// It saves a list of Points in format: "Point: (x, F(x)) \n" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TextSaveGraph(object sender, EventArgs e) { System.Text.UnicodeEncoding uniEncoding = new System.Text.UnicodeEncoding(); Stream streamToSaveText = new MemoryStream(); SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; saveDialog.FilterIndex = 1; saveDialog.RestoreDirectory = true; String points = ""; for (float x = xMin; x <= xMax; x = x + counter) { points += "Point: (" + Math.Round(x, 2) + ", " + Math.Round(F(x), 2) + ")\n"; } byte[] messageBytes = uniEncoding.GetBytes(points); if (saveDialog.ShowDialog() == DialogResult.OK) { if ((streamToSaveText = saveDialog.OpenFile()) != null) { streamToSaveText.Write(messageBytes, 0, messageBytes.Length); streamToSaveText.Position = 0; streamToSaveText.Close(); } } }
public void AddTo (CodeGen code_gen, PEAPI.MetaDataElement elem) { System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding (); foreach (DictionaryEntry entry in permissionset_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction) entry.Key; SSPermissionSet ps = (SSPermissionSet) entry.Value; code_gen.PEFile.AddDeclSecurity (sec_action, ue.GetBytes (ps.ToXml ().ToString ()), elem); } if (permissionset20_table == null) return; foreach (DictionaryEntry entry in permissionset20_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction) entry.Key; MIPermissionSet ps = (MIPermissionSet) entry.Value; code_gen.PEFile.AddDeclSecurity (sec_action, ps.Resolve (code_gen), elem); } }
private string convertUnicodeToASCII(string value) { System.Text.ASCIIEncoding encodingASCII = new System.Text.ASCIIEncoding(); System.Text.UnicodeEncoding encodingUNICODE = new System.Text.UnicodeEncoding(); byte[] sampleTextEncoded = encodingUNICODE.GetBytes(value); return(HttpUtility.UrlEncode(encodingASCII.GetString(sampleTextEncoded))); }
public void RunThread(object Obj) { object[] ObjArray = (object[])Obj; Uri url = (Uri)ObjArray[0]; string requestString = (string)ObjArray[1]; string responseString = (string)ObjArray[2]; WebHeaderCollection headerCollection = (WebHeaderCollection)ObjArray[3]; var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Headers = headerCollection; request.BeginGetRequestStream((s) => { var req = (HttpWebRequest)s.AsyncState; var str = req.EndGetRequestStream(s); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); Byte[] bytes = encoding.GetBytes(responseString); str.Write(bytes, 0, bytes.Length); str.Close(); req.BeginGetResponse((k) => { var req2 = (HttpWebRequest)k.AsyncState; var resp = (HttpWebResponse)req2.EndGetResponse(k); byte[] bytes2 = ReadFully(resp.GetResponseStream()); string res = System.Text.Encoding.Unicode.GetString(bytes2); }, req); }, null); if (RunComleted != null) { RunCompleted(res); } }
internal static string Serialize <T>(IList <T> info) { // serialize data var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); var serializer = new XmlSerializer(info.GetType(), new XmlRootAttribute("ROOT")); var settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }; try { using (var stream = new StringWriter()) { using (var writer = XmlWriter.Create(stream, settings)) { serializer.Serialize(writer, info, emptyNamepsaces); var encoding = new System.Text.UnicodeEncoding(); byte[] bytestosend = encoding.GetBytes(stream.ToString()); string sText = encoding.GetString(bytestosend); return(sText); } } } catch (Exception ex) { Logger.Error(ex); throw; } }
private static void WriteString(FileStream f, string s) { // if (!s.EndsWith ("\n")) // s += "\n"; byte[] bfr = Utf16.GetBytes(s); f.Write(bfr, 0, bfr.Length); }
private void WriteToStream(Stream stream, string msg) { if (stream != null) { stream.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg)); } }
static bool GetSiteNameFromISAPI() { Debug.Trace("config_loc", "GetSiteNameFromISAPI()"); HttpContext context = HttpContext.Current; if (context != null) { string metabaseAppKey = context.Request.ServerVariables["INSTANCE_META_PATH"]; const string KEY_LMW3SVC = "/LM/W3SVC/"; Debug.Assert(metabaseAppKey.StartsWith(KEY_LMW3SVC)); string appNumber = metabaseAppKey.Substring(KEY_LMW3SVC.Length - 1); //string appServerComment = "/" + appNumber + "/ServerComment"; Debug.Trace("config_loc", "appNumber:" + appNumber + " INSTANCE_META_PATH:" + metabaseAppKey); UnicodeEncoding encoding = new UnicodeEncoding(); // null-terminate appNumber and convert to byte array byte [] byteAppNumber = encoding.GetBytes(appNumber + "\0"); int retVal = 2; byte [] outBytes = new byte[64]; while (retVal == 2) { retVal = context.CallISAPI(UnsafeNativeMethods.CallISAPIFunc.GetSiteServerComment, byteAppNumber, outBytes); if (retVal == 2) { if (outBytes.Length > 1024) // should never happen { throw new ConfigurationException(HttpRuntime.FormatResourceString( SR.Config_site_name_too_long, metabaseAppKey)); } outBytes = new byte[outBytes.Length * 2]; } } // find WCHAR null terminator in byte array int i = 0; while (i + 1 < outBytes.Length && (outBytes[i] != 0 || outBytes[i + 1] != 0)) { i += 2; } // decode up to null terminator s_siteName = encoding.GetString(outBytes, 0, i); Debug.Trace("config_loc", "i: " + i + " site name:" + s_siteName); return(true); } else { Debug.Trace("config_loc", "could not query site name. No Context."); } return(false); // keep trying to evaluate }
public ArrayList CreateNewCharContainer(bool lowerCaseLetters, bool capitals, bool peculiar, bool numbers, bool ownCharacters, string myCharacters) { if (lowerCaseLetters) { for (int i = 97; i < 123; i++) { charContainer.Add((char)i); } } if (capitals) { for (int i = 65; i < 91; i++) { charContainer.Add((char)i); } } if (peculiar) { for (int i = 32; i < 48; i++) { charContainer.Add((char)i); } for (int i = 58; i < 65; i++) { charContainer.Add((char)i); } for (int i = 91; i < 97; i++) { charContainer.Add((char)i); } charContainer.Add((char)123); charContainer.Add((char)124); charContainer.Add((char)125); charContainer.Add((char)126); } if (numbers) { for (int i = 48; i < 58; i++) { charContainer.Add((char)i); } } if (ownCharacters) { System.Text.UnicodeEncoding unicode = new System.Text.UnicodeEncoding(); char[] characters = unicode.GetChars(unicode.GetBytes(myCharacters)); for (int i = 0; i < characters.Length; i++) { if (!charContainer.Contains(characters[i])) { charContainer.Add(characters[i]); } } } return(charContainer); }
public static string Encrypt(string pData) { System.Text.UnicodeEncoding parser = new System.Text.UnicodeEncoding(); byte[] _original = parser.GetBytes(pData); MD5CryptoServiceProvider Hash = new MD5CryptoServiceProvider(); byte[] _encrypt = Hash.ComputeHash(_original); return(Convert.ToBase64String(_encrypt)); }
public byte[] KeyGenerator(string AndroidKey) { SecureRandom sr = SecureRandom.GetInstance("SHA1PRNG"); var encoder = new System.Text.UnicodeEncoding(); var b = encoder.GetBytes (AndroidKey); // use key sr.SetSeed(encoder.GetBytes(AndroidKey)); return encoder.GetBytes (AndroidKey); // Cipher c = Cipher.GetInstance("AES"); // c.Init(CipherMode.EncryptMode, // KeyGenerator kg = KeyGenerator.GetInstance("AES"); // kg.Init(128, sr); // return new SecretKeySpec (kg.GenerateKey ().GetEncoded (), "AES").GetEncoded (); }
public byte[] KeyGenerator(string AndroidKey) { SecureRandom sr = SecureRandom.GetInstance("SHA1PRNG"); var encoder = new System.Text.UnicodeEncoding(); var b = encoder.GetBytes(AndroidKey); // use key sr.SetSeed(encoder.GetBytes(AndroidKey)); return(encoder.GetBytes(AndroidKey)); // Cipher c = Cipher.GetInstance("AES"); // c.Init(CipherMode.EncryptMode, // KeyGenerator kg = KeyGenerator.GetInstance("AES"); // kg.Init(128, sr); // return new SecretKeySpec (kg.GenerateKey ().GetEncoded (), "AES").GetEncoded (); }
public void GetStringFromUnicodeArrayTest() { string expected = "Test!"; System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); var self = encoding.GetBytes(expected); var actual = self.GetStringFromArray(EncodingType.Unicode); Assert.AreEqual(expected, actual); }
/// <summary> /// Sets the commands index parameter to the specified string /// </summary> public void SetSParam(int index, string value) { int startIndex = index * 256 * 2; System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); Byte[] bytes = encoding.GetBytes(value); Array.Copy(bytes, 0, sParams, startIndex, bytes.Length); sParams[startIndex + bytes.Length] = 0; sParams[startIndex + bytes.Length + 1] = 0; }
/// <summary>Utility function to convert a string to a byte array</summary> public static byte[] StringToBytes(string message) { if (message.Length <= 0) { return(new byte[0]); } System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); return(encoderUnicode.GetBytes(message)); }
/// <summary> /// Renames the replays' internal name /// </summary> /// <param name="newName">New name to use for the replay</param> public bool RenameReplay(Replay replay, string newName) { try { //load the replay data FileStream fsreader = File.OpenRead(replay.Filename); byte[] data = new byte[fsreader.Length]; fsreader.Read(data, 0, data.Length); fsreader.Close(); //create a buffer for the adjusted file int new_replaysize = replay.FileSize + ((newName.Length - replay.Name.Length) * 2); byte[] buffer = new byte[new_replaysize]; System.IO.MemoryStream writer = new MemoryStream(buffer); //calculate the new db & foldinfo len int database_len = replay.DATABASE + ((newName.Length - replay.Name.Length) * 2); int foldinfo_len = replay.FOLDINFO + ((newName.Length - replay.Name.Length) * 2); //write everything into the new buffer up to the foldinfo len writer.Write(data, 0, replay.FOLDINFOPOS); byte[] foldinfo_byte = BitConverter.GetBytes(foldinfo_len); writer.Write(foldinfo_byte, 0, foldinfo_byte.Length); writer.Write(data, replay.FOLDINFOPOS + 4, (replay.DATABASEPOS - replay.FOLDINFOPOS - 4)); byte[] database_byte = BitConverter.GetBytes(database_len); writer.Write(database_byte, 0, database_byte.Length); writer.Write(data, replay.DATABASEPOS + 4, (replay.REPLAYLENPOS - replay.DATABASEPOS - 4)); byte[] replay_byte = BitConverter.GetBytes(newName.Length); writer.Write(replay_byte, 0, replay_byte.Length); //get the new name in bytes System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] byte_name = encoder.GetBytes(newName); writer.Write(byte_name, 0, byte_name.Length); writer.Write(data, (replay.REPLAYLENPOS + 4 + (replay.Name.Length * 2)), (replay.FileSize - ((replay.REPLAYLENPOS + 4) + replay.Name.Length * 2))); writer.Close(); BinaryWriter binwriter = new BinaryWriter(File.Create(replay.Filename)); binwriter.Write(buffer); binwriter.Close(); return(true); } catch { return(false); } }
/// <summary> /// Mã hóa password /// </summary> protected string EncryptPassword(string Password) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); byte[] hashBytes = encoding.GetBytes(Password); //Compute the SHA-1 hash SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] cryptPassword = sha1.ComputeHash(hashBytes); return(BitConverter.ToString(cryptPassword)); }
/// <summary> /// Encrypt /// </summary> public static string EncryptString(string plainText, string passPhrase = null) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); byte[] input = encoding.GetBytes(plainText); byte[] output = new byte[input.Length]; for (int i = 0; i < input.Length; i++) { output[i] = (byte)(input[i] ^ key); } return(StringUtil.EncodeTo64(output)); }
public string GetHash(string password, string salt) { string passwordHash; string source = salt + password; var encoder = new System.Text.UnicodeEncoding(); byte[] bytes = encoder.GetBytes(source); using (var cryptoProvider = new SHA256CryptoServiceProvider()) { byte[] hash = cryptoProvider.ComputeHash(bytes); passwordHash = Convert.ToBase64String(hash); } return(passwordHash); }
public bool setFileName(string sFileName) { bool bResult = true; System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); if (ue.GetByteCount(sFileName) != 6) { bResult = false; throw new ArrayTypeMismatchException("FileName is should have a length of 6 characters."); } m_FileName = ue.GetBytes(sFileName); return(bResult); }
/// <summary> /// Encode data given as string, return as Base64d byte array /// </summary> /// <param name="plainText">The string to be encoded</param> /// <returns>The resulting encoded string</returns> public string EncryptStringToBase64(string plainText) { byte [] theBytes = unienc.GetBytes(plainText); string encryptedString = null; try { encryptedString = System.Convert.ToBase64String(Encrypt(theBytes, null)); } catch (System.Exception caught) { Log.Write(caught); } return(encryptedString); }
public bool setCharacterComplement(string sCharacterComplement) { bool bResult = true; System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); if (ue.GetByteCount(sCharacterComplement) != 8) { bResult = false; throw new ArrayTypeMismatchException("CharacterComplement should have a length of 8 characters."); } m_CharacterComplement = ue.GetBytes(sCharacterComplement); return(bResult); }
public Encrypt Encode(EncryptType type, string value) { var result = new Encrypt(); result.Value = null; result.Type = type; if (type == EncryptType.OK) { try { var key = AES; if (key != null) { result.Key = key; Cipher c = Cipher.GetInstance("AES"); c.Init(CipherMode.EncryptMode, key as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return(result); } } catch (Exception) { return(null); } } else if (type == EncryptType.STRONG) { try { var keys = RSA; if (keys != null) { result.PublicKey = keys[1]; result.PrivateKey = keys[0]; Cipher c = Cipher.GetInstance("RSA"); c.Init(Javax.Crypto.CipherMode.EncryptMode, result.PublicKey as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return(result); } } catch (Exception) { return(null); } } return(null); }
public ActionResult Create([Bind(Include = "Id,FirstName,LastName,Email,Password,TokenAmount,Status,Role")] User user) { if (ModelState.IsValid) { var password = user.Password; var unicodeCoder = new System.Text.UnicodeEncoding(); var byteEncodedPassword = unicodeCoder.GetBytes(password); var byteHashPassword = new System.Security.Cryptography.SHA256Managed().ComputeHash(byteEncodedPassword); password = Convert.ToBase64String(byteHashPassword); user.Password = password; db.Users.Add(user); db.SaveChanges(); return(RedirectToAction("Index", "Home")); } return(View(user)); }
/// <summary> /// This function is deprecated in favor of Plugin.GetString and Plugin.AllocateString /// </summary> public void SpanSParams(int startIndex, string s) { numSParams = startIndex; for (int i = 0; i < s.Length;) { string ss = s.Substring(i, s.Length - i < 250 ? s.Length - i : 250); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); Byte[] bytes = encoding.GetBytes(ss); int idx = numSParams * 256 * 2; Array.Copy(bytes, 0, sParams, idx, bytes.Length); sParams[idx + bytes.Length] = 0; sParams[idx + bytes.Length + 1] = 0; numSParams++; i += 250; } }
/// <summary> /// Allocates a string on the uWebKit memory paging system /// </summary> public static int AllocateString(string value, ref int size) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); Byte[] bytes = encoding.GetBytes (value); Byte[] nbytes = new Byte[bytes.Length + 2]; Array.Copy (bytes, nbytes, bytes.Length); nbytes[bytes.Length] = 0; nbytes[bytes.Length + 1] = 0; GCHandle pinned = GCHandle.Alloc (nbytes, GCHandleType.Pinned); int i = UWK_AllocateAndCopy (pinned.AddrOfPinnedObject (), nbytes.Length); pinned.Free (); size = nbytes.Length; if (i < 0) throw new Exception ("Error Allocating String"); return i; }
/// <summary> /// Sets the commands index parameter to the specified string /// </summary> public void SetSParam(int index, string value) { int startIndex = index * 256 * 2; System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); Byte[] bytes = encoding.GetBytes (value); Array.Copy (bytes, 0, sParams, startIndex, bytes.Length); sParams[startIndex + bytes.Length] = 0; sParams[startIndex + bytes.Length + 1] = 0; }
/// <summary> /// This function is deprecated in favor of Plugin.GetString and Plugin.AllocateString /// </summary> public void SpanSParams(int startIndex, string s) { numSParams = startIndex; for (int i = 0; i < s.Length;) { string ss = s.Substring (i, s.Length - i < 250 ? s.Length - i : 250); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); Byte[] bytes = encoding.GetBytes (ss); int idx = numSParams * 256 * 2; Array.Copy (bytes, 0, sParams, idx, bytes.Length); sParams[idx + bytes.Length] = 0; sParams[idx + bytes.Length + 1] = 0; numSParams++; i += 250; } }
/// <summary> /// Renames the replays' internal name /// </summary> /// <param name="newName">New name to use for the replay</param> public bool RenameReplay(Replay replay, string newName) { try { //load the replay data FileStream fsreader = File.OpenRead(replay.Filename); byte[] data = new byte[fsreader.Length]; fsreader.Read(data, 0, data.Length); fsreader.Close(); //create a buffer for the adjusted file int new_replaysize = replay.FileSize + ((newName.Length - replay.Name.Length) * 2); byte[] buffer = new byte[new_replaysize]; System.IO.MemoryStream writer = new MemoryStream(buffer); //calculate the new db & foldinfo len int database_len = replay.DATABASE + ((newName.Length - replay.Name.Length) * 2); int foldinfo_len = replay.FOLDINFO + ((newName.Length - replay.Name.Length) * 2); //write everything into the new buffer up to the foldinfo len writer.Write(data, 0, replay.FOLDINFOPOS); byte[] foldinfo_byte = BitConverter.GetBytes(foldinfo_len); writer.Write(foldinfo_byte, 0, foldinfo_byte.Length); writer.Write(data, replay.FOLDINFOPOS + 4, (replay.DATABASEPOS - replay.FOLDINFOPOS - 4)); byte[] database_byte = BitConverter.GetBytes(database_len); writer.Write(database_byte, 0, database_byte.Length); writer.Write(data, replay.DATABASEPOS + 4, (replay.REPLAYLENPOS - replay.DATABASEPOS - 4)); byte[] replay_byte = BitConverter.GetBytes(newName.Length); writer.Write(replay_byte, 0, replay_byte.Length); //get the new name in bytes System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] byte_name = encoder.GetBytes(newName); writer.Write(byte_name, 0, byte_name.Length); writer.Write(data, (replay.REPLAYLENPOS + 4 + (replay.Name.Length * 2)), (replay.FileSize - ((replay.REPLAYLENPOS + 4) + replay.Name.Length * 2))); writer.Close(); BinaryWriter binwriter = new BinaryWriter(File.Create(replay.Filename)); binwriter.Write(buffer); binwriter.Close(); return true; } catch { return false; } }
public bool setFileName( string sFileName ) { bool bResult = true; System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); if( ue.GetByteCount( sFileName ) != 6 ) { bResult = false; throw new ArrayTypeMismatchException( "FileName is should have a length of 6 characters." ); } m_FileName = ue.GetBytes( sFileName ); return bResult; }
public bool setCharacterComplement( string sCharacterComplement ) { bool bResult = true; System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); if( ue.GetByteCount( sCharacterComplement ) != 8 ) { bResult = false; throw new ArrayTypeMismatchException( "CharacterComplement should have a length of 8 characters." ); } m_CharacterComplement = ue.GetBytes( sCharacterComplement ); return bResult; }
public static string Contrasenia_Cryp_MD5(string texto) { byte[] resultadomd5; byte[] qsstrbytearray; int indice; System.Text.UnicodeEncoding codificacion = new System.Text.UnicodeEncoding(); System.Security.Cryptography.MD5CryptoServiceProvider varmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); string codstr = ""; string ret = ""; if (texto == "") ret = ""; else { qsstrbytearray = codificacion.GetBytes(texto); resultadomd5 = varmd5.ComputeHash(qsstrbytearray); for (indice = 0; indice < resultadomd5.Length; indice++) { string tmp = resultadomd5[indice].ToString("X"); if (tmp.Length == 1) codstr += "0"; codstr += tmp; } ret = codstr; } return ret; }
private UInt32 Update( string FullPathToFile ) { unchecked { // Creates an encoder that will map each Unicode character to 2 bytes System.Text.UnicodeEncoding myEncoder = new System.Text.UnicodeEncoding(); // Include file name only, strip off path information // This is done so we get the same CRC no matter if the CD is in drive G // on one machine and drive F on another, kappish? int index = FullPathToFile.LastIndexOf( '\\' ); string strFileName = FullPathToFile.Substring( index + 1 ); // Convert file name to byte array int count = myEncoder.GetByteCount( strFileName ); byte[] buffer = new byte[count]; buffer = myEncoder.GetBytes(strFileName); UInt32 crc = HighBitMask; //ProcessBuffer( ref buffer, ref crc ); for (int i = 0; i < count; i++) crc = ((crc) >> 8) ^ CRCTable[(buffer[i]) ^ ((crc) & 0x000000FF)]; crc = ~crc; LifetimeCRC ^= crc; return crc; } }
public Encrypt Encode(EncryptType type, string value) { var result = new Encrypt (); result.Value = null; result.Type = type; if (type == EncryptType.OK) { try { var key = AES; if (key != null) { result.Key = key; Cipher c = Cipher.GetInstance("AES"); c.Init(CipherMode.EncryptMode, key as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } else if (type == EncryptType.STRONG) { try { var keys = RSA; if (keys != null) { result.PublicKey = keys[1]; result.PrivateKey = keys[0]; Cipher c = Cipher.GetInstance ("RSA"); c.Init(Javax.Crypto.CipherMode.EncryptMode, result.PublicKey as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal (encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } return null; }