public Init ( bool forEncryption, ICipherParameters parameters ) : void | ||
forEncryption | bool | |
parameters | ICipherParameters | |
리턴 | void |
private void blockCheck( PaddedBufferedBlockCipher cipher, IBlockCipherPadding padding, KeyParameter key, byte[] data) { byte[] outBytes = new byte[data.Length + 8]; byte[] dec = new byte[data.Length]; try { cipher.Init(true, key); int len = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0); len += cipher.DoFinal(outBytes, len); cipher.Init(false, key); int decLen = cipher.ProcessBytes(outBytes, 0, len, dec, 0); decLen += cipher.DoFinal(dec, decLen); if (!AreEqual(data, dec)) { Fail("failed to decrypt - i = " + data.Length + ", padding = " + padding.PaddingName); } } catch (Exception e) { Fail("Exception - " + e.ToString(), e); } }
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key) { _cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding); byte[] keyByte = _encoding.GetBytes(key); _cipher.Init(forEncrypt, new KeyParameter(keyByte)); return _cipher.DoFinal(input); }
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key) { try { _cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding); int paddingchar = 16 - key.Length; for (int i = 0; i < paddingchar; i++) { key += " "; } key = key.Substring(0, 16); byte[] keyByte = _encoding.GetBytes(key); _cipher.Init(forEncrypt, new KeyParameter(keyByte)); return(_cipher.DoFinal(input)); } catch (Org.BouncyCastle.Crypto.CryptoException ex) { // throw new CryptoException(ex); } return(null); }
private static byte[] Decrypt(byte[] bytes, byte[] key) { var engine = new BlowfishEngine(); var chiper = new PaddedBufferedBlockCipher(engine); var keyParameter = new KeyParameter(key); chiper.Init(false, keyParameter); return chiper.DoFinal(bytes); }
/** Creates a new instance of AESCipher */ public AESCipher(bool forEncryption, byte[] key, byte[] iv) { IBlockCipher aes = new AesFastEngine(); IBlockCipher cbc = new CbcBlockCipher(aes); bp = new PaddedBufferedBlockCipher(cbc); KeyParameter kp = new KeyParameter(key); ParametersWithIV piv = new ParametersWithIV(kp, iv); bp.Init(forEncryption, piv); }
private static string Cipher(bool encrypt, byte[] key, byte[] data) { PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cipherEngine, padding); cipher.Init(encrypt, new KeyParameter(key)); int size = cipher.GetOutputSize(data.Length); byte[] result = new byte[size]; int position = cipher.ProcessBytes(data, 0, data.Length, result, 0); cipher.DoFinal(result, position); return encrypt ? BitConverter.ToString(result).Replace("-", String.Empty).ToLower() : encoding.GetString(result); }
/// <summary> /// /// </summary> /// <param name="forEncrypt"></param> /// <param name="input"></param> /// <param name="key"></param> /// <returns></returns> /// <exception cref="CryptoException"></exception> private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key) { try { _cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding); byte[] keyByte = _encoding.GetBytes(key); _cipher.Init(forEncrypt, new KeyParameter(keyByte)); return _cipher.DoFinal(input); } catch (Org.BouncyCastle.Crypto.CryptoException ex) { throw new CryptoException("BCEngine CryptoException", ex); } }
public static AesEncyrption getInstance() { if (instance == null) { try { if (string.IsNullOrEmpty(_encryptionKey)) { Initalize(); } AesEncyrption bcEngine = new AesEncyrption(); KeyParameter keyParam = new KeyParameter(Encoding.UTF8.GetBytes(_encryptionKey)); ICipherParameters param = new ParametersWithIV(keyParam, iv); //create decrypt/encryptor cipher IBlockCipherPadding padding = new Pkcs7Padding(); BufferedBlockCipher decrypt = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), padding); decrypt.Reset(); decrypt.Init(false, param); bcEngine.setDecryptCipher(decrypt); BufferedBlockCipher encrypt = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), padding); encrypt.Reset(); encrypt.Init(true, param); bcEngine.setEncryptCipher(encrypt); instance = bcEngine; } catch (Exception) { throw; } } return instance; }
/// <summary> /// Symmetric encryption with AES/CBC/PKCS7. /// </summary> /// <param name="message">Message to be encrypted.</param> /// <param name="key">Private key for use with encryption.</param> /// <returns>Message in cipher text.</returns> public static byte[] Encrypt( byte[] message, byte[] key ) { PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher( new AesEngine() ), new Pkcs7Padding() ); cipher.Init( true, new KeyParameter( key ) ); return cipher.DoFinal( message ); }
/// <summary> /// Symmetric decryption with AES/CBC/PKCS7. /// </summary> /// <param name="cipherText">Message to be decrypted.</param> /// <param name="key">Private key for use with decryption.</param> /// <returns>Plain text message.</returns> public static byte[] Decrypt( byte[] cipherText, byte[] key ) { PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher( new AesEngine() ), new Pkcs7Padding() ); cipher.Init( false, new KeyParameter( key ) ); return cipher.DoFinal( cipherText ); }
/// <summary> /// Decrypt a hex-coded string using our MD5 or PBKDF2 generated key /// </summary> /// <param name="data">data string to be decrypted</param> /// <param name="key">decryption key</param> /// <param name="PBKDF2">flag to indicate we are using PBKDF2 to generate derived key</param> /// <returns>hex coded decrypted string</returns> public static string Decrypt(string data, string password, bool PBKDF2) { byte[] key; byte[] saltBytes = Authenticator.StringToByteArray(data.Substring(0, SALT_LENGTH * 2)); if (PBKDF2 == true) { // extract the salt from the data byte[] passwordBytes = Encoding.UTF8.GetBytes(password); // build our PBKDF2 key #if NETCF PBKDF2 kg = new PBKDF2(passwordBytes, saltbytes, 2000); #else Rfc2898DeriveBytes kg = new Rfc2898DeriveBytes(passwordBytes, saltBytes, PBKDF2_ITERATIONS); #endif key = kg.GetBytes(PBKDF2_KEYSIZE); } else { // extract the salt from the data byte[] passwordBytes = Encoding.UTF8.GetBytes(password); key = new byte[saltBytes.Length + passwordBytes.Length]; Array.Copy(saltBytes, key, saltBytes.Length); Array.Copy(passwordBytes, 0, key, saltBytes.Length, passwordBytes.Length); // build out combined key SHA256Managed md5 =new SHA256Managed(); key = md5.ComputeHash(key); } // extract the actual data to be decrypted byte[] inBytes = Authenticator.StringToByteArray(data.Substring(SALT_LENGTH * 2)); // get cipher BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding()); cipher.Init(false, new KeyParameter(key)); // decrypt the data int osize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[osize]; try { int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); olen += cipher.DoFinal(outBytes, olen); if (olen < osize) { byte[] t = new byte[olen]; Array.Copy(outBytes, 0, t, 0, olen); outBytes = t; } } catch (Exception) { // an exception is due to bad password throw new BadPasswordException(); } // return encoded string return Authenticator.ByteArrayToString(outBytes); }
/// <summary> /// Encrypt a string with a given key /// </summary> /// <param name="plain">data to encrypt - hex representation of byte array</param> /// <param name="key">key to use to encrypt</param> /// <returns>hex coded encrypted string</returns> public static string Encrypt(string plain, string password) { byte[] inBytes = Authenticator.StringToByteArray(plain); byte[] passwordBytes = Encoding.UTF8.GetBytes(password); // build a new salt RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider(); byte[] saltbytes = new byte[SALT_LENGTH]; rg.GetBytes(saltbytes); string salt = Authenticator.ByteArrayToString(saltbytes); // build our PBKDF2 key #if NETCF PBKDF2 kg = new PBKDF2(passwordBytes, saltbytes, PBKDF2_ITERATIONS); #else Rfc2898DeriveBytes kg = new Rfc2898DeriveBytes(passwordBytes, saltbytes, PBKDF2_ITERATIONS); #endif byte[] key = kg.GetBytes(PBKDF2_KEYSIZE); // get our cipher BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding()); cipher.Init(true, new KeyParameter(key)); // encrypt data int osize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[osize]; int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); olen += cipher.DoFinal(outBytes, olen); if (olen < osize) { byte[] t = new byte[olen]; Array.Copy(outBytes, 0, t, 0, olen); outBytes = t; } // return encoded byte->hex string return salt + Authenticator.ByteArrayToString(outBytes); }
/// <summary> /// Decrypt a hex-encoded string with a byte array key /// </summary> /// <param name="data">hex-encoded string</param> /// <param name="key">key for decryption</param> /// <returns>hex-encoded plain text</returns> public static string Decrypt(string data, byte[] key) { // the actual data to be decrypted byte[] inBytes = Authenticator.StringToByteArray(data); // get cipher BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding()); cipher.Init(false, new KeyParameter(key)); // decrypt the data int osize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[osize]; try { int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); olen += cipher.DoFinal(outBytes, olen); if (olen < osize) { byte[] t = new byte[olen]; Array.Copy(outBytes, 0, t, 0, olen); outBytes = t; } } catch (Exception) { // an exception is due to bad password throw new BadPasswordException(); } // return encoded string return Authenticator.ByteArrayToString(outBytes); }
/// <summary> /// Decrypts cypher data /// </summary> /// <param name="cipherData"></param> /// <param name="password"></param> /// <returns></returns> public static string Decrypt(byte[] cipherData, string password) { // If there is no cipher data, return null if (cipherData == null) { return null; } //extract the iv and salt byte[] ivBytes = new byte[IV_LENGTH]; byte[] saltBytes = new byte[SALT_LENGTH]; byte[] cipherBytes = new byte[cipherData.Length - (ivBytes.Length + saltBytes.Length)]; //process the input using (var cipherStream = new MemoryStream(cipherData)) { //read iv cipherStream.Read(ivBytes, 0, ivBytes.Length); //read salt cipherStream.Read(saltBytes, 0, saltBytes.Length); //read cipher bytes cipherStream.Read(cipherBytes, 0, cipherBytes.Length); } //create cipher engine var cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher( new AesEngine())); //get the key parameters from the password var key = GenerateKey(password, saltBytes, ivBytes); //initialize for decryption with the key cipher.Init(false, key); MemoryStream plainStream; //process the input using (plainStream = new MemoryStream()) { byte[] outputBytes; //get output outputBytes = cipher.ProcessBytes(cipherBytes); if (outputBytes != null) { //write the data to the stream plainStream.Write(outputBytes, 0, outputBytes.Length); } //do the final block outputBytes = cipher.DoFinal(); if (outputBytes != null) { //write the data to the stream plainStream.Write(outputBytes, 0, outputBytes.Length); } } return Encoding.UTF8.GetString(plainStream.ToArray()); }
/// <summary> /// Encapsulates the specified links into a CCF container. /// </summary> /// <param name="name">The name of the package.</param> /// <param name="links">The links.</param> /// <returns> /// CCF container. /// </returns> public static byte[] CreateCCF(string name, string[] links) { var sb = new StringBuilder(); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.Append("<CryptLoad>"); sb.Append("<Package service=\"\" name=\"" + name + "\" url=\"Directlinks\">"); foreach (var link in links) { sb.Append("<Download Url=\"" + link + "\">"); sb.Append("<Url>" + link + "</Url>"); //sb.Append("<FileName></FileName>"); //sb.Append("<FileSize></FileSize>"); sb.Append("</Download>"); } sb.Append("</Package>"); sb.Append("</CryptLoad>"); var aes = new AesEngine(); var cbc = new CbcBlockCipher(aes); var pk7 = new Pkcs7Padding(); var pad = new PaddedBufferedBlockCipher(cbc, pk7); pad.Init(true, new ParametersWithIV(new KeyParameter(CCFKey), CCFIV)); return pad.DoFinal(Encoding.UTF8.GetBytes(sb.ToString())); }
/// <summary> /// The decrypt. /// </summary> /// <param name="encrypted"> /// The encrypted. /// </param> /// <param name="key"> /// The key. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> private string Decrypt(string encrypted, SecretKey key) { byte[] bytes = Convert.FromBase64String(encrypted); byte[] keyBytes = key.GetBytes(); // initialise the cipher for decryption var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine())); cipher.Init(false, new KeyParameter(keyBytes)); int inBlockSize = bytes.Length; int outBlockSize = cipher.GetOutputSize(inBlockSize); var inblock = bytes; var outblock = new byte[outBlockSize]; cipher.ProcessBytes(inblock, 0, inBlockSize, outblock, 0); cipher.DoFinal(outblock, 0); var clear = this.ToUTF8String(outblock); return clear; }
private void EncryptDataAes256CbcPkcs7(byte[] dataToEncrypt) { if (_key != null && _key.Length != 32) throw new Exception("Explicit data encryption key is not of required length for encryption method"); if (_key == null) { // No explicit key was provided, we're going to generate our own. _key = new byte[32]; RandomUtil.SecureRandomBc.NextBytes(_key); } _iv = new byte[16]; RandomUtil.SecureRandomBc.NextBytes(_iv); var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesFastEngine()), new Pkcs7Padding()); cipher.Init(true, new ParametersWithIV(new KeyParameter(_key), _iv)); _data = cipher.DoFinal(dataToEncrypt); }
/// <summary> /// Decrypt AES256-CBC with PKCS7 padding data /// </summary> /// <param name="encryptionKey"></param> /// <param name="encryptedDataStream"></param> /// <param name="outputStream"></param> private static void DecryptDataAes256CbcPkcs7( byte[] encryptionKey, Stream encryptedDataStream, Stream outputStream) { if (encryptionKey.Length != 32) throw new Exception("AES256 encryption key not of expected length"); var iv = new byte[16]; var ivBytesRead = encryptedDataStream.Read(iv, 0, 16); if (ivBytesRead != 16) throw new Exception("Unexpected IV"); // The rest of the data stream is the encrypted data itself. var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesFastEngine()), new Pkcs7Padding()); cipher.Init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv)); while (true) { var buffer = new byte[4096]; var dataBytesRead = encryptedDataStream.Read(buffer, 0, 4096); if (dataBytesRead == 0) break; var processedBytes = cipher.ProcessBytes(buffer, 0, dataBytesRead); if (processedBytes != null) outputStream.Write(processedBytes, 0, processedBytes.Length); } var finalBytes = cipher.DoFinal(); outputStream.Write(finalBytes, 0, finalBytes.Length); }
/// <summary> /// Encrypts using AES256Cbc and a password /// </summary> /// <param name="password"></param> /// <param name="plainText"></param> /// <returns></returns> public static byte[] Encrypt(string plainText, string password) { // If text to encrypt is null, return null if (string.IsNullOrWhiteSpace(plainText)) { return null; } // Generate a random salt var saltBytes = GenerateSalt(); //create cipher engine var cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher( new AesEngine())); //get the key parameters from the password var key = GenerateKey(password, saltBytes); //initialize for encryption with the key cipher.Init(true, key); // Convert plain text string to bytes var plainBytes = Encoding.UTF8.GetBytes(plainText); MemoryStream cipherStream; //process the input using (cipherStream = new MemoryStream()) { //write iv cipherStream.Write(key.GetIV(), 0, key.GetIV().Length); //write salt cipherStream.Write(saltBytes, 0, saltBytes.Length); byte[] outputBytes; //get output outputBytes = cipher.ProcessBytes(plainBytes); if (outputBytes != null) { //write the data to the stream cipherStream.Write(outputBytes, 0, outputBytes.Length); } //do the final block outputBytes = cipher.DoFinal(); if (outputBytes != null) { //write the data to the stream cipherStream.Write(outputBytes, 0, outputBytes.Length); } } //return the bytes return cipherStream.ToArray(); }
private void DoCbc(byte[] key, byte[] iv, byte[] pt, byte[] expected) { PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new CbcBlockCipher(new SerpentEngine()), new Pkcs7Padding()); byte[] ct = new byte[expected.Length]; c.Init(true, new ParametersWithIV(new KeyParameter(key), iv)); int l = c.ProcessBytes(pt, 0, pt.Length, ct, 0); c.DoFinal(ct, l); if (!Arrays.AreEqual(expected, ct)) { Fail("CBC test failed"); } }
private void EncryptUsingBC(Stream istream, Stream ostream, byte[] iv, bool forEncryption) { var padding = ((TypeWrapper) BlockCipherModel.Padding).Instance<IBlockCipherPadding>(); var engine = BlockCipherModel.Engine.Instance<IBlockCipher>(); var mode = ((TypeWrapper) BlockCipherModel.Mode).Instance<IBlockCipher>(engine); var cipher = new PaddedBufferedBlockCipher(mode, padding); var buf = new byte[16]; //input buffer var obuf = new byte[512]; //output buffer int noBytesRead; //number of bytes read from input int noBytesProcessed ; //number of bytes processed var p = new ParametersWithIV(new KeyParameter(PbkdfModel.Key), iv); cipher.Init(forEncryption, p); // Buffer used to transport the bytes from one stream to another while ((noBytesRead = istream.Read(buf, 0, Blocksize)) > 0) { //System.out.println(noBytesRead +" bytes read"); noBytesProcessed = cipher.ProcessBytes(buf, 0, noBytesRead, obuf, 0); //System.out.println(noBytesProcessed +" bytes processed"); ostream.Write(obuf, 0, noBytesProcessed); } //System.out.println(noBytesRead +" bytes read"); noBytesProcessed = cipher.DoFinal(obuf, 0); //System.out.println(noBytesProcessed +" bytes processed"); ostream.Write(obuf, 0, noBytesProcessed); ostream.Flush(); }
/// <summary> /// Encrypt a string with a byte array key /// </summary> /// <param name="plain">data to encrypt - hex representation of byte array</param> /// <param name="passwordBytes">key to use to encrypt</param> /// <returns>hex coded encrypted string</returns> public static string Encrypt(string plain, byte[] key) { byte[] inBytes = Authenticator.StringToByteArray(plain); // get our cipher BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding()); cipher.Init(true, new KeyParameter(key)); // encrypt data int osize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[osize]; int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); olen += cipher.DoFinal(outBytes, olen); if (olen < osize) { byte[] t = new byte[olen]; Array.Copy(outBytes, 0, t, 0, olen); outBytes = t; } // return encoded byte->hex string return Authenticator.ByteArrayToString(outBytes); }
private static Stream CreateStream(Stream s, bool bEncrypt, byte[] pbKey, byte[] pbIV) { StandardAesEngine.ValidateArguments(s, bEncrypt, pbKey, pbIV); byte[] pbLocalIV = new byte[16]; Array.Copy(pbIV, pbLocalIV, 16); byte[] pbLocalKey = new byte[32]; Array.Copy(pbKey, pbLocalKey, 32); #if !KeePassRT RijndaelManaged r = new RijndaelManaged(); if(r.BlockSize != 128) // AES block size { Debug.Assert(false); r.BlockSize = 128; } r.IV = pbLocalIV; r.KeySize = 256; r.Key = pbLocalKey; r.Mode = m_rCipherMode; r.Padding = m_rCipherPadding; ICryptoTransform iTransform = (bEncrypt ? r.CreateEncryptor() : r.CreateDecryptor()); Debug.Assert(iTransform != null); if(iTransform == null) throw new SecurityException("Unable to create Rijndael transform!"); return new CryptoStream(s, iTransform, bEncrypt ? CryptoStreamMode.Write : CryptoStreamMode.Read); #else AesEngine aes = new AesEngine(); CbcBlockCipher cbc = new CbcBlockCipher(aes); PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(cbc, new Pkcs7Padding()); KeyParameter kp = new KeyParameter(pbLocalKey); ParametersWithIV prmIV = new ParametersWithIV(kp, pbLocalIV); bc.Init(bEncrypt, prmIV); IBufferedCipher cpRead = (bEncrypt ? null : bc); IBufferedCipher cpWrite = (bEncrypt ? bc : null); return new CipherStream(s, cpRead, cpWrite); #endif }
/// <summary> /// The encrypt. /// </summary> /// <param name="data"> /// The data. /// </param> /// <param name="key"> /// The key. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> private string Encrypt(string data, SecretKey key) { byte[] bytes = Encoding.UTF8.GetBytes(data); // Setup the DESede cipher engine, create a PaddedBufferedBlockCipher in CBC mode. byte[] keyBytes = key.GetBytes(); var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine())); // initialise the cipher with the key bytes, for encryption cipher.Init(true, new KeyParameter(keyBytes)); int inBlockSize = bytes.Length; int outBlockSize = cipher.GetOutputSize(inBlockSize); var inblock = bytes; var outblock = new byte[outBlockSize]; cipher.ProcessBytes(inblock, 0, inBlockSize, outblock, 0); cipher.DoFinal(outblock, 0); return Convert.ToBase64String(outblock); }
/// <summary> /// Encapsulates the specified links into a DLC container. /// </summary> /// <param name="name">The name of the package.</param> /// <param name="links">The links.</param> /// <returns> /// Base-64-encoded DLC container. /// </returns> public static string CreateDLC(string name, string[] links) { var sb = new StringBuilder(); sb.Append("<dlc>"); sb.Append("<header>"); sb.Append("<generator>"); sb.Append("<app>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("RS TV Show Tracker")) + "</app>"); sb.Append("<version>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("1.0")) + "</version>"); sb.Append("<url>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("http://lab.rolisoft.net/")) + "</url>"); sb.Append("</generator>"); sb.Append("<dlcxmlversion>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("20_02_2008")) + "</dlcxmlversion>"); sb.Append("</header>"); sb.Append("<content>"); sb.Append("<package name=\"" + Convert.ToBase64String(Encoding.UTF8.GetBytes(name)) + "\">"); foreach (var link in links) { sb.Append("<file>"); sb.Append("<url>" + Convert.ToBase64String(Encoding.UTF8.GetBytes(link)) + "</url>"); //sb.Append("<filename></filename>"); //sb.Append("<size></size>"); sb.Append("</file>"); } sb.Append("</package>"); sb.Append("</content>"); sb.Append("</dlc>"); var xml = Convert.ToBase64String(Encoding.UTF8.GetBytes(sb.ToString())); var key = BitConverter.ToString(new SHA256CryptoServiceProvider().ComputeHash(BitConverter.GetBytes(DateTime.Now.ToBinary()))).Replace("-", string.Empty).Substring(0, 16); var srv = Utils.GetURL(DLCCrypt, "&data=" + key + "&lid=" + Convert.ToBase64String(Encoding.UTF8.GetBytes("http://lab.rolisoft.net/_3600")) + "&version=1.0&client=rstvshowtracker"); var rcr = Regex.Match(srv, @"<rc>(.+)</rc>"); if (!rcr.Groups[1].Success) { throw new Exception("The jDownloader DLC encryption service did not return an encryption key."); } var enc = rcr.Groups[1].Value; var aes = new AesEngine(); var cbc = new CbcBlockCipher(aes); var zbp = new ZeroBytePadding(); var pad = new PaddedBufferedBlockCipher(cbc, zbp); pad.Init(true, new ParametersWithIV(new KeyParameter(Encoding.ASCII.GetBytes(key)), Encoding.ASCII.GetBytes(key))); var xm2 = Convert.ToBase64String(pad.DoFinal(Encoding.ASCII.GetBytes(xml))); return xm2 + enc; }
private static void en_de_crypt(en_de_cryption_mode en_de_cryption_mode_current, string file_path_from, string file_path_to, bool delete_file_path_from, bool interactive) { Form form = new Form(); Label password_1_label = new Label(), password_2_label = new Label(); int label_width = 150, label_height = 20, textbox_width = 200, textbox_height = 20, button_width = 80, button_height = 40; Color label_forecolor = Color.LightGreen, password_backcolor = Color.Black, password_forecolor = Color.LightGreen, proceed_backcolor = Color.Black, proceed_forecolor = Color.LightGreen, cancel_backcolor = Color.Black, cancel_forecolor = Color.LightGreen, error_forecolor = Color.Red; ContentAlignment label_text_alignment = ContentAlignment.MiddleRight, button_text_alignment = ContentAlignment.MiddleCenter; TextBox password_1 = new TextBox(), password_2 = new TextBox(); char password_character = '*'; BorderStyle password_border_style = BorderStyle.Fixed3D; Font label_font = new Font(FontFamily.GenericMonospace, (float)10.0), password_font = new Font(FontFamily.GenericMonospace, (float)10.0), button_font = new Font(FontFamily.GenericMonospace, (float)10.0); Button proceed = new Button(), cancel = new Button(); form.StartPosition = FormStartPosition.CenterParent; form.Width = 400; form.Height = 180; form.BackColor = Color.Black; form.Text = "Please, provide the password for the " + (en_de_cryption_mode_current == en_de_cryption_mode.encrypt ? "encryption" : "decryption") + "."; password_1_label.Bounds = new Rectangle(10, 20, label_width, label_height); password_1_label.Font = label_font; password_1_label.ForeColor = label_forecolor; password_1_label.TextAlign = label_text_alignment; password_1_label.Text = "Password:"******"Confirm password:"******"OnClick", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(cancel, new object[] { null }); if (en_de_cryption_mode_current == en_de_cryption_mode.encrypt) { if (!string.IsNullOrEmpty(password_1.Text)) { password_2.Enabled = true; } else { proceed.Enabled = false; password_2.Text = ""; if (password_2.Enabled) password_2.Enabled = false; } } else { if (!string.IsNullOrEmpty(password_1.Text)) proceed.Enabled = true; else proceed.Enabled = false; } if ((Keys)e.KeyValue == Keys.Enter && !string.IsNullOrEmpty(password_1.Text)) { if (en_de_cryption_mode_current == en_de_cryption_mode.encrypt) password_2.Focus(); else proceed.GetType() .GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(proceed, new object[] { new KeyEventArgs(Keys.Enter) }); } }; password_2.Bounds = new Rectangle(160, 50, textbox_width, textbox_height); password_2.BackColor = password_backcolor; password_2.ForeColor = password_forecolor; password_2.BorderStyle = password_border_style; password_2.PasswordChar = password_character; password_2.Font = password_font; password_2.Multiline = false; password_2.Enabled = false; if (en_de_cryption_mode_current == en_de_cryption_mode.encrypt) password_2.KeyUp += (sender, e) => { if ((Keys)e.KeyValue == Keys.Escape) cancel.GetType() .GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(cancel, new object[] { null }); if (string.IsNullOrEmpty(password_2.Text) || password_1.Text.Equals(password_2.Text)) { if (!string.IsNullOrEmpty(password_2.Text)) proceed.Enabled = true; password_2.ForeColor = password_forecolor; if ((Keys)e.KeyValue == Keys.Enter && !string.IsNullOrEmpty(password_2.Text)) proceed.GetType() .GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(proceed, new object[] { new KeyEventArgs(Keys.Enter) }); } else { proceed.Enabled = false; password_2.ForeColor = error_forecolor; } }; proceed.Bounds = new Rectangle(290, 100, button_width, button_height); proceed.BackColor = proceed_backcolor; proceed.ForeColor = proceed_forecolor; proceed.Font = button_font; proceed.TextAlign = button_text_alignment; proceed.Text = "Proceed"; proceed.Enabled = false; proceed.Click += (sender, e) => { form.Close(); byte[] key_string_bytes = Encoding.UTF8.GetBytes(password_1.Text), key = new byte[64]; password_1.Text = ""; password_2.Text = ""; FileStream file_from = null, file_to = null; try { WhirlpoolDigest whirlpool_digest = new WhirlpoolDigest(); whirlpool_digest.BlockUpdate(key_string_bytes, 0, key_string_bytes.Length); whirlpool_digest.DoFinal(key, 0); SerpentEngine serpent_engine = new SerpentEngine(); Pkcs7Padding pkcs7_padding = new Pkcs7Padding(); pkcs7_padding.Init(new SecureRandom(key)); PaddedBufferedBlockCipher padded_buffered_block_cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(serpent_engine), pkcs7_padding); byte[] iv = new byte[padded_buffered_block_cipher.GetBlockSize()]; Array.Copy(key, key.Length - iv.Length, iv, 0, iv.Length); padded_buffered_block_cipher.Init((en_de_cryption_mode_current == en_de_cryption_mode.encrypt), new ParametersWithIV(new KeyParameter(key, 31, 32), iv)); int plaintext_buffer_size = 1024 * padded_buffered_block_cipher.GetBlockSize(), ciphertext_buffer_size = padded_buffered_block_cipher.GetBlockSize() + plaintext_buffer_size, bytes_read_count, bytes_en_de_crypted_count; byte[] buffer_from, buffer_to; if (en_de_cryption_mode_current == en_de_cryption_mode.encrypt) { buffer_from = new byte[plaintext_buffer_size]; buffer_to = new byte[ciphertext_buffer_size]; } else { buffer_from = new byte[ciphertext_buffer_size]; buffer_to = new byte[plaintext_buffer_size]; } file_from = new FileStream(file_path_from, FileMode.Open); file_to = new FileStream(file_path_to, FileMode.Create); while (true) { bytes_read_count = file_from.Read(buffer_from, 0, buffer_from.Length); if (bytes_read_count == 0) { break; } bytes_en_de_crypted_count = padded_buffered_block_cipher.DoFinal(buffer_from, 0, bytes_read_count, buffer_to, 0); file_to.Write(buffer_to, 0, bytes_en_de_crypted_count); } file_from.Close(); file_to.Close(); if (delete_file_path_from) File.Delete(file_path_from); for (int i = 0; i < key_string_bytes.Length; i += 1) key_string_bytes[i] = 0; for (int i = 0; i < key.Length; i += 1) key[i] = 0; whirlpool_digest.Reset(); serpent_engine.Reset(); pkcs7_padding = null; padded_buffered_block_cipher.Reset(); for (int i = 0; i < iv.Length; i += 1) iv[i] = 0; for (int i = 0; i < buffer_from.Length; i += 1) buffer_from[i] = 0; for (int i = 0; i < buffer_to.Length; i += 1) buffer_to[i] = 0; } catch(Exception exception) { string message; if (exception.Message.Contains("pad block corrupted")) { if (file_from != null) { file_from.Close(); } if (file_to != null) { file_to.Close(); } try { File.Delete(file_path_to); } catch(Exception) {} message = "A wrong decryption key has been provided."; } else { message = exception.Message; } alert(message, interactive); } }; cancel.Bounds = new Rectangle(200, 100, button_width, button_height); cancel.BackColor = cancel_backcolor; cancel.ForeColor = cancel_forecolor; cancel.Font = button_font; cancel.TextAlign = button_text_alignment; cancel.Text = "Cancel"; cancel.Click += (sender, e) => { form.Close(); password_1.Text = ""; password_2.Text = ""; }; form.Controls.Add(password_1_label); form.Controls.Add(password_2_label); form.Controls.Add(password_1); form.Controls.Add(password_2); form.Controls.Add(proceed); form.Controls.Add(cancel); form.ShowDialog(); }