/// <summary> /// 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的 /// </summary> /// <param name="filePath">要解密的文件</param> /// <param name="dataIndex">要从哪一个块中解密</param> /// <returns>解密后的文本</returns> public static string DecryptFromFile(this string filePath, int dataIndex) { if (dataIndex > 10 && dataIndex < 1) { return(""); } using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true); using var decryptor = _rc2Csp.CreateDecryptor(_key, _iv); var msDecrypt = new MemoryStream(); using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write); var index = new byte[10261]; tmpFileStream.Read(index, 0, 10261); var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2]; var tmp = new byte[count]; Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count); csDecrypt.Write(tmp, 0, count); csDecrypt.FlushFinalBlock(); var decrypted = msDecrypt.ToArray(); return(_textConverter.GetString(decrypted, 0, decrypted.Length)); }
public static bool Test() { Random rnd = new Random(); // create a random array of random bytes int len = rnd.Next(1000000); byte[] plain = new byte[len]; rnd.NextBytes(plain); Console.Write("Working with " + len + " bytes of plaintext..."); // encrypt with salt RC2CryptoServiceProvider rc2s = new RC2CryptoServiceProvider(); rc2s.UseSalt = true; rc2s.Key = new byte[]{1,2,3,4,5}; byte[] encrypted = (rc2s.CreateEncryptor()).TransformFinalBlock(plain, 0, plain.Length); // decrypt with salt RC2CryptoServiceProvider rc2sd = new RC2CryptoServiceProvider(); rc2sd.UseSalt = true; rc2sd.Key = rc2s.Key; rc2sd.IV = rc2s.IV; byte[] decrypted = (rc2sd.CreateDecryptor()).TransformFinalBlock(encrypted, 0, encrypted.Length); if (CompareSlow(plain, decrypted)) { Console.WriteLine("OK."); return true; } else { Console.WriteLine("FAIL."); return false; } }
public static string Desencriptar(string texto, byte[] _key, byte[] _iv) { List <byte> codigos = new List <byte>(); foreach (char letra in texto) { codigos.Add((byte)letra); } RC2CryptoServiceProvider rC2 = new RC2CryptoServiceProvider(); ICryptoTransform desencriptador = rC2.CreateDecryptor(_key, _iv); MemoryStream memoria = new MemoryStream(codigos.ToArray()); CryptoStream cs = new CryptoStream(memoria, desencriptador, CryptoStreamMode.Read); StringBuilder sb = new StringBuilder(); int b = 0; do { b = cs.ReadByte(); if (b != -1) { sb.Append((char)b); } } while (b != -1); return(sb.ToString()); }
/// <summary> /// RC2解密 /// </summary> /// <param name="decryptString">密文</param> /// <param name="decryptKey">密匙(必须为5-16位)</param> /// <returns></returns> private static string RC2Decrypt(string decryptString, string decryptKey) { string returnValue; if (decryptKey.Length < 5 && decryptKey.Length > 16) { throw new Exception("Encrypt key need between 5-16"); } try { byte[] temp = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; RC2CryptoServiceProvider rC2 = new RC2CryptoServiceProvider(); byte[] byteDecrytString = Convert.FromBase64String(decryptString); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, rC2.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), temp), CryptoStreamMode.Write); cryptoStream.Write(byteDecrytString, 0, byteDecrytString.Length); cryptoStream.FlushFinalBlock(); returnValue = Encoding.Default.GetString(memoryStream.ToArray()); } catch (Exception ex) { throw ex; } return(returnValue); }
/// <summary> /// Decrypt incoming message /// </summary> public bool Decrypt(NetIncomingMessage msg) { try { // nested usings are fun! using (RC2CryptoServiceProvider rc2CryptoServiceProvider = new RC2CryptoServiceProvider { KeySize = m_bitSize, Mode = CipherMode.CBC }) { using (ICryptoTransform cryptoTransform = rc2CryptoServiceProvider.CreateDecryptor(m_key, m_iv)) { using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write)) { cryptoStream.Write(msg.m_data, 0, msg.m_data.Length); } msg.m_data = memoryStream.ToArray(); } } } } catch { return(false); } return(true); }
// RC2 알고리즘으로 암호화된 문자열을 받아서 복호화 한 후 암호화 이전의 원래 문자열을 Return 함 public static String Decrypt(String message, String key, String IV) { byte[] pbyteKey = Encoding.UTF8.GetBytes(key); byte[] pbyteIV = Encoding.UTF8.GetBytes(IV); String strReturn; if (pbyteKey.Length != 8) { throw (new Exception("Invalid key. Key length must be 8 byte.")); } using (RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider()) { rc2CSP.Mode = CipherMode.CBC; rc2CSP.Padding = PaddingMode.PKCS7; rc2CSP.Key = pbyteKey; rc2CSP.IV = pbyteIV; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cryptStream = new CryptoStream(ms, rc2CSP.CreateDecryptor(), CryptoStreamMode.Write)) { message = message.Replace(" ", "+"); byte[] data = Convert.FromBase64String(message); cryptStream.Write(data, 0, data.Length); } strReturn = Encoding.UTF8.GetString(ms.GetBuffer()).Trim('\0'); } } return(strReturn); }
public static string DecryptRc2(string srcStr, string sKey = "ABCDEF987654321") { if (string.IsNullOrEmpty(srcStr) || string.IsNullOrEmpty(sKey)) { return(null); } byte[] InByteArray = Convert.FromBase64String(srcStr); byte[] key = Encoding.UTF8.GetBytes(sKey); byte[] IV = Encoding.UTF8.GetBytes(sKey.Substring(0, sKey.Length - 2)); using (RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider()) { ICryptoTransform Decryptor = rc2.CreateDecryptor(key, IV); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, Decryptor, CryptoStreamMode.Write)) { cs.Write(InByteArray, 0, InByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string DesStr = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return(DesStr); } } }
public static bool DecryptFile(string sInputFilename, string sOutputFilename, string sKey) { try { RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); Rfc2898DeriveBytes pwdGen = getKey(sKey); rc2.Key = pwdGen.GetBytes(16); rc2.IV = pwdGen.GetBytes(8); using (FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read)) { ICryptoTransform desdecrypt = rc2.CreateDecryptor(); using (CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)) { using (StreamWriter fsDecrypted = new StreamWriter(sOutputFilename)) { fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd()); fsDecrypted.Flush(); fsDecrypted.Close(); } } } return(true); } catch (Exception) { MessageBox.Show("Incorrect Password"); return(false); } }
public string DecryptText(string encryptedText) { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv)); using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText))) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { List<Byte> bytes = new List<byte>(); int b; do { b = csDecrypt.ReadByte(); if (b != -1) { bytes.Add(Convert.ToByte(b)); } } while (b != -1); return Encoding.Unicode.GetString(bytes.ToArray()); } } }
public static string decrypt(string encrypted) { var rc2CSP = new RC2CryptoServiceProvider(); byte[] key = Encoding.Default.GetBytes(Settings.Default.authKey); byte[] IV = Encoding.Default.GetBytes(Settings.Default.authIV); var decryptor = rc2CSP.CreateDecryptor(key, IV); var msDecrypt = new MemoryStream(Encoding.Default.GetBytes(encrypted)); var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); StringBuilder result = new StringBuilder(); int b = 0; do { b = csDecrypt.ReadByte(); if (b != -1) { result.Append((char)b); } } while (b != -1); return(result.ToString()); }
/// <summary> /// 解密数据 /// </summary> /// <param name="toDecryptText">待解密的文本</param> /// <returns>解密的文本</returns> public static string Decrypt(string toDecryptText) { UnicodeEncoding textConverter = new UnicodeEncoding(); byte[] fromEncrypt; byte[] encrypted; //Get a decryptor that uses the same key and IV as the encryptor. ICryptoTransform decryptor = rc2CSP.CreateDecryptor(key, IV); //encrypted = textConverter.GetBytes(toDecryptText); encrypted = TextService.BufferFromHexStr(toDecryptText, false); if (encrypted == null) { return(toDecryptText); } //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); fromEncrypt = new byte[encrypted.Length]; try { //Read the data oGX of the crypto stream. int count = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); //Convert the byte array back into a string. return(textConverter.GetString(fromEncrypt, 0, count)); } catch { return(toDecryptText); } }
public static String Decrypt(String key, String value) { if (string.IsNullOrEmpty(value)) { return(null); } try { RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); if (key.Length > 128) { key = key.Substring(0, 128); } else if (String.IsNullOrEmpty(key)) { key = "default"; } else if (key.Length < 8) { key = key.PadRight(8, ' '); } byte[] PrivateKey1 = Encoding.UTF8.GetBytes(key); byte[] PrivateKey2 = Encoding.UTF8.GetBytes(key); byte[] data = Convert.FromBase64String(value); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, rc2.CreateDecryptor(PrivateKey1, PrivateKey2), CryptoStreamMode.Write); cs.Write(data, 0, data.Length); cs.FlushFinalBlock(); return(Encoding.UTF8.GetString(ms.ToArray())); } catch (Exception) { return(null); } }
//--METHOD UNTUK MENDECRYPT public string Decrypt(string encrypt, byte[] Key, byte[] iv) { string result = string.Empty; //--CREATE OBJEK RC2CryptoServiceProvider using (RC2CryptoServiceProvider rC2 = new RC2CryptoServiceProvider()) { //--MEMANGGIL METHOD CreateDecryptor ICryptoTransform decrypt = rC2.CreateDecryptor(Key, iv); //--CONVERT ENCRYPT TEXT KE BYTE ARRAY byte[] encryptArray = Convert.FromBase64String(encrypt); //--CREATE OBJEK MemoryStream using (MemoryStream ms = new MemoryStream(encryptArray)) { //--CREATE OBJEK CryptoStream using (CryptoStream cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Read)) { //--CREATE NEW BYTE ARRAY UNTUK MENYIMPAN DECRYPT BYTE ARRAY byte[] resultArray = new byte[encryptArray.Length]; //--READ DECRYPT DI MEMORY KE RESULT ARRAY cs.Read(resultArray, 0, resultArray.Length); //--CONVERT BYTE ARRAY DECRYPT TEXT KE STRING result = new ASCIIEncoding().GetString(resultArray); } } } return(result); }
}//End Function static private ICryptoTransform GetDecryptor() { RC2CryptoServiceProvider CryptoProvider = new RC2CryptoServiceProvider(); CryptoProvider.Mode = CipherMode.CBC; return(CryptoProvider.CreateDecryptor(byteKey, byteIV)); }//End Function
public static string Decrypt(this string self) { if (string.IsNullOrWhiteSpace(self) || (self.Length % 4 != 0) || !_validEncription.IsMatch(self)) { return(self); } using (var rc2CryptoServiceProvider = new RC2CryptoServiceProvider()) { var decryptor = rc2CryptoServiceProvider.CreateDecryptor(Convert.FromBase64String(RGB_KEY), Convert.FromBase64String(RGB_IV)); using (var memoryStream = new MemoryStream(Convert.FromBase64String(self))) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var bytes = new List <byte>(); int readByte; do { readByte = cryptoStream.ReadByte(); if (readByte != -1) { bytes.Add(Convert.ToByte(readByte)); } } while (readByte != -1); return(Encoding.Unicode.GetString(bytes.ToArray())); } } } }
public static string DecryptText(string encryptedText) { try { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(C_KEY), Convert.FromBase64String(C_IV)); MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); List <Byte> bytes = new List <byte>(); int b; do { b = csDecrypt.ReadByte(); if (b != -1) { bytes.Add(Convert.ToByte(b)); } } while (b != -1); return(Encoding.Unicode.GetString(bytes.ToArray())); } catch (Exception) { return(""); } }
public ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { switch (_algorithm) { case EncryptionAlgorithm.Des: DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; des.Key = bytesKey; des.IV = this._initVec; return(des.CreateDecryptor()); case EncryptionAlgorithm.Rc2: RC2 rc = new RC2CryptoServiceProvider(); rc.Mode = CipherMode.CBC; return(rc.CreateDecryptor(bytesKey, _initVec)); case EncryptionAlgorithm.Rijndael: Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; return(rijndael.CreateDecryptor(bytesKey, _initVec)); case EncryptionAlgorithm.TripleDes: TripleDES edes = new TripleDESCryptoServiceProvider(); edes.Mode = CipherMode.CBC; return(edes.CreateDecryptor(bytesKey, _initVec)); } throw new CryptographicException("Algorithm '" + _algorithm + "' not supported."); }
public static string Decrypt(this string encrypted) { if (string.IsNullOrEmpty(encrypted)) { return(string.Empty); } RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV)); using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encrypted))) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { List <Byte> bytes = new List <byte>(); int b; do { b = csDecrypt.ReadByte(); if (b != -1) { bytes.Add(Convert.ToByte(b)); } }while (b != -1); return(Encoding.Unicode.GetString(bytes.ToArray())); } } }
/// <summary> /// RC2解密 /// </summary> /// <param name="Rc2Key">密钥</param> /// <param name="Rc2IV">向量</param> /// <param name="text">原字符串</param> /// <returns></returns> public static string Decrypt(string Rc2Key, string Rc2IV, string text) { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); byte[] key = Convert.FromBase64String(Rc2Key); byte[] IV = Convert.FromBase64String(Rc2IV); byte[] encrypted = Convert.FromBase64String(text); ICryptoTransform decryptor = rc2CSP.CreateDecryptor(key, IV); using (MemoryStream msDecrypt = new MemoryStream(encrypted)) { CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); StringBuilder roundtrip = new StringBuilder(); int b = 0; do { b = csDecrypt.ReadByte(); if (b != -1) { roundtrip.Append((char)b); } } while (b != -1); return(roundtrip.ToString()); } }
/// <summary> /// Gets the crypto service provider. /// </summary> /// <param name="bytesKey">The bytes key.</param> /// <returns></returns> internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { switch (algorithmID) { case EncryptionAlgorithm.Des: DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; des.Key = bytesKey; des.IV = initVec; return(des.CreateDecryptor()); case EncryptionAlgorithm.TripleDes: TripleDES des3 = new TripleDESCryptoServiceProvider(); des3.Mode = CipherMode.CBC; return(des3.CreateDecryptor(bytesKey, initVec)); case EncryptionAlgorithm.Rc2: RC2 rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; return(rc2.CreateDecryptor(bytesKey, initVec)); case EncryptionAlgorithm.Rijndael: Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; return(rijndael.CreateDecryptor(bytesKey, initVec)); default: throw new CryptographicException("Algorithm ID '" + algorithmID + "' not supported!"); } }
/// <summary> /// Loads a key file from disk. /// </summary> /// <param name="filename">Filename to load from</param> /// <param name="ProductKey">ProductKey. will be deserialized from the stream.</param> /// <param name="FingerPrint">Machine fingerprint. Will be deserialized from the stream.</param> /// <param name="lastCheckedDate">UTC Date corresponding to the time this file was last checked. </param> /// <exception cref="FileNotFoundException">File specified does not exist.</exception> /// <remarks>In order to verify that the loaded data is valid, call IsValidKey with the ProductKey and FingerPrint.</remarks> public static void ReadKeyFile(Stream inputstream, out string ProductKey, out string FingerPrint, out DateTime lastCheckedDate, String SuretyKey, out ISerializable readthis) { //throws exceptions for all of the above. // Open the file, decrypt the contents, return the ProductKey, FingerPrint and lastCheckedDate //get the binaryreader, etc. var fr = inputstream; RC2CryptoServiceProvider rc = new RC2CryptoServiceProvider(); Rfc2898DeriveBytes pdb = GetPdb(SuretyKey); rc.Key = pdb.GetBytes(8); rc.IV = pdb.GetBytes(8); CryptoStream cs = new CryptoStream(fr, rc.CreateDecryptor(), CryptoStreamMode.Read); BinaryReader br = new BinaryReader(cs); //sw.Write(ProductKey); //sw.Write(FingerPrint); //sw.Write(lastCheckedDate.ToUniversalTime().Ticks); ProductKey = br.ReadString(); FingerPrint = br.ReadString(); long grabticks = br.ReadInt64(); BinaryFormatter bf = new BinaryFormatter(); lastCheckedDate = DateTime.FromBinary(grabticks); try { readthis = (ISerializable)bf.Deserialize(cs); } catch { readthis = null; } }
public string Decrypt(string strPassword, string strMessage) { switch (strMessage) { case "": case null: return((string)null); default: CspParameters cspParams = new CspParameters(1, "Microsoft Base Cryptographic Provider v1.0"); PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(strPassword, (byte[])null, "MD5", 1, cspParams); byte[] rgbIV = new byte[8]; byte[] numArray = passwordDeriveBytes.CryptDeriveKey("RC2", "MD5", 0, rgbIV); RC2CryptoServiceProvider cryptoServiceProvider = new RC2CryptoServiceProvider(); cryptoServiceProvider.Key = numArray; cryptoServiceProvider.IV = rgbIV; byte[] buffer = this.ConvertFromHex(strMessage); ICryptoTransform decryptor = cryptoServiceProvider.CreateDecryptor(); MemoryStream memoryStream = new MemoryStream(buffer.Length); CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read); memoryStream.Write(buffer, 0, buffer.Length); memoryStream.Position = 0L; string end = new StreamReader((Stream)cryptoStream, Encoding.Unicode).ReadToEnd(); cryptoStream.Close(); return(end); } }
public string Decrypt(string value) { using (System.Security.Cryptography.RC2 algorithm = new RC2CryptoServiceProvider()) { using (ICryptoTransform ct = algorithm.CreateDecryptor(Encoding.UTF8.GetBytes(_key) , Encoding.UTF8.GetBytes(_vectorStart))) { using (var msDados = new MemoryStream(Convert.FromBase64String(value))) { using (var cs = new CryptoStream(msDados, ct, CryptoStreamMode.Read)) { using (var msSaida = new MemoryStream()) { using (var sw = new StreamWriter(msSaida)) { sw.Write(new StreamReader(cs).ReadToEnd()); } return(Encoding.UTF8.GetString(msSaida.ToArray())); } } } } } }
public static void Decrypt_RC2(OpenFileDialog op, string password, CipherMode mode) { try { RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); rc2.Padding = PaddingMode.ISO10126; byte[] str = Convert.FromBase64String(File.ReadAllText(op.FileName)); byte[] salt1 = new byte[16]; rc2.Mode = mode; for (int i = 0; i < 16; i++)// задаем соль по конкретному алгоритму { salt1[i] = (byte)i; } Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(password, salt1, 1000); // rc2.Key = k1.GetBytes(16); //генерируем ключ byte[] salt2 = new byte[8]; for (int i = 0; i < 8; i++) { salt2[i] = (byte)(i - 9); } Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(password, salt2, 1000); // rc2.IV = k2.GetBytes(8); //генерируем вектор инициализации ICryptoTransform icrypt = rc2.CreateDecryptor(rc2.Key, rc2.IV); byte[] s = icrypt.TransformFinalBlock(str, 0, str.Length); icrypt.Dispose(); File.WriteAllBytes(op.FileName, s); } catch (Exception e) { MessageBox.Show(e.Message); } }
public static void Main() { string PlainText = "Titan"; byte[] PlainBytes = new byte[5]; PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray()); PrintByteArray(PlainBytes); byte[] CipherBytes = new byte[8]; PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null); byte[] IV = new byte[8]; byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV); PrintByteArray(Key); PrintByteArray(IV); // Now use the data to encrypt something RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); Console.WriteLine(rc2.Padding); Console.WriteLine(rc2.Mode); ICryptoTransform sse = rc2.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs1.Write(PlainBytes, 0, PlainBytes.Length); cs1.FlushFinalBlock(); CipherBytes = ms.ToArray(); cs1.Close(); Console.WriteLine(Encoding.ASCII.GetString(CipherBytes)); PrintByteArray(CipherBytes); ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV); CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read); byte[] InitialText = new byte[5]; cs2.Read(InitialText, 0, 5); Console.WriteLine(Encoding.ASCII.GetString(InitialText)); PrintByteArray(InitialText); }
public string Decrypt(string scrambledMessage) { UTF8Encoding textConverter = new UTF8Encoding(); RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); // URL decode , replace and convert from Base64 string b64mod = HttpUtility.UrlDecode(scrambledMessage); // Replace '@' back to '+' (avoid URLDecode problem) string b64 = b64mod.Replace('@', '+'); // Base64 decode byte[] encrypted = Convert.FromBase64String(b64); //Get a decryptor that uses the same key and IV as the encryptor. ICryptoTransform decryptor = rc2CSP.CreateDecryptor(ScrambleKey, ScrambleIV); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); byte[] fromEncrypt = new byte[encrypted.Length - 4]; //Read the data out of the crypto stream. byte[] length = new byte[4]; csDecrypt.Read(length, 0, 4); csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); int len = (int)length[0] | (length[1] << 8) | (length[2] << 16) | (length[3] << 24); //Convert the byte array back into a string. return(textConverter.GetString(fromEncrypt).Substring(0, len)); }
} //encrypt public static String DecryptTripleDES(String vl) { String roundtrip = ""; try { fromEncrypt = textConverter.GetBytes(vl); //Get a decryptor that uses the same key and IV as the encryptor. ICryptoTransform decryptor = rc2CSP.CreateDecryptor(key, IV); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); fromEncrypt = new byte[encrypted.Length]; //Read the data out of the crypto stream. csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); //Convert the byte array back into a string. roundtrip = textConverter.GetString(fromEncrypt); return(roundtrip); } catch (Exception e) { } return(roundtrip); return(""); } //decrypt
public static string DecryptText(string encryptedText) { var rc2CSP = new RC2CryptoServiceProvider(); var decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String("de071660"), Convert.FromBase64String("")); // var decryptor = rc2CSP.CreateDecryptor(); using (var msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText))) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { var bytes = new List <byte>(); int b; do { b = csDecrypt.ReadByte(); if (b != -1) { bytes.Add(Convert.ToByte(b)); } }while (b != -1); return(Encoding.Unicode.GetString(bytes.ToArray())); } } }
/// <summary> /// Given an IntPtr to a bufer and the number of bytes, decrypt the buffer and return an /// unencrypted text string. /// </summary> /// <param name="buffer">An IntPtr to the 'buffer' containing the encrypted string</param> /// <param name="nBytes">The number of bytes in 'buffer' to decrypt</param> /// <returns></returns> private static string DecryptLicenseString(IntPtr buffer, uint nBytes) { byte[] ba = new byte[nBytes]; for (int i = 0; i < nBytes; i++) { ba[i] = Marshal.ReadByte(buffer, i); } MemoryStream ms = new MemoryStream(ba); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider { Key = GetBytesFromHexString("7a6823a42a3a3ae27057c647db812d0"), IV = GetBytesFromHexString("827d961224d99b2d") }; CryptoStream cs = new CryptoStream(ms, rc2.CreateDecryptor(), CryptoStreamMode.Read); string licenseString = string.Empty; byte[] ba1 = new byte[4096]; int irtn = cs.Read(ba1, 0, 4096); Encoding enc = Encoding.Unicode; licenseString = enc.GetString(ba1, 0, irtn); cs.Close(); cs.Dispose(); ms.Close(); ms.Dispose(); rc2 = null; return(licenseString); }
private static Int32 DecryptId(String info) { String value = null; Int32 id = -1; var bytes = Convert.FromBase64String(info); using (var c = new RC2CryptoServiceProvider()) { var decr = c.CreateDecryptor(_key, _IV); using (MemoryStream mem = new MemoryStream(bytes)) { CryptoStream crStream = new CryptoStream(mem, decr, CryptoStreamMode.Read); var outcome = new Byte[bytes.Length]; crStream.Read(outcome, 0, outcome.Length); value = System.Text.Encoding.UTF8.GetString(outcome); } } if (!String.IsNullOrEmpty(value)) { var number = value.Split('_').Last(); Int32.TryParse(number, out id); } return(id); }
public static void GiaiMaFile(string inputFile, string outputFile, string szSecureKey, string strIV, string paddingMode, string operationMode) { FileStream inStream, outStream; inStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read); outStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write); RC2CryptoServiceProvider MyRC2 = new RC2CryptoServiceProvider(); MyRC2.Key = ASCIIEncoding.ASCII.GetBytes(szSecureKey); MyRC2.IV = ASCIIEncoding.ASCII.GetBytes(strIV); ChoseOperationMode(MyRC2, operationMode); ChosePaddingMode(MyRC2, paddingMode); ICryptoTransform MyRC2_Decryptor = MyRC2.CreateDecryptor(); CryptoStream myDecryptStream; myDecryptStream = new CryptoStream(outStream, MyRC2_Decryptor, CryptoStreamMode.Write); byte[] byteBuffer = new byte[100]; long nTotalByteInput = inStream.Length, nTotalByteWritten = 0; int nCurReadLen = 0; while (nTotalByteWritten < nTotalByteInput) { nCurReadLen = inStream.Read(byteBuffer, 0, byteBuffer.Length); myDecryptStream.Write(byteBuffer, 0, nCurReadLen); nTotalByteWritten += nCurReadLen; } inStream.Close(); outStream.Close(); myDecryptStream.Close(); }
public static string DecryptString(string MainString, string szSecureKey, string strIV, string paddingMode, string operationMode) { byte[] buffer = Convert.FromBase64String(MainString.Trim()); MemoryStream memory = new MemoryStream(buffer); RC2CryptoServiceProvider MyRC2 = new RC2CryptoServiceProvider(); MyRC2.Key = ASCIIEncoding.ASCII.GetBytes(szSecureKey); MyRC2.IV = ASCIIEncoding.ASCII.GetBytes(strIV); ChoseOperationMode(MyRC2, operationMode); ChosePaddingMode(MyRC2, paddingMode); ICryptoTransform MyRC2_Decryptor = MyRC2.CreateDecryptor(); CryptoStream myDecryptStream = new CryptoStream(memory, MyRC2_Decryptor, CryptoStreamMode.Read); StreamReader sr = new StreamReader(myDecryptStream); // Read the stream as a string. string val = sr.ReadToEnd(); // Close the streams. sr.Close(); myDecryptStream.Close(); memory.Close(); return(val); }
static public bool RC2_CBC_Symmetry_Decode_Byte(byte[] decryptByte, uint startPos, uint inLen, ref byte[] outBytes, byte[] rgbKey) { try { RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider(); MemoryStream m_stream = new MemoryStream(); CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); m_cstream.Write(decryptByte, (int)startPos, (int)inLen); m_cstream.FlushFinalBlock(); outBytes = m_stream.ToArray(); m_stream.Close(); m_stream.Dispose(); m_cstream.Close(); m_cstream.Dispose(); return true; } catch { return false; } }
/// <summary> /// 解密 /// </summary> /// <param name="str">原字符串</param> /// <returns></returns> public static string Decrypt(this string str) { try { if (string.IsNullOrEmpty(str)) return null; var decodeStr = HttpUtility.HtmlDecode(str); var sBuffer = Convert.FromBase64String(decodeStr); var provider = new RC2CryptoServiceProvider(); var rgbIV = Encoding.ASCII.GetBytes(IV); var rgbKey = Encoding.ASCII.GetBytes(Key); var decryptor = provider.CreateDecryptor(rgbKey, rgbIV); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { cs.Write(sBuffer, 0, sBuffer.Length); cs.FlushFinalBlock(); } byte[] buffer = ms.ToArray(); str = Encoding.UTF8.GetString(buffer); } return str; } catch (Exception ex) { throw new DecryptException(ex); } }