美文网首页IDS
OpenLDAP SSHA 加密算法C#实现

OpenLDAP SSHA 加密算法C#实现

作者: Messix_1102 | 来源:发表于2021-01-18 20:06 被阅读0次

    OpenLDAP SSHA 加密算法是 SHA-1 加密算法加盐的一种处理方法,具体算法是这样:{SSHA}+base64(SHA1(明文密码+盐)+盐)

    从已加密密码中获取"盐"方法如下

        /// <summary>
        /// 获取盐
        /// </summary>
        /// <param name="encryptStr"></param>
        /// <returns></returns>
        public static string GetSalt(string encryptStr)
        {
            encryptStr = encryptStr.Replace("{SSHA}", string.Empty);
            byte[] encryptByte = Convert.FromBase64String(encryptStr);
            encryptByte = encryptByte.Skip(20).Take(encryptByte.Length - 20).ToArray();
            string salt = Encoding.Default.GetString(encryptByte);
            return salt;
        }
    

    加密新的密码

        /// <summary>
        /// 获取加密结果
        /// {SSHA}+base64(SHA1(明文密码+盐)+盐)
        /// </summary>
        /// <param name="pwd"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public string StrEncrypt(string pwd, string salt)
        {
            var sha1 = new SHA1Managed();
            byte[] sha1Res = sha1.ComputeHash(Encoding.UTF8.GetBytes($"{pwd}{salt}"));
            byte[] saltByte = Encoding.UTF8.GetBytes(salt);
            byte[] joinByte = new byte[sha1Res.Length + saltByte.Length];
            sha1Res.CopyTo(joinByte, 0);
            saltByte.CopyTo(joinByte, sha1Res.Length);
            string base64Str = Convert.ToBase64String(joinByte);
            return $"{{SSHA}}{base64Str}";
        }
    

    密码验证

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="pwd">明文</param>
        /// <param name="encryptedPwd">密文</param>
        /// <returns></returns>
        public bool ValidatePwd(string pwd, string encryptedPwd)
        {
            string salt = GetSalt(encryptedPwd);
            string encryptedPwd2 = StrEncrypt(pwd, salt);
            if (encryptedPwd == encryptedPwd2)
            {
                return true;
            }
            return false;
        }
    

    相关文章

      网友评论

        本文标题:OpenLDAP SSHA 加密算法C#实现

        本文链接:https://www.haomeiwen.com/subject/ozoxzktx.html