平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PwdUtil.cs 1.5 KiB

4 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 
  2. //
  3. namespace SafeCampus.Core.Utils;
  4. /// <summary>
  5. /// 密码相关通用类
  6. /// </summary>
  7. public class PwdUtil
  8. {
  9. /// <summary>
  10. /// 密码相似度
  11. /// </summary>
  12. /// <param name="oldPassword"></param>
  13. /// <param name="newPassword"></param>
  14. /// <returns></returns>
  15. public static double Similarity(string oldPassword, string newPassword)
  16. {
  17. var editDistance = LevenshteinDistance(oldPassword, newPassword);
  18. var similarity = 1.0 - editDistance / (double)Math.Max(oldPassword.Length, newPassword.Length);
  19. return similarity * 100;
  20. }
  21. /// <summary>
  22. /// 计算莱文斯坦距离算法
  23. /// </summary>
  24. /// <param name="s1"></param>
  25. /// <param name="s2"></param>
  26. /// <returns></returns>
  27. public static int LevenshteinDistance(string s1, string s2)
  28. {
  29. var distance = new int[s1.Length + 1, s2.Length + 1];
  30. for (var i = 0; i <= s1.Length; i++)
  31. {
  32. distance[i, 0] = i;
  33. }
  34. for (var j = 0; j <= s2.Length; j++)
  35. {
  36. distance[0, j] = j;
  37. }
  38. for (var i = 1; i <= s1.Length; i++)
  39. {
  40. for (var j = 1; j <= s2.Length; j++)
  41. {
  42. var cost = s1[i - 1] == s2[j - 1] ? 0 : 1;
  43. distance[i, j] = Math.Min(Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1), distance[i - 1, j - 1] + cost);
  44. }
  45. }
  46. return distance[s1.Length, s2.Length];
  47. }
  48. }