Exemplo n.º 1
0
        /// <summary>
        ///   One-way transformation.  The spec says that the password must be
        ///   padded with blanks, Samba does it iwth 0 ???
        ///   <para>OWF = Ex(P14, S8)</para>
        /// </summary>
        /// <param name = "password">password</param>
        /// <returns>byte[16]</returns>
        internal static byte[] GetLmOwf(string password)
        {
            var p14 = new byte[14];

            password = password.ToUpper();
            for (int i = 0; i < password.Length; i++)
            {
                p14[i] = (byte)(password[i] & 0xff);
            }


            var s16  = new byte[16];
            var key7 = new byte[7];
            var key8 = new byte[8];
            var e8   = new byte[8];

            for (int i = 0; i < 2; i++)
            {
                Array.Copy(p14, 7 * i, key7, 0, 7);
                Des.MakeSmbKey(key7, key8);

                var des = new Des(key8);

                des.Encrypt(S8, e8);

                Array.Copy(e8, 0, s16, 8 * i, 8);
            }

            return(s16);
        }
Exemplo n.º 2
0
        public JsonResponse FastJson(object data, string token = "", int retCode = 0, string retMsg = "请求成功", int retCnt = 0, string reqHash = "")
        {
            try
            {
                if (ConfigUtil.Isdebug)
                {
                    data = data.SerializeObject();
                }
                else
                {
                    data = Des.Encrypt(data.SerializeObject(), TokenHelper.GetKeyByToken(token, 8));
                }

                return(new JsonResponse()
                {
                    Code = retCode, Count = retCnt, Msg = retMsg, Data = data
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex, "basecontroller/fastjson");
                return(new JsonResponse()
                {
                    Code = 1, Msg = "程序错误" + ex.Message
                });
            }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            string message = "TSITSIRI";

            ulong key = 0xF46E986435465354;

            Des.Encrypt(message, key);
        }
Exemplo n.º 4
0
        public IActionResult GrantTicket(AuthRequest request)
        {
            Log.Information("Step #3. Received a Ticket Grant request: {@Request}", request);
            var tgsKey = _keyManager.Keys["tgs"];

            if (!_keyManager.Keys.TryGetValue(request.Recepient, out var recepientKey))
            {
                Log.Error("Requested recepient '{Recepient}' was not registered yet", request.Recepient);
                throw new ArgumentException();
            }
            Log.Information("Step #4.1. Found requested recepient '{Recepient}' in the registered list with key {Key}", request.Recepient, Encoding.UTF8.GetString(recepientKey));

            var ticketGrantingTicket = Des.Decrypt <Ticket>(tgsKey, request.EncryptedTicket);

            Log.Information("Step #4.2. Decrypted the Ticket Granting Ticket using the [AuthServer <-> TGS] key: {@Ticket}", ticketGrantingTicket);

            var clientToTgsKey = ticketGrantingTicket.Key;

            Log.Information("Step #4.3. Got a session key ['{Login}' <-> TGS] from TGT: {Key}", ticketGrantingTicket.From, Encoding.UTF8.GetString(ticketGrantingTicket.Key));

            var authBlock = Des.Decrypt <AuthBlock>(clientToTgsKey, request.EncryptedAuthBlock);

            Log.Information("Step #4.4. Decrypted the Auth Block using ['{Login}' <-> TGS] key: {@AuthBlock}", authBlock.Login, authBlock);

            if (!ticketGrantingTicket.From.Equals(authBlock.Login, System.StringComparison.OrdinalIgnoreCase) ||
                ticketGrantingTicket.Timestamp + ticketGrantingTicket.Expiration < authBlock.Timestamp)
            {
                Log.Warning("Names in two blocks are not equal or the TGT has expired");
                return(NotFound());
            }
            Log.Information("Step #4.5. Verified the data of two blocks and the ticket expiration time");

            var ticket = new Ticket
            {
                From       = authBlock.Login,
                To         = request.Recepient,
                Key        = KeyManager.GenerateSessionKey(),
                Timestamp  = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
                Expiration = 300
            };

            Log.Information("Step #4.6. Build new ticket with newly generated session key [{From} <-> {To}]: {@Ticket}", ticket.From, ticket.To, ticket);

            var authResponse = new AuthResponse
            {
                EncryptedTicket = Des.Encrypt(recepientKey, ticket),
                Key             = ticket.Key
            };

            Log.Information("Step #4.7. Encrypt the ticket using [Auth Server <-> {To}] key and pack it up into the response: {@Response}", ticket.To, authResponse);

            var encryptedResponse = Des.Encrypt(clientToTgsKey, authResponse);

            Log.Information("Step #4.8. Encrypt the message before sending using the [{From} <-> TGS] key", ticket.From);

            return(Ok(Convert.ToBase64String(encryptedResponse)));
        }
Exemplo n.º 5
0
 /// <summary>
 /// token 加密数据
 /// </summary>
 /// <param name="encrydata"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 public static string TokenEncry(string encrydata, string token)
 {
     try
     {
         if (string.IsNullOrEmpty(encrydata) || string.IsNullOrEmpty(token))
         {
             return(string.Empty);
         }
         string key = GetKeyByToken(token, 8);
         return(Des.Encrypt(encrydata, key));
     }
     catch
     {
         return(string.Empty);
     }
 }
Exemplo n.º 6
0
        private static void E_P24(byte[] p21, byte[] c8, byte[] p24)
        {
            var key7 = new byte[7];
            var key8 = new byte[8];
            var e8   = new byte[8];

            for (int i = 0; i < 3; i++)
            {
                Array.Copy(p21, 7 * i, key7, 0, 7);
                Des.MakeSmbKey(key7, key8);

                var des = new Des(key8);

                des.Encrypt(c8, e8);

                Array.Copy(e8, 0, p24, 8 * i, 8);
            }
        }
Exemplo n.º 7
0
        private static void E_P16(byte[] p14, byte[] p16)
        {
            var key7 = new byte[7];
            var key8 = new byte[8];
            var e8   = new byte[8];

            for (int i = 0; i < 2; i++)
            {
                Array.Copy(p14, 7 * i, key7, 0, 7);

                Des.MakeSmbKey(key7, key8);

                var des = new Des(key8);
                des.Encrypt(S8, e8);

                Array.Copy(e8, 0, p16, 8 * i, 8);
            }
        }
Exemplo n.º 8
0
        public IActionResult Auth([FromForm] string login)
        {
            Log.Information("Step #1. Received an authentication request from '{Login}'", login);
            if (!_keyManager.Keys.ContainsKey(login))
            {
                return(NotFound());
            }

            var sessionKey = KeyManager.GenerateSessionKey();

            Log.Information("Step #2.1. Generate a session key [{Login} <-> TGS]: {Key}", login, Encoding.UTF8.GetString(sessionKey));
            var ticket = new Ticket
            {
                From       = login,
                To         = "tgs",
                Key        = sessionKey,
                Timestamp  = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
                Expiration = 3600
            };

            Log.Information("Step #2.2. Make up a Ticket Granting Ticket: {@Ticket}", ticket);

            var tgsKey          = _keyManager.Keys["tgs"];
            var encryptedTicket = Des.Encrypt(tgsKey, ticket);

            Log.Information("Step #2.3. Encrypt the ticket using [AuthServer <-> TGS] key: {Key}", Encoding.UTF8.GetString(tgsKey));

            var authMessage = new AuthResponse
            {
                EncryptedTicket = encryptedTicket,
                Key             = sessionKey
            };

            Log.Information("Step #2.4. Build an authentication response message: {@AuthResponse}", authMessage);

            var encryptedMessage = Des.Encrypt(_keyManager.Keys[login], authMessage);

            Log.Information("Step #2.5. Encrypt the message using [{Login} <-> AuthServer] key before sending response", login);

            return(Ok(Convert.ToBase64String(encryptedMessage)));
        }
Exemplo n.º 9
0
        /// <summary>
        ///   Encrypts password
        /// </summary>
        /// <param name = "s21">Session key</param>
        /// <param name = "c8">challange</param>
        /// <returns>byte[24]</returns>
        internal static byte[] GetAuthData(byte[] s21, byte[] c8)
        {
            var key7 = new byte[7];
            var key8 = new byte[8];
            var e8   = new byte[8];
            var rn   = new byte[24];

            for (int i = 0; i < 3; i++)
            {
                Array.Copy(s21, 7 * i, key7, 0, 7);

                Des.MakeSmbKey(key7, key8);

                var des = new Des(key8);

                des.Encrypt(c8, e8);

                Array.Copy(e8, 0, rn, 8 * i, 8);
            }
            return(rn);
        }
Exemplo n.º 10
0
        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("");
        }
