private static void EncryptDecryptAndDispose(ICryptoTransform crypto, ICryptoTransform decrypto, byte[] data) { var encryptedData = crypto.TransformFinalBlock(data, 0, data.Length); var decryptedData = decrypto.TransformFinalBlock(encryptedData, 0, encryptedData.Length); // NOTE: no need to check if they are equal //if (!decryptedData.AllEqual(data)) // throw new InvalidProgramException(); crypto.Dispose(); decrypto.Dispose(); }
public override byte[] Transform(byte[] data, TransformType type) { MemoryStream memoryStream = (MemoryStream)null; ICryptoTransform transform = (ICryptoTransform)null; DES des = DES.Create(); try { memoryStream = new MemoryStream(); des.Key = this.Key; des.IV = this.IV; transform = type != TransformType.ENCRYPT ? des.CreateDecryptor() : des.CreateEncryptor(); if (data == null || data.Length == 0) { return((byte[])null); } CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, transform, CryptoStreamMode.Write); cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); return(memoryStream.ToArray()); } catch (CryptographicException ex) { throw new CryptographicException(ex.Message); } finally { des?.Clear(); transform?.Dispose(); memoryStream.Close(); } }
public void Dispose() { _decryptor?.Dispose(); _encryptor?.Dispose(); _symmetricAlgorithm.Dispose(); }
private static string Decrypt(SymmetricAlgorithm symmetricAlgorithm, string cipherText, string salt, string key, string iv, bool useHasing) { if (string.IsNullOrWhiteSpace(cipherText)) { return(cipherText); } Init(symmetricAlgorithm, salt, key, iv, useHasing); ICryptoTransform cryptoTransform = null; string plaintext = null; try { cryptoTransform = symmetricAlgorithm.CreateDecryptor(); using (var memoryStream = new MemoryStream(Convert.FromBase64String(cipherText))) { using (var stream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read)) { using (var reader = new StreamReader(stream)) { plaintext = reader.ReadToEnd(); } } } } finally { cryptoTransform?.Dispose(); } return(plaintext); }
public async Task <Stream> OpenReadAsync(CancellationToken ct) { Stream stream = null; System.Security.Cryptography.Aes aes = null; ICryptoTransform decryptor = null; try { stream = await _fileInfo.OpenReadAsync(ct); var header = await AesHeader.ReadAsync(stream, ct); aes = CreateAes(header.Version); var key = FileSystem.ComputeKey(header.IV, header.Version); decryptor = CreateTransform(aes, key, header.IV, AesMode.Decrypt); // disposed by CryptoStream return(new CryptoStream(stream, decryptor, CryptoStreamMode.Read)); } catch { decryptor?.Dispose(); stream?.Dispose(); throw; } finally { aes?.Dispose(); } }
private static string Encrypt(SymmetricAlgorithm symmetricAlgorithm, string plainText, string salt, string key, string iv, bool useHasing) { if (string.IsNullOrWhiteSpace(plainText)) { return(plainText); } Init(symmetricAlgorithm, salt, key, iv, useHasing); ICryptoTransform cryptoTransform = null; byte[] encrypted; try { cryptoTransform = symmetricAlgorithm.CreateEncryptor(); using (var buffer = new MemoryStream()) { using (var stream = new CryptoStream(buffer, cryptoTransform, CryptoStreamMode.Write)) { using (var writer = new StreamWriter(stream, Encoding.Unicode)) { writer.Write(plainText); } encrypted = buffer.ToArray(); } } } finally { cryptoTransform?.Dispose(); } return(Convert.ToBase64String(encrypted)); }
public static string DecryptString(string str) { if (string.IsNullOrEmpty(str)) { return(""); } //DESCryptoServiceProviderオブジェクトの作成 using (var des = new System.Security.Cryptography.DESCryptoServiceProvider()) { //共有キーと初期化ベクタを決定 //パスワードをバイト配列にする var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_"); //共有キーと初期化ベクタを設定 des.Key = ResizeBytesArray(bytesKey, des.Key.Length); des.IV = ResizeBytesArray(bytesKey, des.IV.Length); //Base64で文字列をバイト配列に戻す var bytesIn = Convert.FromBase64String(str); MemoryStream msIn = null; ICryptoTransform desdecrypt = null; CryptoStream cryptStreem = null; try { //暗号化されたデータを読み込むためのMemoryStream msIn = new MemoryStream(bytesIn); //DES復号化オブジェクトの作成 desdecrypt = des.CreateDecryptor(); //読み込むためのCryptoStreamの作成 cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read); //Disposeが重複して呼ばれないようにする msIn = null; desdecrypt = null; //復号化されたデータを取得するためのStreamReader using (StreamReader srOut = new StreamReader(cryptStreem, Encoding.UTF8)) { //Disposeが重複して呼ばれないようにする cryptStreem = null; //復号化されたデータを取得する var result = srOut.ReadToEnd(); return(result); } } finally { msIn?.Dispose(); desdecrypt?.Dispose(); cryptStreem?.Dispose(); } } }
public void Dispose() { if (disposed) { return; } mTransformer?.Dispose(); disposed = true; }
public static string EncryptString(string str) { if (string.IsNullOrEmpty(str)) { return(""); } //文字列をバイト型配列にする var bytesIn = Encoding.UTF8.GetBytes(str); //DESCryptoServiceProviderオブジェクトの作成 using (var des = new DESCryptoServiceProvider()) { //共有キーと初期化ベクタを決定 //パスワードをバイト配列にする var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_"); //共有キーと初期化ベクタを設定 des.Key = ResizeBytesArray(bytesKey, des.Key.Length); des.IV = ResizeBytesArray(bytesKey, des.IV.Length); MemoryStream msOut = null; ICryptoTransform desdecrypt = null; try { //暗号化されたデータを書き出すためのMemoryStream msOut = new MemoryStream(); //DES暗号化オブジェクトの作成 desdecrypt = des.CreateEncryptor(); //書き込むためのCryptoStreamの作成 using (CryptoStream cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write)) { //Disposeが重複して呼ばれないようにする MemoryStream msTmp = msOut; msOut = null; desdecrypt = null; //書き込む cryptStream.Write(bytesIn, 0, bytesIn.Length); cryptStream.FlushFinalBlock(); //暗号化されたデータを取得 var bytesOut = msTmp.ToArray(); //Base64で文字列に変更して結果を返す return(Convert.ToBase64String(bytesOut)); } } finally { msOut?.Dispose(); desdecrypt?.Dispose(); } } }
public void Dispose() { _encryptor?.Dispose(); _decryptor?.Dispose(); if (_disposeAlgorithm) { _algorithm.Dispose(); } }
internal static byte[] TripleDESKeyWrapDecrypt(byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData) { // Check to see whether the length of the encrypted key is reasonable if (rgbEncryptedWrappedKeyData.Length != 32 && rgbEncryptedWrappedKeyData.Length != 40 && rgbEncryptedWrappedKeyData.Length != 48) { throw new CryptographicException(SR.Cryptography_Xml_KW_BadKeySize); } TripleDES tripleDES = null; ICryptoTransform dec1 = null; ICryptoTransform dec2 = null; try { tripleDES = TripleDES.Create(); // Assume no padding, use CBC mode tripleDES.Padding = PaddingMode.None; dec1 = tripleDES.CreateDecryptor(rgbKey, s_rgbTripleDES_KW_IV); byte[] temp2 = dec1.TransformFinalBlock(rgbEncryptedWrappedKeyData, 0, rgbEncryptedWrappedKeyData.Length); Array.Reverse(temp2); // Get the IV and temp1 byte[] rgbIV = new byte[8]; Buffer.BlockCopy(temp2, 0, rgbIV, 0, 8); byte[] temp1 = new byte[temp2.Length - rgbIV.Length]; Buffer.BlockCopy(temp2, 8, temp1, 0, temp1.Length); dec2 = tripleDES.CreateDecryptor(rgbKey, rgbIV); byte[] rgbWKCKS = dec2.TransformFinalBlock(temp1, 0, temp1.Length); // checksum the key byte[] rgbWrappedKeyData = new byte[rgbWKCKS.Length - 8]; Buffer.BlockCopy(rgbWKCKS, 0, rgbWrappedKeyData, 0, rgbWrappedKeyData.Length); using (var sha = SHA1.Create()) { byte[] rgbCKS = sha.ComputeHash(rgbWrappedKeyData); for (int index = rgbWrappedKeyData.Length, index1 = 0; index < rgbWKCKS.Length; index++, index1++) { if (rgbWKCKS[index] != rgbCKS[index1]) { throw new CryptographicException(SR.Cryptography_Xml_BadWrappedKeySize); } } return(rgbWrappedKeyData); } } finally { dec2?.Dispose(); dec1?.Dispose(); tripleDES?.Dispose(); } }
protected override void Dispose(bool disposing) { if (disposing) { encryptor?.Dispose(); aesAlg?.Dispose(); if (autoDisposeBaseStream) { baseStream?.Dispose(); } } base.Dispose(disposing); }
protected override void Dispose(bool disposing) { if (disposing) { _encryptor?.Dispose(); _aes?.Dispose(); if (AutoDisposeBaseStream) { _baseStream?.Dispose(); } } base.Dispose(disposing); }
internal static byte[] TripleDESKeyWrapEncrypt(byte[] rgbKey, byte[] rgbWrappedKeyData) { byte[] rgbCKS; using (var sha = SHA1.Create()) { // checksum the key rgbCKS = sha.ComputeHash(rgbWrappedKeyData); } // generate a random IV byte[] rgbIV = new byte[8]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(rgbIV); } // rgbWKCS = rgbWrappedKeyData | (first 8 bytes of the hash) byte[] rgbWKCKS = new byte[rgbWrappedKeyData.Length + 8]; TripleDES tripleDES = null; ICryptoTransform enc1 = null; ICryptoTransform enc2 = null; try { tripleDES = TripleDES.Create(); // Don't add padding, use CBC mode: for example, a 192 bits key will yield 40 bytes of encrypted data tripleDES.Padding = PaddingMode.None; enc1 = tripleDES.CreateEncryptor(rgbKey, rgbIV); enc2 = tripleDES.CreateEncryptor(rgbKey, s_rgbTripleDES_KW_IV); Buffer.BlockCopy(rgbWrappedKeyData, 0, rgbWKCKS, 0, rgbWrappedKeyData.Length); Buffer.BlockCopy(rgbCKS, 0, rgbWKCKS, rgbWrappedKeyData.Length, 8); byte[] temp1 = enc1.TransformFinalBlock(rgbWKCKS, 0, rgbWKCKS.Length); byte[] temp2 = new byte[rgbIV.Length + temp1.Length]; Buffer.BlockCopy(rgbIV, 0, temp2, 0, rgbIV.Length); Buffer.BlockCopy(temp1, 0, temp2, rgbIV.Length, temp1.Length); // temp2 = REV (rgbIV | E_k(rgbWrappedKeyData | rgbCKS)) Array.Reverse(temp2); return(enc2.TransformFinalBlock(temp2, 0, temp2.Length)); } finally { enc2?.Dispose(); enc1?.Dispose(); tripleDES?.Dispose(); } }
static string Key = "bV9yJ8R4mh5ujbUCk8qLjeQky9s3Xgmk"; //32 char 256bits public static string Encrypt(string unencrypted) { byte[] textBytes = ASCIIEncoding.ASCII.GetBytes(unencrypted.ToCharArray()); AesCryptoServiceProvider enDec = new AesCryptoServiceProvider(); enDec.BlockSize = 128; enDec.KeySize = 256; enDec.Key = ASCIIEncoding.ASCII.GetBytes(Key); enDec.IV = ASCIIEncoding.ASCII.GetBytes(IV); enDec.Padding = PaddingMode.PKCS7; enDec.Mode = CipherMode.CBC; ICryptoTransform iCrypt = enDec.CreateEncryptor(enDec.Key, enDec.IV); byte[] enc = iCrypt.TransformFinalBlock(textBytes, 0, textBytes.Length); iCrypt.Dispose(); return(Convert.ToBase64String(enc)); }
public static string Decrypt(string encrypted) { byte[] encryptedbytes = Convert.FromBase64String(encrypted); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.BlockSize = 128; aes.KeySize = 256; aes.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key); aes.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV); aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV); byte[] secret = crypto.TransformFinalBlock(encryptedbytes, 0, encryptedbytes.Length); crypto.Dispose(); return(System.Text.ASCIIEncoding.ASCII.GetString(secret)); }
public string Encrypt(string text) { byte[] plaintextbytes = System.Text.Encoding.UTF8.GetBytes(text); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.BlockSize = 128; aes.KeySize = 256; aes.Key = System.Text.Encoding.UTF8.GetBytes(Key); aes.IV = System.Text.Encoding.UTF8.GetBytes(IV); aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; ICryptoTransform crypto = aes.CreateEncryptor(aes.Key, aes.IV); byte[] encrypted = crypto.TransformFinalBlock(plaintextbytes, 0, plaintextbytes.Length); crypto.Dispose(); return(Convert.ToBase64String(encrypted)); }
public string Decrypted(string encrypted) { byte[] textbytes = Convert.FromBase64String(encrypted); AesCryptoServiceProvider endec = new AesCryptoServiceProvider(); endec.BlockSize = 128; endec.KeySize = 256; endec.IV = ASCIIEncoding.ASCII.GetBytes(IV); endec.Key = ASCIIEncoding.ASCII.GetBytes(Key); endec.Padding = PaddingMode.PKCS7; endec.Mode = CipherMode.CBC; ICryptoTransform icrypt = endec.CreateDecryptor(endec.Key, endec.IV); byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length); icrypt.Dispose(); return(System.Text.ASCIIEncoding.ASCII.GetString(enc)); }
/// <summary> /// DES 加密 /// </summary> /// <param name="EncryptKey"></param> /// <param name="str">明文</param> /// <param name="_encoding"></param> /// <returns></returns> public string DES3Encrypt ( string EncryptKey, string str, System.Text.Encoding _encoding ) { string theResult = ""; TripleDESCryptoServiceProvider DES = null; ICryptoTransform desEncryptValue = null; try { DES = new TripleDESCryptoServiceProvider(); DES.Key = _encoding.GetBytes(EncryptKey); DES.Mode = CipherMode.ECB; desEncryptValue = DES.CreateEncryptor(); byte[] Buffer = _encoding.GetBytes(str); theResult = Convert.ToBase64String(desEncryptValue.TransformFinalBlock(Buffer, 0, Buffer.Length)); } catch (Exception err) { throw err; } finally { if (desEncryptValue != null) { desEncryptValue.Dispose(); desEncryptValue = null; } if (DES != null) { DES = null; } } return(theResult); }
/// <summary> /// Decrypts a BASE64 encoded string of encrypted data, returns a plain string /// </summary> /// <param name="base64StringToDecrypt">an Aes encrypted AND base64 encoded string</param> /// <param name="passphrase">The passphrase.</param> /// <returns>returns a plain string</returns> public static string DecryptString(string base64StringToDecrypt) { //Set up the encryption objects using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passPhrase))) { byte[] RawBytes = null; String status = "aaaaaaaaaa000000000"; MemoryStream msD = null; CryptoStream csD = null; StreamReader sr = null; // string filepath = @"c:\temp\posttestLog\"; RawBytes = Convert.FromBase64String(base64StringToDecrypt); //System.IO.File.WriteAllText(filepath + "bese64.txt", base64StringToDecrypt + "=RawBytes>"+RawBytes.Length); //byte[] RawBytes = ConvertStringToByte(base64StringToDecrypt); ICryptoTransform ictD = acsp.CreateDecryptor(); //status = "aaaaaaaaaa1111111"; //RawBytes now contains original byte array, still in Encrypted state //Decrypt into stream msD = new MemoryStream(RawBytes, 0, RawBytes.Length); //status = "aaaaaaaaaa222222222"; csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read); //status = "aaaaaaaaaa3333333333"; //csD now contains original byte array, fully decrypted sr = new StreamReader(csD); status = sr.ReadToEnd(); //status = "aaaaaaaaaa4444444"; /* 20120614 add release method */ msD.Close(); csD.Close(); sr.Close(); ictD.Dispose(); sr = null; msD = null; csD = null; ictD = null; RawBytes = null; //return the content of msD as a regular string return(status); } }
public string Decrypt(string value) { byte[] numArray; int num; ICryptoTransform cryptoTransform = null; MemoryStream memoryStream = null; CryptoStream cryptoStream = null; var numArray1 = Convert.FromBase64String(value); var rijndaelManaged = new RijndaelManaged(); using (rijndaelManaged) { try { cryptoTransform = rijndaelManaged.CreateDecryptor(PasskeyBytes, InitVectorBytes); memoryStream = new MemoryStream(numArray1); cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read); numArray = new byte[numArray1.Length]; num = cryptoStream.Read(numArray, 0, numArray1.Length); cryptoStream.Close(); cryptoStream = null; memoryStream = null; } finally { if (cryptoStream != null) { cryptoStream.Dispose(); memoryStream = null; } if (memoryStream != null) { memoryStream.Dispose(); } if (cryptoTransform != null) { cryptoTransform.Dispose(); } rijndaelManaged.Clear(); } } var nums = new List <byte>(numArray); return(Encoding.Unicode.GetString(nums.GetRange(0, num).ToArray())); }
public void Decrypt(byte[] input, int offset, int length, Stream output) { int blockSize = _rijndael.BlockSize / 8; if (length < blockSize) { return; } byte[] tmp = new byte[blockSize]; Array.Copy(input, offset, tmp, 0, blockSize); _rijndael.IV = tmp; ICryptoTransform cryptoTransform = _rijndael.CreateDecryptor(); int count = length - blockSize; if (count % blockSize == 0) { count = count / blockSize; } else { count = count / blockSize + 1; } byte[] buf = new byte[blockSize]; int off = offset + blockSize; try { for (int i = 0; i < count - 1; ++i) { cryptoTransform.TransformBlock(input, off, blockSize, buf, 0); off += blockSize; if (i != 0) { output.Write(buf, 0, blockSize); } } buf = cryptoTransform.TransformFinalBlock(input, off, offset + length - off); output.Write(buf, 0, buf.Length); } catch { } cryptoTransform.Dispose(); }
// ------------------------------------------------------------------------------- /// <summary> /// SimpleEncrypts the plaintext. /// </summary> /// <param name="plaintext">The plaintext to be encrypted.</param> /// <returns>The encrypted plaintext (-> ciphertext).</returns> private byte[] SimpleEncrypt(byte[] plaintext) { byte[] ciphertext = null; MemoryStream memoryStream = new MemoryStream(); byte[] IV = new byte[16]; //Creates the default implementation, which is RijndaelManaged. SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); //RNGCryptoServiceProvider is an implementation of a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // The array is now filled with cryptographically strong random bytes, and none are zero. rng.GetNonZeroBytes(IV); // creates a symmetric encryptor object with the specified Key and initialization vector (IV). ICryptoTransform encryptor = rijn.CreateEncryptor(this.key, IV); // write the unencrypted initialization vector memoryStream.Write(IV, 0, IV.Length); // prepare the Crypto Stream CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); // write plaintext into compressed and encrypted stream cryptoStream.Write(plaintext, 0, plaintext.Length); cryptoStream.Close(); cryptoStream.Clear(); // Umwandlung in einen Base64 String, damit die Daten auch serialisiert werden können (.xml) byte[] binaryData = memoryStream.ToArray(); string base64String = Convert.ToBase64String(binaryData); ciphertext = AnsiStringToByteArray(base64String); // Speicher frei geben memoryStream.Close(); encryptor.Dispose(); rijn.Clear(); return(ciphertext); }
public byte[] EncryptData(byte[] bytIn) { byte[] buffer = null; MemoryStream stream = null; TripleDESCryptoServiceProvider provider = null; CryptoStream stream2 = null; ICryptoTransform transform = null; try { stream = new MemoryStream(); provider = new TripleDESCryptoServiceProvider(); transform = provider.CreateEncryptor(key, iv); stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write); stream2.Write(bytIn, 0, bytIn.Length); stream2.FlushFinalBlock(); buffer = stream.ToArray(); } catch { } finally { if (stream2 != null) { stream2.Clear(); stream2 = null; } if (transform != null) { transform.Dispose(); transform = null; } if (provider != null) { provider.Clear(); provider = null; } if (stream != null) { stream = null; } } return(buffer); }
static string key = "nogaroka"; //8 charov #endregion ; static string EncryptData(string msg) { byte[] bytes = Encoding.UTF8.GetBytes(msg.ToCharArray(), 0, msg.Length); //ustvarimo array bytov in ga napolnimo z sporocilom, ki ga zelimo kodirat DESCryptoServiceProvider encoder = new DESCryptoServiceProvider(); //class za enkripcijo in dekripcijo po DES(data Encryption Standard) algoritmu encoder.BlockSize = 64; //nastavimo dolzina bit stringa IV encoder.KeySize = 64; //nastavimo dolzina bit stringa kljuca encoder.Key = Encoding.UTF8.GetBytes(key.ToCharArray(), 0, key.Length); //encoderju nastavimo kljuc v bytih encoder.IV = Encoding.UTF8.GetBytes(IV.ToCharArray(), 0, IV.Length); //encoderju nastavimo IV v bytih encoder.Padding = PaddingMode.PKCS7; //Nastavimo padding na PKCS7 (standard). S tem preprecimo predvidljivost. encoder.Mode = CipherMode.CBC; //Nastavimo nacin na CBC(cipher block chaining) ICryptoTransform crypt = encoder.CreateEncryptor(encoder.Key, encoder.IV); //ustvari enkriptor byte[] enc = crypt.TransformFinalBlock(bytes, 0, bytes.Length); //kriptira sporocilo crypt.Dispose(); //odstrani neuporabne resource return(Convert.ToBase64String(enc)); //pretvori byte v string }
static string DecryptData(string msg) { byte[] bytes = Convert.FromBase64String(msg); DESCryptoServiceProvider decoder = new DESCryptoServiceProvider(); decoder.BlockSize = 64; decoder.KeySize = 64; decoder.Key = Encoding.UTF8.GetBytes(key.ToCharArray(), 0, key.Length); decoder.IV = Encoding.UTF8.GetBytes(IV.ToCharArray(), 0, IV.Length); decoder.Padding = PaddingMode.PKCS7; decoder.Mode = CipherMode.CBC; ICryptoTransform crypt = decoder.CreateDecryptor(decoder.Key, decoder.IV); byte[] dec = crypt.TransformFinalBlock(bytes, 0, bytes.Length); crypt.Dispose(); return(Encoding.UTF8.GetString(dec, 0, dec.Length)); }
/// <summary> /// Generic DES Decryption Function /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <param name="padding"></param> /// <param name="mode"></param> /// <returns></returns> internal static byte[] Decrypt(byte[] data, byte[] key, byte[] iv, PaddingMode padding, CipherMode mode) { try { var algorithm = new DESCryptoServiceProvider { Padding = padding, Mode = mode }; ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv); var retVal = Crypter(data, key, iv, decryptor); decryptor.Dispose(); algorithm.Dispose(); return(retVal); } catch (CryptographicException ex) { throw new ApplicationException("Error during des decryption of license code.", ex); } }
public string Encrypt(string Decryptd) { byte[] byteEn = ASCIIEncoding.ASCII.GetBytes(Decryptd); AesCryptoServiceProvider encod = new AesCryptoServiceProvider(); encod.BlockSize = 128; encod.KeySize = 256; encod.Key = ASCIIEncoding.ASCII.GetBytes(Key); encod.IV = ASCIIEncoding.ASCII.GetBytes(Algor); encod.Padding = PaddingMode.PKCS7; encod.Mode = CipherMode.CBC; ICryptoTransform trnas = encod.CreateEncryptor(encod.Key, encod.IV); byte[] enc = trnas.TransformFinalBlock(byteEn, 0, byteEn.Length); trnas.Dispose(); return(Convert.ToBase64String(enc)); }
protected virtual void Dispose(bool disposing) { if (!disposing) { return; } if (_transform != null) { _transform.Dispose(); _transform = null; } if (_algorithm != null) { // Clear() is implemented as a call to Dispose(), but Mono does not implement Dispose(), so this avoids a MoMA warning. _algorithm.Clear(); _algorithm = null; } }
public static byte[] DecryptAES(byte[] srcData, string pw = "illusion", string salt = "unityunity") { RijndaelManaged rijndaelManaged = new RijndaelManaged(); rijndaelManaged.KeySize = 128; rijndaelManaged.BlockSize = 128; byte[] bytes = Encoding.UTF8.GetBytes(salt); Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(pw, bytes); rfc2898DeriveBytes.IterationCount = 1000; rijndaelManaged.Key = rfc2898DeriveBytes.GetBytes(rijndaelManaged.KeySize / 8); rijndaelManaged.IV = rfc2898DeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8); ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(); byte[] numArray = decryptor.TransformFinalBlock(srcData, 0, srcData.Length); decryptor.Dispose(); return(numArray); }
public string RijndaelCipherText(string plaintext) // { string key = "jhIBty*&%98BjKMhgu#@$_)mJEDYT%$J"; //32byte string iv = "jHYjnUyt435#$VHJ"; //16byte //RijndaelManaged byte[] plainbytes = UTF8Encoding.UTF8.GetBytes(plaintext); RijndaelManaged rdm = new RijndaelManaged(); rdm.BlockSize = 128; rdm.KeySize = 256; ICryptoTransform ict = rdm.CreateEncryptor(UTF8Encoding.UTF8.GetBytes(key), UTF8Encoding.UTF8.GetBytes(iv));// byte[] encryptedbytearr = ict.TransformFinalBlock(plainbytes, 0, plainbytes.Length); ict.Dispose(); rdm.Dispose(); return(Convert.ToBase64String(encryptedbytearr)); }
public void DecryptRecord(byte[] fragment, out byte[] dcrFragment, out byte[] dcrMAC) { int fragmentSize = 0; int paddingLength = 0; // Decrypt message fragment ( fragment + mac [+ padding + padding_length] ) DecryptionTransform = DecryptionAlgorithm.CreateDecryptor(ServerWriteKey, LastCipherTextBlock); byte [] bOutput = this.DecryptionTransform.TransformFinalBlock(fragment, 0, fragment.Length); DecryptionTransform.Dispose(); //this.DecryptionTransform.TransformBlock(fragment, 0, fragment.Length, bOutput, 0); if (bOutput.Length != fragment.Length) { /// It appears the above may remove all the padding, but lease the padding length byte on /// dcrFragment = new byte[bOutput.Length - this.SecurityParameters.Cipher.HashSize-1]; dcrMAC = new byte[this.SecurityParameters.Cipher.HashSize]; Array.Copy(bOutput, 0, dcrFragment, 0, dcrFragment.Length); Array.Copy(bOutput, dcrFragment.Length, dcrMAC, 0, dcrMAC.Length); return; } fragment = bOutput; // optimization: decrypt "in place", worst case: padding will reduce the size of the data // this will cut in half the memory allocations (dcrFragment and dcrMAC remains) // Calculate fragment size // Calculate padding_length paddingLength = fragment[fragment.Length - 1]; ///// Not sure what's going on, but the Server Finished handshake message has it's padding byte set to 0, and there are 11 bytes filled with 0s, ///// I can't find documentation on why, so have to assume it's a bug in openssl... see if we can work around it ///// //if (paddingLength == 0) // paddingLength = 11; if (paddingLength > fragment.Length) throw new Exception("Decryption Failed, padding length is longer than the fragment length"); fragmentSize = (fragment.Length - (paddingLength + 1)) - this.SecurityParameters.Cipher.HashSize; dcrFragment = new byte[fragmentSize]; dcrMAC = new byte[this.SecurityParameters.Cipher.HashSize]; Array.Copy(fragment, 0, dcrFragment, 0, dcrFragment.Length); Array.Copy(fragment, dcrFragment.Length, dcrMAC, 0, dcrMAC.Length); }
/// <summary> /// Process the data with CryptoStream /// </summary> protected byte[] Process(byte[] data, int startIndex, int count, ICryptoTransform cryptor) { // // the memory stream granularity must match the block size // of the current cryptographic operation // int capacity = count; int mod = count % algorithm.BlockSize; if (mod > 0) { capacity += (algorithm.BlockSize - mod); } MemoryStream memoryStream = new MemoryStream(capacity); CryptoStream cryptoStream = new CryptoStream( memoryStream, cryptor, CryptoStreamMode.Write); cryptoStream.Write(data, startIndex, count); cryptoStream.FlushFinalBlock(); cryptoStream.Close(); cryptoStream = null; cryptor.Dispose(); cryptor = null; return memoryStream.ToArray(); }
private static void ReturnCryptoTransform(bool fEncrypt, ICryptoTransform ct, bool useValidationSymAlgo, bool legacyMode) { ct.Dispose(); }