翼度科技»论坛 编程开发 .net 查看内容

上传文件附件时判断word、excel、txt等是否含有敏感词如身份证号,手机号等

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
上传附件判断word、excel、txt等文档中是否含有敏感词如身份证号,手机号等,其它检测如PDF,图片(OCR)等可以自行扩展。
互联网项目中,展示的数据中不能包含个人信息等敏感信息。判断word中是否包含手机号,word正文中是否包含身份证号等敏感信息,通过正则表达式判断匹配手机号,身份证号,以下做为参考。会出现碰撞错误,碰撞不准确等情况,不在本文范围。
开发语言C#,框架asp.net webform。由于传文件是做的判断,所以这里是判断数据流HttpPostedFile postedFile中的内容。通过load本地文件,本文不做过多介绍。
一、word校验身份证号,手机号
获取word中内容最初用的是npoi插件,office的插件导入导出以前用的比较多,npoi只获取docx文档文本,npoi获取doc后缀有问题,又找的Spire.Doc。可以都使用后者,笔者只简单测试了doc后缀,其它复杂情况没具体测试。有时间的推荐Spire,因为附件中pdf也是一个大项,刚好有对应的using Spire.Pdf;
using NPOI.XWPF.UserModel;
using Spire.Doc;
using Spire.Doc.Documents;
  1. public class WordToTextConvert
  2. {
  3.      /// <summary>
  4.      /// docx提取成纯文本
  5.      /// </summary>
  6.      /// <param name="file"></param>
  7.      /// <returns></returns>
  8.      public static string ExtractTextFromWord(Stream wordFileStream,string fileExt)
  9.      {
  10.          using (wordFileStream)
  11.          {
  12.              XWPFDocument doc = new XWPFDocument(wordFileStream);
  13.              using (StringWriter writer = new StringWriter())
  14.              {
  15.                  string text = "";
  16.                  foreach (var para in doc.Paragraphs)
  17.                  {
  18.                      text += para.Text+" ";
  19.                  }
  20.                  foreach (XWPFTable table in doc.Tables)
  21.                  {
  22.                      foreach (XWPFTableRow row in table.Rows)
  23.                      {
  24.                          foreach (XWPFTableCell cell in row.GetTableCells())
  25.                          {
  26.                              text += cell.GetText() + " ";
  27.                          }
  28.                      }
  29.                      text += "\r\n";
  30.                  }
  31.                  return text;
  32.              }
  33.          }
  34.      }
  35.      /// <summary>
  36.      /// doc后缀
  37.      /// </summary>
  38.      /// <param name="wordFileStream"></param>
  39.      /// <param name="fileExt"></param>
  40.      /// <returns></returns>
  41.      public static string ExtractTextFromWordDoc(Stream wordFileStream, string fileExt)
  42.      {
  43.          Spire.Doc.Document doc = new Spire.Doc.Document(wordFileStream);
  44.          Spire.Doc.Table table = doc.Sections[0].Tables[0] as Table;
  45.          string text = doc.GetText()+" ";//获取word文档中的文本
  46.          //纯表格可以使用以下方法
  47.          //遍历表格内容
  48.          for (int i = 0; i < table.Rows.Count; i++)
  49.          {
  50.              var cellsindex = table.Rows[i].Cells.Count;
  51.              for (int j = 0; j < cellsindex; j++)
  52.              {
  53.                  TableCell cell = table.Rows[i].Cells[j];
  54.                  foreach (Paragraph paragraph in cell.Paragraphs)
  55.                  {
  56.                      text += paragraph.Text+" ";
  57.                  }
  58.              }
  59.              text += "\r\n";
  60.          }
  61.          return text;
  62.      }
  63. }
复制代码
二、EXCEL校验校验身份证号,手机号
npoi处理excel时要判断后缀,xls和xlsx使用的类不同
  1. public class ExcelToTextConvert
  2. {
  3.     /// <summary>
  4.     /// 提取成纯文本
  5.     /// </summary>
  6.     /// <param name="file"></param>
  7.     /// <returns></returns>
  8.     public static string ExtractTextFromExcel(Stream excelFileStream,string fileExt)
  9.     {
  10.         using (excelFileStream)
  11.         {
  12.             string text = "";
  13.             IWorkbook workbook=null;
  14.             if (fileExt == "xls")
  15.             {
  16.                 workbook = new HSSFWorkbook(excelFileStream);
  17.             }
  18.             if (fileExt == "xlsx")
  19.             {
  20.                 workbook = new XSSFWorkbook(excelFileStream);
  21.             }
  22.             ISheet sheet = workbook.GetSheetAt(0);
  23.             if (sheet != null)
  24.             {
  25.                 foreach (IRow row in sheet)
  26.                 {
  27.                     foreach (ICell cell in row)
  28.                     {
  29.                         switch (cell.CellType)
  30.                         {
  31.                             case CellType.String:
  32.                                 text += cell.StringCellValue + " ";
  33.                                 break;
  34.                             case CellType.Numeric:
  35.                                 text += cell.NumericCellValue + " ";
  36.                                 break;
  37.                         }
  38.                     }
  39.                     text += "\r\n";
  40.                 }
  41.             }
  42.             return text;
  43.         }
  44.     }
  45. }
复制代码
三、txt校验校验身份证号,手机号
获取文件流的内容,文本文件可以直接读取。方法如下:
  1. if ("txt".Contains(fileExt))
  2. {
  3.     // 确保文件不为null并且有数据
  4.     if (postedFile != null && postedFile.ContentLength > 0)
  5.     {
  6.         using (StreamReader reader = new StreamReader(postedFile.InputStream))
  7.         {
  8.             // 读取文件内容并返回
  9.             string readContent = reader.ReadToEnd();
  10.             bool hasMobile = ContainsMobileNumber(readContent);
  11.             if (hasMobile)
  12.             {
  13.                 return "{"status": 0, "msg": "内容中不可含有手机号!"}";
  14.             }
  15.             bool hasId = ContainsIdNumber(readContent);
  16.             if (hasId)
  17.             {
  18.                 return "{"status": 0, "msg": "内容中不可含有身份证号!"}";
  19.             }
  20.         }
  21.     }
  22. }
复制代码
 四、正则校验字符串中是否包含身份证号,手机号等
  1. public static bool ContainsMobileNumber(string text)
  2. {
  3.     // 中国大陆手机号码正则表达式
  4.     string pattern = @"1[3-9]\d{9}";
  5.     return Regex.IsMatch(text, pattern);
  6. }
  7. public static bool ContainsIdNumber(string text)
  8. {
  9.     // 中国大陆身份证号正则表达式
  10.     string pattern = @"[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])";
  11.     return Regex.IsMatch(text, pattern);
  12. }
复制代码
五、读取pdf方法,未做项目验证,请自行搜索相关方法
供参考:读取显示PDF需要借助PDF库,国内Spire.PDF可以读取PDF内容,包括文本,图片以及表格,你可以通过NuGet搜索安装
  1.   1 using Spire.Pdf;
  2.   2 using Spire.Pdf.Texts;
  3.   3 using System.IO;
  4.   4
  5.   5 using System.Text;
  6.   6
  7.   7 namespace ExtractText
  8.   8
  9.   9 {
  10. 10
  11. 11 internal class Program
  12. 12
  13. 13 {
  14. 14
  15. 15 static void Main(string[] args)
  16. 16
  17. 17 {
  18. 18
  19. 19 //创建一个 PdfDocument 对象
  20. 20
  21. 21 PdfDocument doc = new PdfDocument();
  22. 22 //加载PDF文件
  23. 23
  24. 24 doc.LoadFromFile("AI数字人.pdf");
  25. 25
  26. 26 StringBuilder sb = new StringBuilder();
  27. 27
  28. 28 foreach (PdfPageBase page in doc.Pages)
  29. 29
  30. 30 {
  31. 31
  32. 32 //创建一个PdfTextExtractot 对象
  33. 33
  34. 34 PdfTextExtractor textExtractor = new PdfTextExtractor(page);
  35. 35
  36. 36 //创建一个 PdfTextExtractOptions 对象
  37. 37
  38. 38 PdfTextExtractOptions extractOptions = new PdfTextExtractOptions();
  39. 39
  40. 40 //将 isExtractAllText 设置为true
  41. 41
  42. 42 extractOptions.IsExtractAllText = true;
  43. 43
  44. 44 //从页面中提取文本
  45. 45
  46. 46 sb.AppendLine(textExtractor.ExtractText(extractOptions));
  47. 47
  48. 48 }
  49. 49
  50. 50 //将提取的文本写入 TXT 文件
  51. 51
  52. 52 File.WriteAllText("提取指定页面文本.txt", sb.ToString());
  53. 53
  54. 54 }
  55. 55
  56. 56 }
  57. 57
  58. 58 }
  59. 59
  60. 60 读取表格内容:
  61. 61
  62. 62 using Spire.Pdf;
  63. 63
  64. 64 using Spire.Pdf.Utilities;
  65. 65
  66. 66 using System.IO;
  67. 67
  68. 68 using System.Text;
  69. 69
  70. 70 namespace ExtractTable{
  71. 71 class Program
  72. 72 {
  73. 73 static void Main(string[] args)
  74. 74 {
  75. 75 //实例化PdfDocument类的对象
  76. 76 PdfDocument pdf = new PdfDocument();
  77. 77 //加载PDF文档
  78. 78 pdf.LoadFromFile("sample.pdf");
  79. 79 //创建StringBuilder类的对象
  80. 80 StringBuilder builder = new StringBuilder();
  81. 81 //实例化PdfTableExtractor类的对象
  82. 82 PdfTableExtractor extractor = new PdfTableExtractor(pdf);
  83. 83 //声明PdfTable类的表格数组
  84. 84 PdfTable[] tableLists;
  85. 85 //遍历PDF页面
  86. 86 for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)
  87. 87 {
  88. 88 //从页面提取表格
  89. 89 tableLists = extractor.ExtractTable(pageIndex);
  90. 90 //判断表格列表是否为空
  91. 91 if (tableLists != null && tableLists.Length > 0)
  92. 92 {
  93. 93 //遍历表格
  94. 94 foreach (PdfTable table in tableLists)
  95. 95 {
  96. 96 //获取表格中的行和列数
  97. 97 int row = table.GetRowCount();
  98. 98 int column = table.GetColumnCount();
  99. 99 //遍历表格行和列
  100. 100 for (int i = 0; i < row; i++)
  101. 101 {
  102. 102 for (int j = 0; j < column; j++)
  103. 103 {
  104. 104 //获取行和列中的文本
  105. 105 string text = table.GetText(i, j);
  106. 106 //写入文本到StringBuilder容器
  107. 107 builder.Append(text + " ");
  108. 108 }
  109. 109 builder.Append("\r\n");
  110. 110 }
  111. 111 }
  112. 112 }
  113. 113 }
  114. 114 //保存提取的表格内容为.txt文档
  115. 115 File.WriteAllText("ExtractedTable.txt", builder.ToString());
  116. 116 }
  117. 117 }
  118. 118
  119. 119 }
复制代码
读取PDF的内容,文本、表格、图片 
总结:尽一切合理努力保护用户个人信息, 并对个人信息进行保护。为防止用户个人信息在意外的、未经授权的情况下泄漏。
压缩包内容校验基本方法同上,先解压缩,再逐文件处理。本文直接判断有敏感词,不让上传,也可以通过正则把信息替换成****后再转存,这里不再展开。
如有专门的更好用的插件请留言告知讨论,避免重复造轮子。
 
出处:http://www.cnblogs.com/oorz/Q群:NET CORE技术交流(444036561)

微信公众号:“专卓”;因为专业,所以卓越!可扫描左侧二维码关注。本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
来源:https://www.cnblogs.com/oorz/p/18067714
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具