Advertisement
kyrathasoft

code from which I build crypt.dll

Jun 6th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 19.03 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Drawing;
  5.  
  6. namespace com.wms.crypt{
  7.    
  8.     /*
  9.         + https://gist.github.com/kyrathasoft/f436e4bfaed8bf2f43f7d72916a4e670
  10.         + https://pastebin.com/RNinZTiz
  11.     */
  12.    
  13.     public class ClassCrypt{   
  14.    
  15.         public static string[] GetTopLevelFiles(string path){
  16.             string[] results = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly);
  17.             return results;
  18.         }      
  19.        
  20.         public static string ImageToBase64(Image image){
  21.             try{
  22.                 var imageStream = new MemoryStream();
  23.                 image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
  24.                 imageStream.Position = 0;
  25.                 var imageBytes = imageStream.ToArray();
  26.                 var ImageBase64 = Convert.ToBase64String(imageBytes);
  27.                 return ImageBase64;
  28.             }
  29.             catch
  30.             {
  31.                 return "Error converting image to base64!";
  32.             }
  33.         }
  34.        
  35.         public static Bitmap Base64ToBitmap(string ImageText){
  36.             Byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage(ImageText));
  37.             System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
  38.             Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));
  39.             return bitImage;
  40.         }
  41.  
  42.         public static string FixBase64ForImage(string Image) {
  43.             System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image,Image.Length);
  44.             sbText.Replace("\r\n", String.Empty); sbText.Replace(" ", String.Empty);
  45.             return sbText.ToString();
  46.         }              
  47.        
  48.         public static bool ConvertedBase64StringToImage(string b64_filepath){
  49.             bool succeeded = false;            
  50.             try{
  51.                 string data = string.Empty;
  52.                 System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
  53.                 if(File.Exists(b64_filepath)){
  54.                     using(StreamReader sr = new StreamReader(b64_filepath)){
  55.                         data = sr.ReadToEnd();
  56.                     }
  57.                     if(b64_filepath.Contains(".jpg.txt")){
  58.                         format = System.Drawing.Imaging.ImageFormat.Jpeg;
  59.                     }
  60.                     if(b64_filepath.Contains(".png.txt")){
  61.                         format = System.Drawing.Imaging.ImageFormat.Png;
  62.                     }
  63.                     Bitmap b = Base64ToBitmap(data);
  64.                     b.Save(b64_filepath.Substring(0, b64_filepath.Length -4), format);
  65.                 }
  66.                 succeeded = true;
  67.             }catch{}
  68.            
  69.             return succeeded;
  70.         }
  71.        
  72.         public static bool ConvertedImageToBase64String(string img_filepath){
  73.             bool succeeded = false;
  74.             try{
  75.                 string converted = ImageToBase64(Image.FromFile(img_filepath));
  76.                 img_filepath = Path.GetFullPath(img_filepath);
  77.                 using(StreamWriter sw = new StreamWriter(img_filepath + ".txt")){
  78.                     sw.Write(converted);
  79.                 }  
  80.                 succeeded = true;
  81.             }catch{}
  82.             return succeeded;
  83.         }        
  84.        
  85.         public static bool SuccessfullyEncryptedAndSavedDataToFile(string plain_text, string password, string saved_file){
  86.             bool result = false;           
  87.             try{
  88.                 plain_text = Encrypt(plain_text, password);
  89.             }catch(Exception exWhileEncrypting){
  90.                 Console.WriteLine(" {0}", exWhileEncrypting.Message);
  91.                 return result;
  92.             }          
  93.             //encryption was successful; now, to save the protected data to file...
  94.             try{               
  95.                 using(StreamWriter sw = new StreamWriter(saved_file)){
  96.                     sw.Write(plain_text);                                      
  97.                 }
  98.             }catch(Exception exWhileStreamWriting){
  99.                 Console.WriteLine(" {0}", exWhileStreamWriting.Message);
  100.                 return result;
  101.             }          
  102.             result = true;
  103.             return result;                     
  104.         }
  105.        
  106.         public static string GetRandomFileName(){
  107.             string result = Path.GetRandomFileName();
  108.             return result;
  109.         }
  110.        
  111.         // Encrypt a byte array into a byte array using a key and an IV
  112.         public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) {
  113.             // Create a MemoryStream to accept the encrypted bytes
  114.             MemoryStream ms = new MemoryStream();
  115.    
  116.             // Create a symmetric algorithm.
  117.             // We are going to use Rijndael because it is strong and
  118.             // available on all platforms.
  119.             // You can use other algorithms, to do so substitute the
  120.             // next line with something like
  121.             //      TripleDES alg = TripleDES.Create();
  122.             Rijndael alg = Rijndael.Create();
  123.    
  124.             // Now set the key and the IV.
  125.             // We need the IV (Initialization Vector) because
  126.             // the algorithm is operating in its default
  127.             // mode called CBC (Cipher Block Chaining).
  128.             // The IV is XORed with the first block (8 byte)
  129.             // of the data before it is encrypted, and then each
  130.             // encrypted block is XORed with the
  131.             // following block of plaintext.
  132.             // This is done to make encryption more secure.
  133.    
  134.             // There is also a mode called ECB which does not need an IV,
  135.             // but it is much less secure.
  136.             alg.Key = Key;
  137.             alg.IV = IV;
  138.    
  139.             // Create a CryptoStream through which we are going to be
  140.             // pumping our data.
  141.             // CryptoStreamMode.Write means that we are going to be
  142.             // writing data to the stream and the output will be written
  143.             // in the MemoryStream we have provided.
  144.             CryptoStream cs = new CryptoStream(ms,
  145.                alg.CreateEncryptor(), CryptoStreamMode.Write);
  146.    
  147.             // Write the data and make it do the encryption
  148.             cs.Write(clearData, 0, clearData.Length);
  149.    
  150.             // Close the crypto stream (or do FlushFinalBlock).
  151.             // This will tell it that we have done our encryption and
  152.             // there is no more data coming in,
  153.             // and it is now a good time to apply the padding and
  154.             // finalize the encryption process.
  155.             cs.Close();
  156.    
  157.             // Now get the encrypted data from the MemoryStream.
  158.             // Some people make a mistake of using GetBuffer() here,
  159.             // which is not the right way.
  160.             byte[] encryptedData = ms.ToArray();
  161.             return encryptedData;
  162.         }
  163.    
  164.         // Encrypt a string into a string using a password
  165.         //    Uses Encrypt(byte[], byte[], byte[])
  166.    
  167.         public static string Encrypt(string clearText, string Password){
  168.             // First we need to turn the input string into a byte array.
  169.             byte[] clearBytes =
  170.               System.Text.Encoding.Unicode.GetBytes(clearText);
  171.    
  172.             // Then, we need to turn the password into Key and IV
  173.             // We are using salt to make it harder to guess our key
  174.             // using a dictionary attack -
  175.             // trying to guess a password by enumerating all possible words.
  176.             PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  177.                 new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  178.                 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  179.    
  180.             // Now get the key/IV and do the encryption using the
  181.             // function that accepts byte arrays.
  182.             // Using PasswordDeriveBytes object we are first getting
  183.             // 32 bytes for the Key
  184.             // (the default Rijndael key length is 256bit = 32bytes)
  185.             // and then 16 bytes for the IV.
  186.             // IV should always be the block size, which is by default
  187.             // 16 bytes (128 bit) for Rijndael.
  188.             // If you are using DES/TripleDES/RC2 the block size is
  189.             // 8 bytes and so should be the IV size.
  190.             // You can also read KeySize/BlockSize properties off
  191.             // the algorithm to find out the sizes.
  192.             byte[] encryptedData = Encrypt(clearBytes,
  193.                      pdb.GetBytes(32), pdb.GetBytes(16));
  194.    
  195.             // Now we need to turn the resulting byte array into a string.
  196.             // A common mistake would be to use an Encoding class for that.
  197.             //It does not work because not all byte values can be
  198.             // represented by characters.
  199.             // We are going to be using Base64 encoding that is designed
  200.             //exactly for what we are trying to do.
  201.             return Convert.ToBase64String(encryptedData);
  202.         }
  203.        
  204.         // Encrypt bytes into bytes using a password
  205.         //    Uses Encrypt(byte[], byte[], byte[])
  206.    
  207.         public static byte[] Encrypt(byte[] clearData, string Password){
  208.             // We need to turn the password into Key and IV.
  209.             // We are using salt to make it harder to guess our key
  210.             // using a dictionary attack -
  211.             // trying to guess a password by enumerating all possible words.
  212.             PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  213.                 new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  214.                 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  215.    
  216.             // Now get the key/IV and do the encryption using the function
  217.             // that accepts byte arrays.
  218.             // Using PasswordDeriveBytes object we are first getting
  219.             // 32 bytes for the Key
  220.             // (the default Rijndael key length is 256bit = 32bytes)
  221.             // and then 16 bytes for the IV.
  222.             // IV should always be the block size, which is by default
  223.             // 16 bytes (128 bit) for Rijndael.
  224.             // If you are using DES/TripleDES/RC2 the block size is 8
  225.             // bytes and so should be the IV size.
  226.             // You can also read KeySize/BlockSize properties off the
  227.             // algorithm to find out the sizes.
  228.             return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16));
  229.         }
  230.    
  231.         // Encrypt a file into another file using a password
  232.         public static void Encrypt(string fileIn,
  233.                     string fileOut, string Password){
  234.    
  235.             // First we are going to open the file streams
  236.             FileStream fsIn = new FileStream(fileIn,
  237.                 FileMode.Open, FileAccess.Read);
  238.             FileStream fsOut = new FileStream(fileOut,
  239.                 FileMode.OpenOrCreate, FileAccess.Write);
  240.    
  241.             // Then we are going to derive a Key and an IV from the
  242.             // Password and create an algorithm
  243.             PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  244.                 new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  245.                 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  246.    
  247.             Rijndael alg = Rijndael.Create();
  248.             alg.Key = pdb.GetBytes(32);
  249.             alg.IV = pdb.GetBytes(16);
  250.    
  251.             // Now create a crypto stream through which we are going
  252.             // to be pumping data.
  253.             // Our fileOut is going to be receiving the encrypted bytes.
  254.             CryptoStream cs = new CryptoStream(fsOut,
  255.                 alg.CreateEncryptor(), CryptoStreamMode.Write);
  256.    
  257.             // Now will will initialize a buffer and will be processing
  258.             // the input file in chunks.
  259.             // This is done to avoid reading the whole file (which can
  260.             // be huge) into memory.
  261.             int bufferLen = 4096;
  262.             byte[] buffer = new byte[bufferLen];
  263.             int bytesRead;
  264.    
  265.             do {
  266.                 // read a chunk of data from the input file
  267.                 bytesRead = fsIn.Read(buffer, 0, bufferLen);
  268.    
  269.                 // encrypt it
  270.                 cs.Write(buffer, 0, bytesRead);
  271.             } while(bytesRead != 0);
  272.    
  273.             // close everything
  274.    
  275.             // this will also close the unrelying fsOut stream
  276.             cs.Close();
  277.             fsIn.Close();    
  278.         }
  279.    
  280.         // Decrypt a byte array into a byte array using a key and an IV
  281.         public static byte[] Decrypt(byte[] cipherData,
  282.                                     byte[] Key, byte[] IV){
  283.             // Create a MemoryStream that is going to accept the
  284.             // decrypted bytes
  285.             MemoryStream ms = new MemoryStream();
  286.    
  287.             // Create a symmetric algorithm.
  288.             // We are going to use Rijndael because it is strong and
  289.             // available on all platforms.
  290.             // You can use other algorithms, to do so substitute the next
  291.             // line with something like
  292.             //     TripleDES alg = TripleDES.Create();
  293.             Rijndael alg = Rijndael.Create();
  294.    
  295.             // Now set the key and the IV.
  296.             // We need the IV (Initialization Vector) because the algorithm
  297.             // is operating in its default
  298.             // mode called CBC (Cipher Block Chaining). The IV is XORed with
  299.             // the first block (8 byte)
  300.             // of the data after it is decrypted, and then each decrypted
  301.             // block is XORed with the previous
  302.             // cipher block. This is done to make encryption more secure.
  303.             // There is also a mode called ECB which does not need an IV,
  304.             // but it is much less secure.
  305.             alg.Key = Key;
  306.             alg.IV = IV;
  307.    
  308.             // Create a CryptoStream through which we are going to be
  309.             // pumping our data.
  310.             // CryptoStreamMode.Write means that we are going to be
  311.             // writing data to the stream
  312.             // and the output will be written in the MemoryStream
  313.             // we have provided.
  314.             CryptoStream cs = new CryptoStream(ms,
  315.                 alg.CreateDecryptor(), CryptoStreamMode.Write);
  316.    
  317.             // Write the data and make it do the decryption
  318.             cs.Write(cipherData, 0, cipherData.Length);
  319.    
  320.             // Close the crypto stream (or do FlushFinalBlock).
  321.             // This will tell it that we have done our decryption
  322.             // and there is no more data coming in,
  323.             // and it is now a good time to remove the padding
  324.             // and finalize the decryption process.
  325.             cs.Close();
  326.    
  327.             // Now get the decrypted data from the MemoryStream.
  328.             // Some people make a mistake of using GetBuffer() here,
  329.             // which is not the right way.
  330.             byte[] decryptedData = ms.ToArray();
  331.             return decryptedData;
  332.         }
  333.    
  334.         // Decrypt a string into a string using a password
  335.         //    Uses Decrypt(byte[], byte[], byte[])
  336.    
  337.         public static string Decrypt(string cipherText, string Password){
  338.             // First we need to turn the input string into a byte array.
  339.             // We presume that Base64 encoding was used
  340.             byte[] cipherBytes = Convert.FromBase64String(cipherText);
  341.    
  342.             // Then, we need to turn the password into Key and IV
  343.             // We are using salt to make it harder to guess our key
  344.             // using a dictionary attack -
  345.             // trying to guess a password by enumerating all possible words.
  346.             PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  347.                 new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
  348.                 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  349.    
  350.             // Now get the key/IV and do the decryption using
  351.             // the function that accepts byte arrays.
  352.             // Using PasswordDeriveBytes object we are first
  353.             // getting 32 bytes for the Key
  354.             // (the default Rijndael key length is 256bit = 32bytes)
  355.             // and then 16 bytes for the IV.
  356.             // IV should always be the block size, which is by
  357.             // default 16 bytes (128 bit) for Rijndael.
  358.             // If you are using DES/TripleDES/RC2 the block size is
  359.             // 8 bytes and so should be the IV size.
  360.             // You can also read KeySize/BlockSize properties off
  361.             // the algorithm to find out the sizes.
  362.             byte[] decryptedData = Decrypt(cipherBytes,
  363.                 pdb.GetBytes(32), pdb.GetBytes(16));
  364.    
  365.             // Now we need to turn the resulting byte array into a string.
  366.             // A common mistake would be to use an Encoding class for that.
  367.             // It does not work
  368.             // because not all byte values can be represented by characters.
  369.             // We are going to be using Base64 encoding that is
  370.             // designed exactly for what we are trying to do.
  371.             return System.Text.Encoding.Unicode.GetString(decryptedData);
  372.         }
  373.    
  374.         // Decrypt bytes into bytes using a password
  375.         //    Uses Decrypt(byte[], byte[], byte[])
  376.    
  377.         public static byte[] Decrypt(byte[] cipherData, string Password){
  378.             // We need to turn the password into Key and IV.
  379.             // We are using salt to make it harder to guess our key
  380.             // using a dictionary attack -
  381.             // trying to guess a password by enumerating all possible words.
  382.             PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  383.                 new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  384.                 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  385.    
  386.             // Now get the key/IV and do the Decryption using the
  387.             //function that accepts byte arrays.
  388.             // Using PasswordDeriveBytes object we are first getting
  389.             // 32 bytes for the Key
  390.             // (the default Rijndael key length is 256bit = 32bytes)
  391.             // and then 16 bytes for the IV.
  392.             // IV should always be the block size, which is by default
  393.             // 16 bytes (128 bit) for Rijndael.
  394.             // If you are using DES/TripleDES/RC2 the block size is
  395.             // 8 bytes and so should be the IV size.
  396.    
  397.             // You can also read KeySize/BlockSize properties off the
  398.             // algorithm to find out the sizes.
  399.             return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16));
  400.         }
  401.    
  402.         // Decrypt a file into another file using a password
  403.         public static void Decrypt(string fileIn,
  404.                     string fileOut, string Password){
  405.        
  406.             // First we are going to open the file streams
  407.             FileStream fsIn = new FileStream(fileIn,
  408.                         FileMode.Open, FileAccess.Read);
  409.             FileStream fsOut = new FileStream(fileOut,
  410.                         FileMode.OpenOrCreate, FileAccess.Write);
  411.      
  412.             // Then we are going to derive a Key and an IV from
  413.             // the Password and create an algorithm
  414.             PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  415.                 new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  416.                 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  417.             Rijndael alg = Rijndael.Create();
  418.    
  419.             alg.Key = pdb.GetBytes(32);
  420.             alg.IV = pdb.GetBytes(16);
  421.    
  422.             // Now create a crypto stream through which we are going
  423.             // to be pumping data.
  424.             // Our fileOut is going to be receiving the Decrypted bytes.
  425.             CryptoStream cs = new CryptoStream(fsOut,
  426.                 alg.CreateDecryptor(), CryptoStreamMode.Write);
  427.      
  428.             // Now will will initialize a buffer and will be
  429.             // processing the input file in chunks.
  430.             // This is done to avoid reading the whole file (which can be
  431.             // huge) into memory.
  432.             int bufferLen = 4096;
  433.             byte[] buffer = new byte[bufferLen];
  434.             int bytesRead;
  435.    
  436.             do {
  437.                 // read a chunk of data from the input file
  438.                 bytesRead = fsIn.Read(buffer, 0, bufferLen);
  439.    
  440.                 // Decrypt it
  441.                 cs.Write(buffer, 0, bytesRead);
  442.    
  443.             } while(bytesRead != 0);
  444.    
  445.             // close everything
  446.             cs.Close(); // this will also close the unrelying fsOut stream
  447.             fsIn.Close();    
  448.         }
  449.          
  450.     }      
  451.    
  452. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement