Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.01 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Numerics;
  7. using System.Security.Cryptography;
  8. using System.Globalization;
  9.  
  10. namespace RaidBot.Engine.Utility.Security
  11. {
  12.     public static class Cryptography
  13.     {
  14.  
  15.         #region Methods
  16.  
  17.         public static byte[] Encrypt(byte[] key, string salt, byte[] aesKey, string username, string password)
  18.         {
  19.             List<byte> unsigned = key.ToList();
  20.  
  21.             //Set Public Key
  22.  
  23.             RSACryptoServiceProvider publicKey = SetPublicKey(unsigned);
  24.  
  25.             //Set Salt
  26.  
  27.             string validSalt = SetSalt(salt);
  28.  
  29.             //Get Credentials
  30.  
  31.             byte[] credentials = SetCredentials(publicKey, validSalt, aesKey, username, password);
  32.  
  33.             //Convert Byte To SByte
  34.  
  35.             return credentials;
  36.         }
  37.  
  38.         #region Set
  39.         private static string GetRsaPublicKey()
  40.         {
  41.             return "MIIBUzANBgkqhkiG9w0BAQEFAAOCAUAAMIIBOwKCATIAgucoka9J2PXcNdjcu6CuDmgteIMB+rih2UZJIuSoNT/0J/lEKL/W4UYbDA4U/6TDS0dkMhOpDsSCIDpO1gPG6+6JfhADRfIJItyHZflyXNUjWOBG4zuxc/L6wldgX24jKo+iCvlDTNUedE553lrfSU23Hwwzt3+doEfgkgAf0l4ZBez5Z/ldp9it2NH6/2/7spHm0Hsvt/YPrJ+EK8ly5fdLk9cvB4QIQel9SQ3JE8UQrxOAx2wrivc6P0gXp5Q6bHQoad1aUp81Ox77l5e8KBJXHzYhdeXaM91wnHTZNhuWmFS3snUHRCBpjDBCkZZ+CxPnKMtm2qJIi57RslALQVTykEZoAETKWpLBlSm92X/eXY2DdGf+a7vju9EigYbX0aXxQy2Ln2ZBWmUJyZE8B58CAwEAAQ==";
  42.         }
  43.  
  44.         private static RSACryptoServiceProvider SetPublicKey(List<byte> key)
  45.         {
  46.             byte[] array = key.ToArray();
  47.             //Decode RSAPublicKey
  48.             string _rsaPublicKey = GetRsaPublicKey();
  49.             RSACryptoServiceProvider rsapublicKey = DecodeX509PublicKey(Convert.FromBase64String(_rsaPublicKey));
  50.  
  51.             //Verify
  52.             byte[] VerifiedKey = verify(array, rsapublicKey.ExportParameters(false));
  53.  
  54.             //Return Valid Public Key
  55.             return DecodeX509PublicKey(VerifiedKey);
  56.  
  57.         }
  58.  
  59.         private static string SetSalt(string salt)
  60.         {
  61.             if (salt.Length < 32)
  62.             {
  63.                 while (salt.Length < 32)
  64.                 {
  65.                     salt += " ";
  66.                 }
  67.             }
  68.  
  69.             return salt;
  70.         }
  71.  
  72.         private static byte[] SetCredentials(RSACryptoServiceProvider publickey, string salt, byte[] aesKey, string username, string password)
  73.         {
  74.             List<byte> Credentials = new List<byte>();
  75.             Credentials.AddRange(Encoding.UTF8.GetBytes(salt));
  76.             Credentials.AddRange(aesKey);
  77.             Credentials.Add(Convert.ToByte(username.Length));
  78.             Credentials.AddRange(Encoding.UTF8.GetBytes(username));
  79.             Credentials.AddRange(Encoding.UTF8.GetBytes(password));
  80.  
  81.             byte[] result = publickey.Encrypt(Credentials.ToArray(), false);
  82.  
  83.             return result;
  84.         }
  85.         #endregion
  86.  
  87.         #region Autre Methode
  88.  
  89.  
  90.  
  91.         private static RSACryptoServiceProvider DecodeX509PublicKey(byte[] x509key)
  92.         {
  93.             // Inspired of http://stackoverflow.com/questions/11506891/how-to-load-the-rsa-public-key-from-file-in-c-sharp
  94.  
  95.             // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
  96.             byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
  97.             byte[] seq = new byte[15];
  98.             // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
  99.             MemoryStream mem = new MemoryStream(x509key);
  100.             BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
  101.             byte bt = 0;
  102.             ushort twobytes = 0;
  103.  
  104.             try
  105.             {
  106.  
  107.                 twobytes = binr.ReadUInt16();
  108.                 if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  109.                     binr.ReadByte();    //advance 1 byte
  110.                 else if (twobytes == 0x8230)
  111.                     binr.ReadInt16();   //advance 2 bytes
  112.                 else
  113.                     return null;
  114.  
  115.                 seq = binr.ReadBytes(15);       //read the Sequence OID
  116.                 if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
  117.                     return null;
  118.  
  119.                 twobytes = binr.ReadUInt16();
  120.                 if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
  121.                     binr.ReadByte();    //advance 1 byte
  122.                 else if (twobytes == 0x8203)
  123.                     binr.ReadInt16();   //advance 2 bytes
  124.                 else
  125.                     return null;
  126.  
  127.                 bt = binr.ReadByte();
  128.                 if (bt != 0x00)     //expect null byte next
  129.                     return null;
  130.  
  131.                 twobytes = binr.ReadUInt16();
  132.                 if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  133.                     binr.ReadByte();    //advance 1 byte
  134.                 else if (twobytes == 0x8230)
  135.                     binr.ReadInt16();   //advance 2 bytes
  136.                 else
  137.                     return null;
  138.  
  139.                 twobytes = binr.ReadUInt16();
  140.                 byte lowbyte = 0x00;
  141.                 byte highbyte = 0x00;
  142.  
  143.                 if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
  144.                     lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
  145.                 else if (twobytes == 0x8202)
  146.                 {
  147.                     highbyte = binr.ReadByte(); //advance 2 bytes
  148.                     lowbyte = binr.ReadByte();
  149.                 }
  150.                 else
  151.                     return null;
  152.                 byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
  153.                 int modsize = BitConverter.ToInt32(modint, 0);
  154.  
  155.                 byte firstbyte = binr.ReadByte();
  156.                 binr.BaseStream.Seek(-1, SeekOrigin.Current);
  157.  
  158.                 if (firstbyte == 0x00)
  159.                 {   //if first byte (highest order) of modulus is zero, don't include it
  160.                     binr.ReadByte();    //skip this null byte
  161.                     modsize -= 1;   //reduce modulus buffer size by 1
  162.                 }
  163.  
  164.                 byte[] modulus = binr.ReadBytes(modsize);   //read the modulus bytes
  165.  
  166.                 if (binr.ReadByte() != 0x02)            //expect an Integer for the exponent data
  167.                     return null;
  168.                 int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
  169.                 byte[] exponent = binr.ReadBytes(expbytes);
  170.  
  171.                 // ------- create RSACryptoServiceProvider instance and initialize with public key -----
  172.                 RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
  173.                 RSAParameters RSAKeyInfo = new RSAParameters();
  174.                 RSAKeyInfo.Modulus = modulus;
  175.                 RSAKeyInfo.Exponent = exponent;
  176.                 RSA.ImportParameters(RSAKeyInfo);
  177.                 return RSA;
  178.             }
  179.             catch (System.Exception)
  180.             {
  181.                 return null;
  182.             }
  183.  
  184.             finally { binr.Close(); }
  185.  
  186.         }
  187.  
  188.         private static bool CompareBytearrays(byte[] a, byte[] b)
  189.         {
  190.             // Inspired of http://stackoverflow.com/questions/11506891/how-to-load-the-rsa-public-key-from-file-in-c-sharp
  191.  
  192.             if (a.Length != b.Length)
  193.                 return false;
  194.             int i = 0;
  195.             foreach (byte c in a)
  196.             {
  197.                 if (c != b[i])
  198.                     return false;
  199.                 i++;
  200.             }
  201.             return true;
  202.         }
  203.  
  204.         private static byte[] verify(byte[] key, RSAParameters RSAParameters)
  205.         {
  206.             // Thank's to MoonLight Angel
  207.  
  208.             BigInteger Exponent = new BigInteger(RSAParameters.Exponent.Reverse().Concat(new byte[] { 0 }).ToArray());
  209.             BigInteger Modulus = new BigInteger(RSAParameters.Modulus.Reverse().Concat(new byte[] { 0 }).ToArray());
  210.  
  211.             BigInteger PreparedData = new BigInteger(key   // Our data block
  212.                 .Reverse()  // BigInteger has another byte order
  213.                 .Concat(new byte[] { 0 })   // Append 0 so we are always handling positive numbers
  214.                 .ToArray()  // Constructor wants an array
  215.             );
  216.  
  217.             byte[] DecryptedData = BigInteger.ModPow(PreparedData, Exponent, Modulus)   // The RSA operation itself
  218.                 .ToByteArray()  // Make bytes from BigInteger
  219.                 .Reverse()  // Back to "normal" byte order
  220.                 .ToArray(); // Return as byte array
  221.  
  222.             return DecryptedData.SkipWhile(x => x != 0).Skip(1).ToArray(); // PKCS#1 padding
  223.         }
  224.  
  225.         #endregion
  226.  
  227.         #endregion
  228.  
  229.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement