Lucene.NET开发——索引文件关键字加密处理

       使用Lucene生成的索引文件是不经过加密处理的,里边的关键字我们可以打开索引文件看到。但是如果我们需要对索引文件中的关键字和非索引字段进行加密处理,我们就必须查看底层代码,找到关键字和非索引字段的提取的入口处。找到这个关键字加入到索引文件的代码部分,我们就可以在关键字存入索引文件之前对其进行加密了。

关键字加密:

将关键字加入到索引文件的代码在Index文件夹下得TermsHashPerField.cs文件中,找到internal override void Add()函数,部分代码如下:

internal override void  Add()

{

       

   System.Diagnostics.Debug.Assert(!postingsCompacted);

       

   // We are first in the chain so we must "intern" the

   // term text into textStart address

       

   // Get the text of this term.

   char[] tokenText = termAtt.TermBuffer();

   int tokenTextLen = termAtt.TermLength();

       

   // Compute hashcode & replace any invalid UTF16 sequences

   int downto = tokenTextLen;

   int code = 0;

 

将其修改为加密形式:

internal override char[] Add()

{

 

   System.Diagnostics.Debug.Assert(!postingsCompacted);

 

   // We are first in the chain so we must "intern" the

   // term text into textStart address

 

   // Get the text of this term.

   char[] tokenText = termAtt.TermBuffer();

   int tokenTextLen = termAtt.TermLength();

   //这里进行加密***************************************

   StringBuilder strBuilder = new StringBuilder();

   for (int i = 0; i < tokenTextLen; i++)

   {

      strBuilder.Append(tokenText[i]);

   }

   string getstring = strBuilder.ToString();

   string cipher = Encrypt(getstring, Password.password);

   tokenText = cipher.ToCharArray();

   tokenTextLen = tokenText.Length;

   //加密结束***************************************

   // Compute hashcode & replace any invalid UTF16 sequences

   int downto = tokenTextLen;

   int code = 0;

非索引字段加密:

       当我们需要在索引文件中存储一些不需要索引和检索的内容时,比如一个文档的摘要内容,我们就需要对这些摘要等非索引检索内容进行加密以防信息泄露,非索引字段的代码在Index文件夹下的FieldsWriter.cs文件中,找到internal void WriteField(FieldInfo fi, Fieldable field)函数,我们以压缩的文本内容进行加密为例:

这是原来的非加密代码:

else

{

   byte[] x = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(field.StringValue());

   data = CompressionTools.Compress(x, 0, x.Length);

}

修改为加密形式:

else

{

   //这里进行加密*************如果是压缩,则在压缩前加密

   string original = field.StringValue();

   string cipherText = Encrypt(original, Lucene.Net.Index.Password.password);

   //加密结束

   byte[] x = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(cipherText);

   data = CompressionTools.Compress(x, 0, x.Length);

}

经过这样的加密处理,当我们再次生成索引文件的时候,我们会发现,生成的索引文件中关键字都已经经过了加密,已经看不到原来的明文内容了,对于非索引字段一样不能得到其明文内容,完成了索引文件的加密处理。当我们在加密的索引文件上进行检索的时候,我们只需要将要检索的关键字进行加密后再检索便可以得到加密的检索结果了,对于加密的检索结果,使用我们的密钥进行解密便可得到最后的检索结果。

posted @ 2011-10-05 15:01  Erebus_NET  阅读(503)  评论(0编辑  收藏  举报