/// <summary> /// 将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块, /// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但 /// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。 /// </summary> /// <param name="toEncryptText">要加密的文本数据</param> /// <param name="filePath">要写入的文件</param> /// <param name="dataIndex">写入第几块,取值为1--10</param> /// <returns>是否操作成功</returns> public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex) { var r = false; if ((dataIndex > 10) && (dataIndex < 1)) { return(r); } //打开要写入的文件,主要是为了保持原文件的内容不丢失 var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true); var index = new byte[10261]; //将读取的内容写到byte数组 tmpFileStream.Read(index, 0, 10261); tmpFileStream.Close(); //定义基本的加密转换运算 using var Encryptor = _rc2Csp.CreateEncryptor(_key, _iv); var msEncrypt = new MemoryStream(); //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。 using var csEncrypt = new CryptoStream(msEncrypt, Encryptor, CryptoStreamMode.Write); //将要加密的文本转换成UTF-16 编码,保存在tmp数组。 var tmp = _textConverter.GetBytes(toEncryptText); //将tmp输入csEncrypt,将通过Encryptor来加密。 csEncrypt.Write(tmp, 0, tmp.Length); //输出到msEnctypt csEncrypt.FlushFinalBlock(); //将流转成byte[] var encrypted = msEncrypt.ToArray(); if (encrypted.Length > 1024) { return(false); } //得到加密后数据的大小,将结果存在指定的位置。 index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128)); index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128)); //将加密后的结果写入index(覆盖) for (var i = 0; i < encrypted.Length; i++) { index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i]; } //建立文件流 tmpFileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true); //写文件 tmpFileStream.Write(index, 0, 10261); tmpFileStream.Flush(); r = true; tmpFileStream.Close(); return(r); }
public string Encrypt(string strPassword, string strMessage) { ///linux 不能使用Microsoft Base Cryptographic Provider v1.0 加密 固定返回 return("fb239b54a07d2fbc10551b4a56315bd4843bef9b6ce3b7bd"); 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[] bytes = new UnicodeEncoding().GetBytes(strMessage); ICryptoTransform encryptor = cryptoServiceProvider.CreateEncryptor(); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock(); byte[] array = memoryStream.ToArray(); cryptoStream.Close(); return(this.ConvertToHex(array)); }
public static String Encrypt(String key, String text) { 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 = Encoding.UTF8.GetBytes(text); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, rc2.CreateEncryptor(PrivateKey1, PrivateKey2), CryptoStreamMode.Write); cs.Write(Data, 0, Data.Length); cs.FlushFinalBlock(); return(Convert.ToBase64String(ms.ToArray())); }
/// <summary> /// RC2加密 /// </summary> /// <param name="encryptString">待加密的密文</param> /// <param name="encryptKey">密匙(必须为5-16位)</param> /// <returns></returns> private static string RC2Encrypt(string encryptString, string encryptKey) { string returnValue; if (encryptKey.Length < 5 && encryptKey.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[] byteEncryptString = Encoding.Default.GetBytes(encryptString); MemoryStream memorystream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memorystream, rC2.CreateEncryptor(Encoding.Default.GetBytes(encryptKey), temp), CryptoStreamMode.Write); cryptoStream.Write(byteEncryptString, 0, byteEncryptString.Length); cryptoStream.FlushFinalBlock(); returnValue = Convert.ToBase64String(memorystream.ToArray()); } catch (Exception ex) { throw ex; } return(returnValue); }
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 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 by default RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); rc2.Key = new byte[]{5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0}; // salt only takes effect when we use a 40-bit key byte[] encrypted1 = (rc2.CreateEncryptor()).TransformFinalBlock(plain, 0, plain.Length); // encrypt with salt RC2CryptoServiceProvider rc2s = new RC2CryptoServiceProvider(); rc2s.UseSalt = true; rc2s.Key = new byte[]{1,2,3,4,5}; rc2s.IV = rc2.IV; byte[] encrypted2 = (rc2s.CreateEncryptor()).TransformFinalBlock(plain, 0, plain.Length); if (CompareSlow(encrypted1, encrypted2)) { Console.WriteLine("OK."); return true; } else { Console.WriteLine("FAIL."); return false; } }
public static String Encrypt(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.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] data = Encoding.UTF8.GetBytes(message.ToCharArray()); cryptStream.Write(data, 0, data.Length); } strReturn = Convert.ToBase64String(ms.ToArray()); } } return(strReturn); }
/// <summary> /// Encrypts the string. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncryptString(string value) { if (value == null) { return(new ArgumentNullException(nameof(value)).ToString()); } var ms = new MemoryStream(); switch (_encryptionMethod) { case (int)CryptoProvider.Des: var providerDes = new DESCryptoServiceProvider(); var cs = new CryptoStream(ms, providerDes.CreateEncryptor(Key, IV), CryptoStreamMode.Write); var sw = new StreamWriter(cs); sw.Write(value); sw.Flush(); cs.FlushFinalBlock(); break; case (int)CryptoProvider.Rc2: var providerRc2 = new RC2CryptoServiceProvider(); cs = new CryptoStream(ms, providerRc2.CreateEncryptor(Key, IV), CryptoStreamMode.Write); sw = new StreamWriter(cs); sw.Write(value); sw.Flush(); cs.FlushFinalBlock(); break; case (int)CryptoProvider.TripleDes: var provider3Des = new TripleDESCryptoServiceProvider(); cs = new CryptoStream(ms, provider3Des.CreateEncryptor(Key, IV), CryptoStreamMode.Write); sw = new StreamWriter(cs); sw.Write(value); sw.Flush(); cs.FlushFinalBlock(); break; case (int)CryptoProvider.Rijndael: var providerRij = new RijndaelManaged(); cs = new CryptoStream(ms, providerRij.CreateEncryptor(Key, IV), CryptoStreamMode.Write); sw = new StreamWriter(cs); sw.Write(value); sw.Flush(); cs.FlushFinalBlock(); break; } ms.Flush(); return(Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length)); }
/// <summary> /// 加密数据 /// </summary> /// <param name="toEncryptText">待加密的文本</param> /// <returns>经过加密的文本</returns> public static string Encrypt(string toEncryptText) { UnicodeEncoding textConverter = new UnicodeEncoding(); byte[] encrypted; byte[] toEncrypt; //Get an encryptor. ICryptoTransform encryptor = rc2CSP.CreateEncryptor(key, IV); //Encrypt the data. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); //Convert the data to a byte array. toEncrypt = textConverter.GetBytes(toEncryptText); //Write all data to the crypto stream and flush it. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); //Get encrypted array of bytes. encrypted = msEncrypt.ToArray(); //return textConverter.GetString(encrypted); return(TextService.BufferToHexStr(encrypted, 0, encrypted.Length)); }
} //compute hash from arguments and return hash value as string private static string GetRC2Hash(string text) { //create variables for computing hash and making it a string UnicodeEncoding UniCode = new UnicodeEncoding(); byte[] HashResult; byte[] msg = UniCode.GetBytes(text); RC2 hashString = new RC2CryptoServiceProvider(); //generate a weak KEY and Initialization Vector for the hash algorithm hashString.GenerateKey(); hashString.GenerateIV(); ICryptoTransform encryptor = hashString.CreateEncryptor(hashString.Key, hashString.IV); string Str = ""; //compute hash with RC2 module and format output as string //convert bytes in HashResult to string values HashResult = encryptor.TransformFinalBlock(msg, 0, msg.Length); foreach (byte x in HashResult) { Str += String.Format("{0:x2}", x); } //clear excess resource usage hashString.Clear(); return(Str); } //compute hash from arguments and return hash value as string
public string Encrypt_Data(string p) { lock (LockObj) { if (File.Exists("RC2KEY.txt") && File.Exists("RC2IV.txt")) { using (RC2CryptoServiceProvider RC2 = new RC2CryptoServiceProvider()) { RC2.Key = Convert.FromBase64String(File.ReadAllText("RC2KEY.txt")); RC2.IV = Convert.FromBase64String(File.ReadAllText("RC2IV.txt")); byte[] DataToEncrypt = Encoding.Unicode.GetBytes(p); ICryptoTransform encryptor = RC2.CreateEncryptor(RC2.Key, RC2.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(DataToEncrypt, 0, DataToEncrypt.Length); csEncrypt.FlushFinalBlock(); return(Convert.ToBase64String(msEncrypt.ToArray())); } } } } else { MessageBox.Show("You must create keys", "Error"); return(null); } } }
public void Encrypt(Stream streamIn, Stream streamOut, Stream streamKey) { using (RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider()) { key = rc2.Key; iv = rc2.IV; ICryptoTransform encryptor = rc2.CreateEncryptor(key, iv); CryptoStream cryptoStream = new CryptoStream(streamOut, encryptor, CryptoStreamMode.Write); streamIn.CopyTo(cryptoStream); StringBuilder builder = new StringBuilder(); builder.AppendLine(Convert.ToBase64String(iv)); builder.AppendLine(Convert.ToBase64String(key)); byte[] keyfile = System.Text.Encoding.Default.GetBytes(builder.ToString()); streamKey.Write(keyfile, 0, keyfile.Length); } }
}//End Function static private ICryptoTransform GetEncryptor() { RC2CryptoServiceProvider CryptoProvider = new RC2CryptoServiceProvider(); CryptoProvider.Mode = CipherMode.CBC; return(CryptoProvider.CreateEncryptor(byteKey, byteIV)); }//End Function
public string Encrypt(string message) { UTF8Encoding textConverter = new UTF8Encoding(); RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); //Convert the data to a byte array. byte[] toEncrypt = textConverter.GetBytes(message); //Get an encryptor. ICryptoTransform encryptor = rc2CSP.CreateEncryptor(ScrambleKey, ScrambleIV); //Encrypt the data. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); //Write all data to the crypto stream and flush it. // Encode length as first 4 bytes byte[] length = new byte[4]; length[0] = (byte)(message.Length & 0xFF); length[1] = (byte)((message.Length >> 8) & 0xFF); length[2] = (byte)((message.Length >> 16) & 0xFF); length[3] = (byte)((message.Length >> 24) & 0xFF); csEncrypt.Write(length, 0, 4); csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); //Get encrypted array of bytes. byte[] encrypted = msEncrypt.ToArray(); // Convert to Base64 string string b64 = Convert.ToBase64String(encrypted); // Protect against URLEncode/Decode problem string b64mod = b64.Replace('+', '@'); // Return a URL encoded string return(HttpUtility.UrlEncode(b64mod)); }
public string Encrypt(string value) { // Create a new instance of the RC2CryptoServiceProvider class // and automatically generate a Key and IV. RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); //MessageBox.Show("Effective key size is {0} bits." + rc2CSP.EffectiveKeySize); GenerateKays(); // Get the key and IV. rc2CSP.Key = key; rc2CSP.IV = IV; // Get an encryptor. ICryptoTransform encryptor = rc2CSP.CreateEncryptor(key, IV); // Encrypt the data as an array of encrypted bytes in memory. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); // Convert the data to a byte array. string original = value; byte[] toEncrypt = Encoding.ASCII.GetBytes(original); // Write all data to the crypto stream and flush it. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); // Get the encrypted array of bytes. byte[] encrypted = msEncrypt.ToArray(); return(Convert.ToBase64String(encrypted)); // Display the original data and the decrypted data. }
public static Boolean TestKnown() { Boolean bRes = true; Byte[] IV = new Byte[8]; Byte[] PlainText = { 0, 1, 2, 3, 4, 5, 6, 7 }; Byte[] KnownVector = { 0x7A, 0x50, 0x39, 0x82, 0xB5, 0x0E, 0xB0, 0x0D, 0x1F, 0x37, 0x9D, 0xC8, 0x36, 0x09, 0xD3, 0xFF }; PasswordDeriveBytes pdb = new PasswordDeriveBytes("simplepassword", null); Byte[] the_key = pdb.CryptDeriveKey("RC2", "MD5", 40, IV); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); ICryptoTransform sse = rc2.CreateEncryptor(the_key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs.Write(PlainText, 0, PlainText.Length); cs.FlushFinalBlock(); byte[] ciphertext = ms.ToArray(); cs.Close(); Console.WriteLine("--- Cipher Text : ----"); PrintByteArray(ciphertext); Console.WriteLine("--- Known vector : ----"); PrintByteArray(KnownVector); if (!Compare(ciphertext, KnownVector)) { Console.WriteLine("Known and calculated values differ!"); bRes = false; } return(bRes); }
public string Sifrelerc2(string strGiris) { string sonuc = ""; if (strGiris == "" || strGiris == null) { throw new ArgumentNullException("Şifrelenecek veri yok."); } else { byte[] aryKey = Byte8("12345678"); byte[] aryIV = Byte8("12345678"); RC2CryptoServiceProvider dec = new RC2CryptoServiceProvider(); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, dec.CreateEncryptor(aryKey, aryIV), CryptoStreamMode.Write); StreamWriter writer = new StreamWriter(cs); writer.Write(strGiris); writer.Flush(); cs.FlushFinalBlock(); writer.Flush(); sonuc = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); writer.Dispose(); cs.Dispose(); ms.Dispose(); } return(sonuc); }
public string RC2Encrypt(string strInput, string keyInput, string ivInput) { string output = ""; if ((keyInput != null || keyInput != null) && (ivInput != null || ivInput != "")) { if (strInput == "" || strInput == null) { throw new ArgumentNullException("No Input!"); } else { byte[] aryKey = Byte8(keyInput); byte[] aryIV = Byte8(ivInput); RC2CryptoServiceProvider dec = new RC2CryptoServiceProvider(); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, dec.CreateEncryptor(aryKey, aryIV), CryptoStreamMode.Write); StreamWriter writer = new StreamWriter(cs); writer.Write(strInput); writer.Flush(); cs.FlushFinalBlock(); writer.Flush(); output = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); writer.Dispose(); cs.Dispose(); ms.Dispose(); } } return(output); }
/// <summary> /// RC2加密 /// </summary> /// <param name="plainStr">明文字符串</param> /// <param name="key">加密密钥支持40~128长度,可以每8位递增(5到16个长度的字符串)</param> /// <param name="iv">加密向量64位以上(8个字节上去字符串)</param> /// <param name="isBase64Code">是否是Base64编码,否则是16进制编码</param> /// <param name="mode">加密模式</param> /// <param name="padding">填充模式</param> /// <returns>密文</returns> public static string RC2Encrypt(string plainStr, string key = DefaultRC2Key, string iv = DefaultRC2IV, bool isBase64Code = true, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) { byte[] bKey = Encoding.UTF8.GetBytes(key); byte[] bIV = Encoding.UTF8.GetBytes(iv); byte[] byteArray = Encoding.UTF8.GetBytes(plainStr); string encrypt = null; var rc2 = new RC2CryptoServiceProvider(); try { rc2.Padding = padding; rc2.Mode = mode; using (var mStream = new MemoryStream()) { using (var cStream = new CryptoStream(mStream, rc2.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); if (isBase64Code) { encrypt = Convert.ToBase64String(mStream.ToArray()); } else { encrypt = ConvertHelper.ToString(mStream.ToArray()); } } } } catch { } rc2.Clear(); return(encrypt); }
public static void MaHoaFile(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); ICryptoTransform MyRC2_Ecryptor = MyRC2.CreateEncryptor(); ChoseOperationMode(MyRC2, operationMode); ChosePaddingMode(MyRC2, paddingMode); CryptoStream myEncryptStream; myEncryptStream = new CryptoStream(outStream, MyRC2_Ecryptor, 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); myEncryptStream.Write(byteBuffer, 0, nCurReadLen); nTotalByteWritten += nCurReadLen; } myEncryptStream.Close(); inStream.Close(); outStream.Close(); }
public static string MyRC2Crypto(string str, string key) { string encryptKeyall = Convert.ToString(key); if (encryptKeyall.Length < 9) { while (!(encryptKeyall.Length < 9)) { encryptKeyall += encryptKeyall; } } string encryptKey = encryptKeyall.Substring(0, 8); byte[] strs = Encoding.Unicode.GetBytes(str); byte[] keys = Encoding.UTF8.GetBytes(encryptKey); RC2CryptoServiceProvider rc2C = new RC2CryptoServiceProvider { Key = keys, IV = Iv }; ICryptoTransform cryp = rc2C.CreateEncryptor(); return(Convert.ToBase64String(cryp.TransformFinalBlock(strs, 0, strs.Length))); }
public static string EncryptRc2(string srcStr, string sKey = "ABCDEF987654321") { if (string.IsNullOrEmpty(srcStr) || string.IsNullOrEmpty(sKey)) { return(null); } byte[] InByteArray = Encoding.UTF8.GetBytes(srcStr); byte[] key = Encoding.UTF8.GetBytes(sKey); byte[] IV = Encoding.UTF8.GetBytes(sKey.Substring(0, sKey.Length - 2)); using (RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider()) { ICryptoTransform Encrytor = rc2.CreateEncryptor(key, IV); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, Encrytor, CryptoStreamMode.Write)) { cs.Write(InByteArray, 0, InByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string DesStr = Convert.ToBase64String(ms.ToArray()); ms.Close(); return(DesStr); } } }
//--METHOD UNTUK MENGECNRYPT public string Encrypt(string plainttext, byte[] key, byte[] iv) { string result = string.Empty; //--CREATE OBJEK RC2CryptoServiceProvider using (RC2CryptoServiceProvider rs2 = new RC2CryptoServiceProvider()) { //--MEMANGGIL METHOD CreateEncryptor ICryptoTransform ecnryptor = rs2.CreateEncryptor(key, iv); //--CREATE OBJEK MemoryStream using (MemoryStream ms = new MemoryStream()) { //--CREATE OBJEK CryptoStream using (CryptoStream cs = new CryptoStream(ms, ecnryptor, CryptoStreamMode.Write)) { //--CONVERT STRING INPUT KE BYTE ARRAY byte[] butArrayInput = new ASCIIEncoding().GetBytes(plainttext); //--WRITE BYTE ARRAY INPUT KE CRYPTO cs.Write(butArrayInput, 0, butArrayInput.Length); //--UPDATE BYTE ARRAY DALAM MEMORY DENGAN BUT ARRAY INPUT DAN CLEAR BUT ARRAY INPUT cs.FlushFinalBlock(); //--MENGAMBIL BYET ARRAY MEMORY DAN MENGKONVERT KE STRING result = Convert.ToBase64String(ms.ToArray()); } } } return(result); }
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; } }
/// <summary> /// Encrypt outgoing message /// </summary> public bool Encrypt(NetOutgoingMessage msg) { try { // nested usings are fun! using (RC2CryptoServiceProvider rc2CryptoServiceProvider = new RC2CryptoServiceProvider { KeySize = m_bitSize, Mode = CipherMode.CBC }) { using (ICryptoTransform cryptoTransform = rc2CryptoServiceProvider.CreateEncryptor(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); }
public static void Encrypt_RC2(OpenFileDialog op, string password, CipherMode mode) { RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); rc2.Padding = PaddingMode.ISO10126; byte[] textbytes = File.ReadAllBytes(op.FileName); byte[] salt1 = new byte[16]; byte[] salt2 = new byte[8]; 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); //генерируем ключ 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.CreateEncryptor(rc2.Key, rc2.IV); byte[] s = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length); icrypt.Dispose(); File.WriteAllText(op.FileName, Convert.ToBase64String(s)); }
/// <summary> /// 加密 /// </summary> public static string Encrypt(string @string) { if (String.IsNullOrEmpty(@string)) { return(@string); } string result; try { byte[] bytes = Encoding.ASCII.GetBytes(@string); using (MemoryStream dataStream = new MemoryStream()) { RC2CryptoServiceProvider cryptoService = new RC2CryptoServiceProvider(); cryptoService.Key = Encoding.UTF8.GetBytes(Licenses.Default.Key); cryptoService.IV = Encoding.UTF8.GetBytes(Licenses.Default.IV); cryptoService.UseSalt = false; using (CryptoStream cryptoStream = new CryptoStream(dataStream, cryptoService.CreateEncryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock(); byte[] inputBytes = dataStream.ToArray(); result = Convert.ToBase64String(inputBytes); cryptoStream.Close(); } dataStream.Close(); } } catch (Exception) { result = string.Empty; } return(result); }
/// <summary> /// Encrypts bytes with a certain password /// </summary> /// <param name="password">The password to use</param> /// <param name="input_buffer">The bytes to be entered</param> /// <returns>The bytes encrypted</returns> private static byte[] Encrypt(byte[] password, byte[] input_buffer) { MemoryStream memStream = new MemoryStream(); RC2 rc2 = new RC2CryptoServiceProvider(); // init IV of algo byte[] rc2_IV = new Byte[] { 0x01, 0x2E, 0x99, 0x1A, 0x22, 0xD1, 0x51, 0x99 }; // init key of algo rc2.IV = rc2_IV; rc2.Key = PasswordGenerator.EnsureValidPassword(password, rc2); //des.GenerateIV(); CryptoStream encStream = new CryptoStream(memStream, rc2.CreateEncryptor(), CryptoStreamMode.Write | CryptoStreamMode.Read); int block_size = (int)(rc2.BlockSize / 8); // encyption here for (int i = 0; i < input_buffer.Length; i += block_size) { if (i + block_size <= input_buffer.Length) { encStream.Write(input_buffer, i, block_size); } else { encStream.Write(input_buffer, i, input_buffer.Length - i); } } encStream.FlushFinalBlock(); long ret_size = memStream.Length; encStream.Close(); byte[] ret = new byte[ret_size]; Array.Copy(memStream.GetBuffer(), 0, ret, 0, ret.Length); return(ret); }
public byte[] EncryptRC2(byte[] data, byte[] key) { using (RC2CryptoServiceProvider csp = createProviderRC2(key)) { ICryptoTransform encypter = csp.CreateEncryptor(); return(encypter.TransformFinalBlock(data, 0, data.Length)); } }
/// <summary> /// 加密 /// </summary> /// <param name="inputStream">明文输入流</param> /// <param name="key">秘钥</param> /// <param name="iv">偏移量</param> /// <param name="outStream">输出流</param> public static void Encryptor(Stream inputStream, byte[] key, byte[] iv, ref Stream outStream) { using (RC2CryptoServiceProvider rC2Crypto = CreateRC2CriptoService(key, iv)) { var encryptor = rC2Crypto.CreateEncryptor(); CryptoTransform.TransformByWrite(inputStream, encryptor, ref outStream); } }
/**===================================================================================================* * ET99加密狗密钥存储区可以存储8个32字节密钥,用于HMAC-MD5计算。实际上相当于种子码算法,通过输入(每次不超过51字节) * 进行计算,产生结果,将结果与应用软件中的数据进行加密处理,产生密文存储在多功能锁中。这样在应用软件使用时,必须通过该 * 把多功能锁中的密钥计算产生的结果与密文进行反向解密处理产生明文,供软件使用。 * * 因为RC2算法默认密钥大小128(Bit)=16字节=加密狗通过密钥存储区内的密钥加密运算后的结果长度 ***===================================================================================================*/ /// <summary> /// RC2 加密(用变长密钥对大量数据进行加密) /// </summary> /// <param name="EncryptString">待加密密文</param> /// <param name="EncryptKey">加密密钥-->即加密狗计算后的16字节数据结果</param> /// <returns>returns</returns> public static string RC2Encrypt(string EncryptString, string EncryptKey) { if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); } if (EncryptKey.Length < 5 || EncryptKey.Length > 16)//RC2算法有效密钥大小40~128(Bit) { throw (new Exception("密钥必须为5-16位")); } string m_strEncrypt = ""; byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider(); try { byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString); MemoryStream m_stream = new MemoryStream(); CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write); m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length); m_cstream.FlushFinalBlock(); m_strEncrypt = Convert.ToBase64String(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_cstream.Close(); m_cstream.Dispose(); } catch (IOException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { m_RC2Provider.Clear(); } return(m_strEncrypt); }
//************************************************ public byte[] RC2Encrypt(byte[] B, string ikey) { RC2CryptoServiceProvider rc2CryptoServiceProvider = new RC2CryptoServiceProvider(); MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider(); byte[] key = md5CryptoServiceProvider.ComputeHash(Encoding.BigEndianUnicode.GetBytes(ikey)); rc2CryptoServiceProvider.Key = key; rc2CryptoServiceProvider.Mode = CipherMode.ECB; return(rc2CryptoServiceProvider.CreateEncryptor().TransformFinalBlock(B, 0, B.Length)); }
public static byte[] Encode(String text, String key) { UTF8Encoding ascii = new UTF8Encoding(); byte[] UnicodeKey = FormatKey(key); byte[] Text = ascii.GetBytes(text); ICryptoTransform transf = cryptoProvider.CreateEncryptor(UnicodeKey, RCS_IV_BYTES); return(transf.TransformFinalBlock(Text, 0, Text.Length)); }
/// <summary> /// 加密 /// </summary> /// <param name="str">原字符串</param> /// <returns></returns> public static string Encrypt(this string str) { if (string.IsNullOrEmpty(str)) return null; var sBuffer = Encoding.UTF8.GetBytes(str); var provider = new RC2CryptoServiceProvider(); var rgbIV = Encoding.ASCII.GetBytes(IV); var rgbKey = Encoding.ASCII.GetBytes(Key); var encryptor = provider.CreateEncryptor(rgbKey, rgbIV); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(sBuffer, 0, sBuffer.Length); cs.FlushFinalBlock(); } byte[] buffer = ms.ToArray(); str = Convert.ToBase64String(buffer); } return HttpUtility.HtmlEncode(str.Trim()); }
public static Boolean TestKnown() { Boolean bRes = true; Byte[] IV = new Byte[8]; Byte[] PlainText = {0,1,2,3,4,5,6,7}; Byte[] KnownVector = {0x7A, 0x50, 0x39, 0x82, 0xB5, 0x0E, 0xB0, 0x0D, 0x1F, 0x37, 0x9D, 0xC8, 0x36, 0x09, 0xD3, 0xFF}; PasswordDeriveBytes pdb = new PasswordDeriveBytes("simplepassword", null); Byte[] the_key = pdb.CryptDeriveKey("RC2", "MD5", 40, IV); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); ICryptoTransform sse = rc2.CreateEncryptor(the_key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs.Write(PlainText,0,PlainText.Length); cs.FlushFinalBlock(); byte[] ciphertext = ms.ToArray(); cs.Close(); Console.WriteLine("--- Cipher Text : ----"); PrintByteArray(ciphertext); Console.WriteLine("--- Known vector : ----"); PrintByteArray(KnownVector); if(!Compare(ciphertext, KnownVector)) { Console.WriteLine("Known and calculated values differ!"); bRes = false; } return bRes; }
// rc2 加密后大小不会变化的 static public bool RC2_CBC_Symmetry_Encode_Byte(byte[] encryptByte, 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.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); m_cstream.Write(encryptByte, (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; } }