Ejemplo n.º 1
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)));
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 初始化令牌
 /// </summary>
 /// <param name="tokenKey"></param>
 /// <returns></returns>
 public bool InitToken(string tokenKey)
 {
     try
     {
         _expireDate = DateTime.Now;
         _tokenKey   = tokenKey;
         _tokenId    = Des.Decrypt(_tokenKey, EncryptKey);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// token 解密数据
        /// </summary>
        /// <param name="encrydata"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string TokenDecry(string encrydata, string token)
        {
            try
            {
                if (string.IsNullOrEmpty(encrydata) || string.IsNullOrEmpty(token))
                {
                    return(string.Empty);
                }

                string key = GetKeyByToken(token, 8);
                return(Des.Decrypt(encrydata, key));
            }
            catch
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 4
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("");
        }
Ejemplo n.º 5
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)));
        }
Ejemplo n.º 6
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;
        }