MailEncoder.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // System.Web.Mail.MailEncoder
  2. // author: Per Arneng <[email protected]>
  3. using System;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. namespace System.Web.Mail {
  8. internal class MailEncoder {
  9. private delegate void EncodeStreamDelegate( Stream ins , Stream outs );
  10. private EncodeStreamDelegate RealEncodeStream;
  11. public MailEncoder( MailEncoding enc ) {
  12. if( enc == MailEncoding.Base64 ) {
  13. RealEncodeStream = new EncodeStreamDelegate( Base64EncodeStream );
  14. } else if( enc == MailEncoding.UUEncode ) {
  15. throw new NotImplementedException();
  16. }
  17. }
  18. public void EncodeStream( Stream ins , Stream outs ) {
  19. RealEncodeStream( ins , outs );
  20. }
  21. // reads bytes from a stream and writes the encoded
  22. // as base64 encoded characters. ( 60 chars on each row)
  23. private void Base64EncodeStream( Stream ins , Stream outs ) {
  24. if( ( ins == null ) || ( outs == null ) )
  25. throw new ArgumentNullException( "The input and output streams may not " +
  26. "be null.");
  27. ICryptoTransform base64 = new ToBase64Transform();
  28. // the buffers
  29. byte[] plainText = new byte[ base64.InputBlockSize ];
  30. byte[] cipherText = new byte[ base64.OutputBlockSize ];
  31. int readLength = 0;
  32. int trLength = 0;
  33. int count = 0;
  34. byte[] newln = new byte[] { 13 , 10 }; //CR LF with mail
  35. // read through the stream until there
  36. // are no more bytes left
  37. while( true ) {
  38. // read some bytes
  39. readLength = ins.Read( plainText , 0 , plainText.Length );
  40. // break when there is no more data
  41. if( readLength < 1 ) break;
  42. // transfrom and write the blocks. If the block size
  43. // is less than the InputBlockSize then write the final block
  44. if( readLength == plainText.Length ) {
  45. trLength = base64.TransformBlock( plainText , 0 ,
  46. plainText.Length ,
  47. cipherText , 0 );
  48. // write the data
  49. outs.Write( cipherText , 0 , cipherText.Length );
  50. // do this to output lines that
  51. // are 60 chars long
  52. count += cipherText.Length;
  53. if( count == 60 ) {
  54. outs.Write( newln , 0 , newln.Length );
  55. count = 0;
  56. }
  57. } else {
  58. // convert the final blocks of bytes and write them
  59. cipherText = base64.TransformFinalBlock( plainText , 0 , readLength );
  60. outs.Write( cipherText , 0 , cipherText.Length );
  61. }
  62. }
  63. outs.Write( newln , 0 , newln.Length );
  64. }
  65. }
  66. }