Exemplo n.º 11
0
        public IActionResult Auth(AuthRequest request)
        {
            Log.Information("Step #5.1. Received an authentication request: {@Request}", request);
            var tgsKey = _keyManager.Keys[Credentials.Login];

            var ticket = Des.Decrypt <Ticket>(tgsKey, request.EncryptedTicket);

            Log.Information("Step #5.2. Decrypted the ticket using the [server <-> TGS] key: {@Ticket}", ticket);

            var clientKey = ticket.Key;
            var authBlock = Des.Decrypt <AuthBlock>(clientKey, request.EncryptedAuthBlock);

            Log.Information("Step #5.3. Decrypted the auth block using the [server <-> client] session key: {@AuthBlock}", authBlock);

            if (!ticket.From.Equals(authBlock.Login, System.StringComparison.OrdinalIgnoreCase) ||
                ticket.Timestamp + ticket.Expiration < authBlock.Timestamp)
            {
                Log.Warning("Names in two blocks are not equal or the ticket has expired");
                return(NotFound());
            }
            Log.Information("Step #5.4. Successfully verified the identity of '{From}'", ticket.From);

            _keyManager.Keys.Add(ticket.From, clientKey);
            Log.Information("Step #5.5. Stored the session key for [server <-> client] conversation");

            var timestamp = authBlock.Timestamp + 1;

            Log.Information("Step #6.1. Incrementing the timestamp value by 1 to prove the server's identity: {Timestamp}", timestamp);

            var timestampWrapper = new TimestampWrapper {
                Timestamp = timestamp
            };
            var encryptedTimestamp = Des.Encrypt(clientKey, timestampWrapper);

            Log.Information("Step #6.2. Encrypting timestamp using the [server <-> client] session key");
            Log.Information("Step #6.3. Sending encrypted timestamp back to client");

            return(Ok(Convert.ToBase64String(encryptedTimestamp)));
        }
