X509安全登录
服务端:
public UnaryResult<CurrentUser> SignIn(string employeeNoEncry, string pwdEncry, string sessionIdEncry) { //密码解密 X509Certificate2 x509 = new X509Certificate2(GlobalConfig.CertFileName, GlobalConfig.CertPwd, X509KeyStorageFlags.Exportable); var privateKey = x509.PrivateKey.ToXmlString(true); string pwdHash = RSACryptoHelper.Decrypt(privateKey, pwdEncry); string employeeNo = RSACryptoHelper.Decrypt(privateKey, employeeNoEncry); string sessionId = RSACryptoHelper.Decrypt(privateKey, sessionIdEncry); var user = _userRepository.GetByEmployeeNo(employeeNo); if (user == null) { return UnaryResult<CurrentUser>(null); } if (pwdHash == user.Password) { return GetCurrentUser(user.Id); } return UnaryResult<CurrentUser>(null); }
public UnaryResult<string> GetUserSalt(string employeeNoEncry, string sessionIdEncry) { //密码解密 X509Certificate2 x509 = new X509Certificate2(GlobalConfig.CertFileName, GlobalConfig.CertPwd, X509KeyStorageFlags.Exportable); var privateKey = x509.PrivateKey.ToXmlString(true); string employeeNo = RSACryptoHelper.Decrypt(privateKey, employeeNoEncry); string sessionId = RSACryptoHelper.Decrypt(privateKey, sessionIdEncry); var user = _userRepository.GetByEmployeeNo(employeeNo); if (user == null) { return new UnaryResult<string>(); } var saltEncry = SymmetricCryptoHelper.Encrypt(user.Secrect.ToString(), sessionId); return new UnaryResult<string>(saltEncry); }
客户端:
public bool SignIn(string employeeNo, string pwdPlainText) { //获取公钥 string publicKeyBase64 = _userService.GetPublicKey().ResponseAsync.Result; byte[] publicKeyBytes = Convert.FromBase64String(publicKeyBase64); string publicKeyXml = System.Text.Encoding.Default.GetString(publicKeyBytes); //产生SessionId(对称加密的Key) var sessionId = Guid.NewGuid(); var sessionIdString = sessionId.ToString(); //加密SessionId string sessionIdEncry = RSACryptoHelper.Encrypt(publicKeyXml, sessionIdString); //用公钥加密工号 string employeeNoEncry = RSACryptoHelper.Encrypt(publicKeyXml, employeeNo); //获取用户的盐 string saltEncry = _userService.GetUserSalt(employeeNoEncry, sessionIdEncry).ResponseAsync.Result; //如果没有盐,说明用户不存在 if (string.IsNullOrWhiteSpace(saltEncry)) { return false; } //对称解密盐 string salt = SymmetricCryptoHelper.Decrypt(saltEncry, sessionIdString); //用盐哈希密码 string pwdHash = HashHelper.GuidwithPassword(Guid.Parse(salt), pwdPlainText); //用公钥加密哈希密码 string pwdEncry = RSACryptoHelper.Encrypt(publicKeyXml, pwdHash); //登录 var currentUser = _userService.SignIn(employeeNoEncry, pwdEncry, sessionIdEncry).ResponseAsync.Result; //如果用户不存在 if (currentUser == null) { return false; } //保存缓存 CurrentUser = currentUser; return true; }
浙公网安备 33010602011771号