平安校园
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.
 
 
 
 
 
 

63 lines
1.5 KiB

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