Exemplo n.º 12
0
        private static byte[] GetOldPwHash(byte[] p14key, byte[] in16)
        {
            var s16  = new byte[16];
            var key7 = new byte[7];
            var key8 = new byte[8];
            var e8   = new byte[8];
            var s8   = new byte[8];

            for (int i = 0; i < 2; i++)
            {
                Array.Copy(p14key, 7 * i, key7, 0, 7);
                Des.MakeSmbKey(key7, key8);

                var des = new Des(key8);
                Array.Copy(in16, 8 * i, s8, 0, 8);

                des.Encrypt(s8, e8);

                Array.Copy(e8, 0, s16, 8 * i, 8);
            }

            return(s16);
        }
Exemplo n.º 13
0
        static async Task DoWork()
        {
            var kdcClient = new KdcClient();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Debug)
                         .CreateLogger();

            Log.Information("Sending a registration request with login '{Login}' and password '{Password}'", Login, Password);
            await kdcClient.Register(Login, Password);

            var mainKey = KeyManager.GenerateSessionKey(Password);

            Log.Information("Generated a [Client <-> AuthServer] key based on password. Key: {Key}", Encoding.UTF8.GetString(mainKey));

            Log.Information("Step #1. Send an authentication request with login '{Login}'", Login);
            var authEncrypted = await kdcClient.Authenticate(Login);

            Log.Information("Step #2.1. Bytes received from Authentication Server: {Bytes}", Encoding.UTF8.GetString(authEncrypted));
            var authResponse = Des.Decrypt <AuthResponse>(mainKey, authEncrypted);

            Log.Information("Step #2.2. Decrypting incoming bytes using [Client <-> AuthServer] key. Authentication Response: {@AuthResponse}", authResponse);

            var tgsKey = authResponse.Key;

            Log.Information("Step #2.3. Got a key that will be used for [Clien <-> TGS] conversation. Key: {Key}", Encoding.UTF8.GetString(tgsKey));

            var authBlock = new AuthBlock {
                Login = Login, Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
            };
            var encryptedAuthBlock = Des.Encrypt(tgsKey, authBlock);
            var ticketRequest      = new AuthRequest
            {
                EncryptedTicket    = authResponse.EncryptedTicket,
                EncryptedAuthBlock = encryptedAuthBlock,
                Recepient          = ServerName
            };

            Log.Information("Step #3.1. Making up a Ticket Request message to send to the Ticket Granting Server. Decrypted Auth Block: {@AuthBlock}", authBlock);
            Log.Information("Step #3.2. Ticket Request: {@TicketRequest}", ticketRequest);

            authEncrypted = await kdcClient.RequestTicket(ticketRequest);

            Log.Information("Step #4.1. Bytes received from Ticket Granting Server: {Bytes}", Encoding.UTF8.GetString(authEncrypted));
            authResponse = Des.Decrypt <AuthResponse>(tgsKey, authEncrypted);
            Log.Information("Step #4.2. Decrypting incoming bytes using [Client <-> TGS] key. TGS Response: {@AuthResponse}", authResponse);

            var serverKey = authResponse.Key;

            Log.Information("Received a session key for [server <-> client] conversation");

            authBlock.Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
            encryptedAuthBlock  = Des.Encrypt(serverKey, authBlock);
            Log.Information("Step #5.1. Using the [server <-> client] session key to encrypt the renewed auth block: {@AuthBlock}", authBlock);
            var authRequest = new AuthRequest
            {
                EncryptedTicket    = authResponse.EncryptedTicket,
                EncryptedAuthBlock = encryptedAuthBlock,
                Recepient          = ServerName
            };

            Log.Information("Step #5.2. Building the auth request for the server: {@AuthRequest}", authRequest);

            Log.Information("Step #5.3. Sending the request to the server");
            var serverResponse = await kdcClient.AuthOnServer(authRequest);

            Log.Information("Step #6.1. Received {Length} bytes from the server, trying to decrypt", serverResponse.Length);

            var timestamp = Des.Decrypt <TimestampWrapper>(serverKey, serverResponse).Timestamp;

            Log.Information("Step #6.2. Decrypted the timestamp using the [server <-> client] session key: {Timestamp}", timestamp);

            if (timestamp - 1 != authBlock.Timestamp)
            {
                Log.Error("Server's timestamp didn't pass the verification. Client's: {T1}, Server's: {T2}", authBlock.Timestamp, timestamp);
                return;
            }
            Log.Information("Step #6.3. Server's identity verified. Client's: {T1}, Server's: {T2}", authBlock.Timestamp, timestamp);
            Log.Information("==== \n\nSuccess! Safe connection has been established. Now [client <-> server] conversation can be continued using the session key: {Key}", Encoding.UTF8.GetString(serverKey));

            return;
        }