首页  编辑  

简单文件加解密

Tags: /C#/文件目录操作/   Date Created:

public void FileEncoder( string AFileName , string AStr , string AKey)

{

    byte [] vStrBytes = Encoding . Default . GetBytes(AStr);

    byte [] vKeyBytes = Encoding . Default . GetBytes(AKey);

    int j = 0 ;

    for ( int i = 0 ; i < vStrBytes . Length; i ++ )

   {

       vStrBytes[i] ^= vKeyBytes[j];

       j = (j + 1 ) % vKeyBytes . Length;

   }

    FileStream vFileStream = new FileStream (

       AFileName, FileMode . Create, FileAccess . Write);

   vFileStream . Write(vStrBytes, 0 , vStrBytes . Length);

   vFileStream . Close();

}

public string FileDecoder( string AFileName , string AKey)

{

    if ( ! File . Exists(AFileName)) return null ;

    byte [] vKeyBytes = Encoding . Default . GetBytes(AKey);

    FileStream vFileStream = new FileStream (

       AFileName, FileMode . Open, FileAccess . Read);

    byte [] vStrBytes = new byte [vFileStream . Length];

   vFileStream . Read(vStrBytes, 0 , (int)vFileStream . Length);

   vFileStream . Close();

    int j = 0 ;

    for ( int i = 0 ; i < vStrBytes . Length; i ++ )

   {

       vStrBytes[i] ^= vKeyBytes[j];

       j = (j + 1 ) % vKeyBytes . Length;

   }

    return Encoding . Default . GetString(vStrBytes);

}