private CreateEncryptor ( byte rgbKey, byte rgbIV ) : ICryptoTransform | ||
rgbKey | byte | |
rgbIV | byte | |
return | ICryptoTransform |
public string mEncryptURLEncode(string text) { byte[] plainBytes = Encoding.Unicode.GetBytes(text); byte[] cipherBytes; using (ICryptoTransform sse = rc2.CreateEncryptor()) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write)) { cs.Write(plainBytes, 0, plainBytes.Length); cs.FlushFinalBlock(); cs.Close(); cs.Dispose(); } cipherBytes = ms.ToArray(); ms.Close(); ms.Dispose(); } sse.Dispose(); } string sEncrypt = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length); return(HttpUtility.UrlEncode(sEncrypt)); }
public static void Main() { //chave secreta byte[] Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; //vetor de inicialização byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; //Stream de memória IO.MemoryStream memstream = new IO.MemoryStream(15); //Stream de criptografia CP.RC2CryptoServiceProvider provider = new CP.RC2CryptoServiceProvider(); CP.ICryptoTransform transform = provider.CreateEncryptor(Key, IV); CP.CryptoStreamMode mode = CP.CryptoStreamMode.Write; CP.CryptoStream stream = new CP.CryptoStream(memstream, transform, mode); //Lê cada caracter da string foreach (char ch in "Isto é um teste") { stream.WriteByte((Convert.ToByte(ch))); } int c; //Reposiciona o ponteiro para leitura memstream.Position = c = 0; //técnica não trivial, mas válida while ((c = memstream.ReadByte()) != -1) { Console.Write((char)c); } stream.Close(); //Libera a stream (crypto) memstream.Close(); //Libera a stream (mem) }
public static string Encrypt(string input, string key) { byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); rc2.Key = UTF8Encoding.UTF8.GetBytes(key); rc2.Mode = CipherMode.ECB; rc2.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rc2.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length); rc2.Clear(); return System.Convert.ToBase64String(resultArray, 0, resultArray.Length); }
public static string EncryptText(string openText) { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); ICryptoTransform encryptor = rc2CSP.CreateEncryptor(Convert.FromBase64String(C_KEY), Convert.FromBase64String(C_IV)); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); byte[] toEncrypt = Encoding.Unicode.GetBytes(openText); csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); byte[] encrypted = msEncrypt.ToArray(); return Convert.ToBase64String(encrypted); }
public static byte[] RC2Encrypt(string text, string encryptionKey, string vector) { byte[] key = CalculateMD5Hash(encryptionKey); byte[] IV = new byte[64]; IV.Initialize(); byte[] varr = Encoding.ASCII.GetBytes(vector); Buffer.BlockCopy(varr, 0, IV, 0, varr.Length > 64 ? 64 : varr.Length); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); ICryptoTransform enc = rc2.CreateEncryptor(key, IV); MemoryStream stream = new MemoryStream(); CryptoStream cs = new CryptoStream(stream, enc, CryptoStreamMode.Write); byte[] bytes = Encoding.ASCII.GetBytes(text); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); return stream.ToArray(); }
// 加密 private void button3_Click(object sender, EventArgs e) { try { if (pictureBox1.ImageLocation == null) { MessageBox.Show("请选择一幅图片用于加密"); return; } if (textBox1.Text == "") { MessageBox.Show("请选择加密文件路径"); return; } //图片流 FileStream fsPic = new FileStream(pictureBox1.ImageLocation, FileMode.Open, FileAccess.Read); //加密文件流 FileStream fsText = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read); //初始化Key IV byte[] bykey = new byte[16]; byte[] byIv = new byte[8]; fsPic.Read(bykey, 0, 16); fsPic.Read(byIv, 0, 8); //临时加密文件 string strPath = textBox1.Text;//加密文件的路径 int intLent = strPath.LastIndexOf("\\") + 1; int intLong = strPath.Length; string strName = strPath.Substring(intLent, intLong - intLent);//要加密的文件名称 string strLinPath = "C:\\" + strName;//临时加密文件路径,所以被加密的文件不可以放在C盘的根目录下 FileStream fsOut = File.Open(strLinPath, FileMode.Create, FileAccess.Write); //开始加密 RC2CryptoServiceProvider desc = new RC2CryptoServiceProvider();//des进行加 BinaryReader br = new BinaryReader(fsText);//从要加密的文件中读出文件内容 CryptoStream cs = new CryptoStream(fsOut, desc.CreateEncryptor(bykey, byIv), CryptoStreamMode.Write);//写入临时加密文件 cs.Write(br.ReadBytes((int)fsText.Length), 0, (int)fsText.Length);//写入加密流 cs.FlushFinalBlock(); cs.Flush(); cs.Close(); fsPic.Close(); fsText.Close(); fsOut.Close(); File.Delete(textBox1.Text.TrimEnd());//册除原文件 File.Copy(strLinPath, textBox1.Text);//复制加密文件 File.Delete(strLinPath);//册除临时文件 MessageBox.Show("加密成功"); pictureBox1.ImageLocation = null; textBox1.Text = ""; } catch (Exception ee) { MessageBox.Show(ee.Message); } }
// Methods public override string DoEncrypt(string plainText, string key, Encoding encoding, DataMode encryptedType) { MemoryStream stream = new MemoryStream(200); stream.SetLength(0L); byte[] bytes = Encoding.Unicode.GetBytes(plainText); RC2 rc = new RC2CryptoServiceProvider(); CryptoStream stream2 = new CryptoStream(stream, rc.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); stream.Flush(); stream.Seek(0L, SeekOrigin.Begin); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream2.Close(); stream.Close(); return Convert.ToBase64String(buffer, 0, buffer.Length); }
//���� //����:strData:Ҫ���ܵ����� strKey:��Կ //����:�Ӻ��ܵ��ַ��� public static string Encrypt(string strData, string strKey) { try { RC2CryptoServiceProvider desc = new RC2CryptoServiceProvider();//des���м��� byte[] key = System.Text.Encoding.Unicode.GetBytes(strKey); byte[] data = System.Text.Encoding.Unicode.GetBytes(strData); MemoryStream ms = new MemoryStream();//�洢���ܺ������ CryptoStream cs = new CryptoStream(ms,desc.CreateEncryptor(key,key),CryptoStreamMode.Write); cs.Write(data, 0, data.Length);//���м��� cs.FlushFinalBlock(); return System.Text.Encoding.Unicode.GetString(ms.ToArray());//ȡ���ܺ������ } catch { return ""; } }
public static string EncryptPassword(string password) { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); ICryptoTransform encryptor = rc2CSP.CreateEncryptor(rc2CSP.Key, rc2CSP.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { byte[] toEncrypt = Encoding.Unicode.GetBytes(password); csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); byte[] encrypted = msEncrypt.ToArray(); return Convert.ToBase64String(encrypted); } } }
/// <summary> /// 进行RC2加密。 /// </summary> /// <param name="pToEncrypt">要加密的字符串。</param> /// <param name="sKey">初始化向量</param> /// <param name="IV">密钥,且必须为8位。</param> /// <returns>以Base64格式返回的加密字符串。</returns> public static string Encrypt(string pToEncrypt, byte[] key, byte[] IV) { //创建UTF-16 编码,用来在byte[]和string之间转换 System.Text.UnicodeEncoding textConverter = new UnicodeEncoding(); byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt); using (RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider()) { System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateEncryptor(key, IV); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, Encryptor, CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Convert.ToBase64String(ms.ToArray()); ms.Close(); return str; } }
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); } }
/// <summary> /// Do Encry for plainString. /// </summary> /// <param name="plainString">Plain string.</param> /// <returns>Encrypted string as base64.</returns> public string Encrypt(string plainString) { MemoryStream fout = new MemoryStream(200); fout.SetLength(0); // Create variables to help with read and write. byte[] bin = System.Text.Encoding.Unicode.GetBytes(plainString); RC2 rc = new RC2CryptoServiceProvider(); // des.KeySize=64; CryptoStream encStream = new CryptoStream(fout, rc.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); encStream.Write(bin, 0, bin.Length); encStream.FlushFinalBlock(); fout.Flush(); fout.Seek(0, SeekOrigin.Begin); // read all string byte[] bout = new byte[fout.Length]; fout.Read(bout, 0, bout.Length); encStream.Close(); fout.Close(); return Convert.ToBase64String(bout, 0, bout.Length); }
public static string Compute(string password, string salt, int iterations){ // Setup the password generator var salted = System.Text.Encoding.Default.GetBytes(salt); var pwdGen = new Rfc2898DeriveBytes(password, salted, iterations); // generate an RC2 key byte[] key = pwdGen.GetBytes(16); byte[] iv = pwdGen.GetBytes(8); // setup an RC2 object to encrypt with the derived key RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); rc2.Key = key; rc2.IV = iv; // now encrypt with it byte[] plaintext = Encoding.UTF8.GetBytes("Message"); var ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, rc2.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(plaintext, 0, plaintext.Length); cs.Close(); byte[] encrypted = ms.ToArray(); var hashed = Convert.ToBase64String(encrypted); return hashed; //var saltBytes = System.Text.Encoding.Default.GetBytes(salt); ////var iterationCount = 1000;//GetIterationCount(); //var hashValue = GenerateHashValue(password, saltBytes, iterations); ////var iterationCountBtyeArr = BitConverter.GetBytes(iterations); ////var valueToSave = new byte[SaltByteLength + DerivedKeyLength + iterationCountBtyeArr.Length]; ////Buffer.BlockCopy(saltBytes, 0, valueToSave, 0, SaltByteLength); ////Buffer.BlockCopy(hashValue, 0, valueToSave, SaltByteLength, DerivedKeyLength); ////Buffer.BlockCopy(iterationCountBtyeArr, 0, valueToSave, salt.Length + hashValue.Length, iterationCountBtyeArr.Length); //return Convert.ToBase64String(hashValue); }
/// <summary> /// 加密数据. /// </summary> /// <param name="toEncrypt">要加密的数据.</param> /// <returns>之所以不直接返回string是因为当将该string再转成byte[]后,解密会出现异常</returns> private byte[] RC2Encrypt(string toEncrypt) { RC2CryptoServiceProvider myRC2 = new RC2CryptoServiceProvider(); ICryptoTransform myCryptoTrans = myRC2.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream CStream = new CryptoStream(ms , myCryptoTrans, CryptoStreamMode.Write); StringBuilder sb = new StringBuilder(); byte[] buf = Encoding.UTF8.GetBytes(toEncrypt); CStream.Write(buf, 0, buf.Length); CStream.FlushFinalBlock(); byte[] enc = ms.ToArray(); ms.Close(); CStream.Close(); return enc; }
static void Main(string[] args) { const int n = 100 * 1000; var sw = new Stopwatch(); Random r = new Random(); var data = new byte[1024]; var key8B = new byte[8]; var key16B = new byte[16]; var key24B = new byte[24]; var key32B = new byte[32]; r.NextBytes(data); r.NextBytes(key8B); r.NextBytes(key16B); r.NextBytes(key24B); r.NextBytes(key32B); Action<string> outputToConsole = (s) => { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(s); }; // AES Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("AES"); var aes = new AesCryptoServiceProvider(); aes.Padding = PaddingMode.PKCS7; aes.Key = key16B; Action doAes = () => EncryptDecryptAndDispose(aes.CreateEncryptor(), aes.CreateDecryptor(), data); doAes.Repeat(n) .OutputPerformance(sw, outputToConsole)(); aes.Dispose(); // RSA Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("DES"); var des = new DESCryptoServiceProvider(); des.IV = key8B; des.Key = key8B; Action doDes = () => EncryptDecryptAndDispose(des.CreateEncryptor(), des.CreateDecryptor(), data); doDes.Repeat(n) .OutputPerformance(sw, outputToConsole)(); des.Dispose(); // RC2 Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("RC2"); var rc2 = new RC2CryptoServiceProvider(); rc2.IV = key8B; rc2.Key = key8B; Action doRc2 = () => EncryptDecryptAndDispose(rc2.CreateEncryptor(), rc2.CreateDecryptor(), data); doRc2.Repeat(n) .OutputPerformance(sw, outputToConsole)(); rc2.Dispose(); // Rijndael Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("Rijndael"); var rijndael = new RijndaelManaged(); rijndael.IV = key16B; rijndael.Key = key16B; Action doRijndael = () => EncryptDecryptAndDispose(rijndael.CreateEncryptor(), rijndael.CreateDecryptor(), data); doRijndael.Repeat(n) .OutputPerformance(sw, outputToConsole)(); rijndael.Dispose(); // 3DES Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("3DES"); var tripleDes = new TripleDESCryptoServiceProvider(); tripleDes.IV = key8B; tripleDes.Key = key24B; Action do3des = () => EncryptDecryptAndDispose(tripleDes.CreateEncryptor(), tripleDes.CreateDecryptor(), data); do3des.Repeat(n) .OutputPerformance(sw, outputToConsole)(); tripleDes.Dispose(); // RSA Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("RSA"); RSAParameters param = new RSAParameters(); param.Exponent = new byte[] {0, 1, 0}; var store = new X509Store(StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate cert = null; foreach (X509Certificate cer in store.Certificates) { if (cer != null) { cert = cer; break; } } param.Modulus = cert.GetPublicKey(); var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(param); Action doRsa = () => { var encryptedData = rsa.Encrypt(key32B, true); //var decryptedData = rsa.Decrypt(encryptedData, true); }; doRsa.Repeat(n) .OutputPerformance(sw, outputToConsole)(); rsa.Dispose(); Console.Read(); }
public static string Encrypt(string pvDataString) { RC2CryptoServiceProvider RC2 = new RC2CryptoServiceProvider(); byte[] fvKey = RC2.Key; byte[] IV = RC2.IV; ASCIIEncoding fvByteConverter = new ASCIIEncoding(); ICryptoTransform fvEncryptorr = RC2.CreateEncryptor(fvKey, IV); MemoryStream fvMsEncrypt = new MemoryStream(); CryptoStream fvCsEncrypt = new CryptoStream(fvMsEncrypt, fvEncryptorr, CryptoStreamMode.Write); byte[] toEncrypt = Encoding.ASCII.GetBytes(pvDataString); fvCsEncrypt.Write(toEncrypt, 0, toEncrypt.Length); fvCsEncrypt.FlushFinalBlock(); return Convert.ToBase64String(fvMsEncrypt.ToArray()); }
public ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { ICryptoTransform iCryptoTransform; switch (this.algorithmID) { case EncryptionAlgorithm.Des: DES dES = new DESCryptoServiceProvider(); dES.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = dES.Key; } else { dES.Key = bytesKey; this.encKey = dES.Key; } if (this.initVec == null) { this.initVec = dES.IV; } else { dES.IV = this.initVec; } iCryptoTransform = dES.CreateEncryptor(); break; case EncryptionAlgorithm.TripleDes: TripleDES tripleDES = new TripleDESCryptoServiceProvider(); tripleDES.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = tripleDES.Key; } else { tripleDES.Key = bytesKey; this.encKey = tripleDES.Key; } if (this.initVec == null) { this.initVec = tripleDES.IV; } else { tripleDES.IV = this.initVec; } iCryptoTransform = tripleDES.CreateEncryptor(); break; case EncryptionAlgorithm.Rc2: RC2 rC2 = new RC2CryptoServiceProvider(); rC2.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = rC2.Key; } else { rC2.Key = bytesKey; this.encKey = rC2.Key; } if (this.initVec == null) { this.initVec = rC2.IV; } else { rC2.IV = this.initVec; } iCryptoTransform = rC2.CreateEncryptor(); break; case EncryptionAlgorithm.Rijndael: Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = rijndael.Key; } else { rijndael.Key = bytesKey; this.encKey = rijndael.Key; } if (this.initVec == null) { this.initVec = rijndael.IV; } else { rijndael.IV = this.initVec; } iCryptoTransform = rijndael.CreateEncryptor(); break; default: throw new CryptographicException(String.Concat("Algorithm ID \'", this.algorithmID, "\' not supported.")); } return iCryptoTransform; }
private static void DoEncryption(byte[] key, byte[] iv) { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); // 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 = "Here is some data to encrypt."; 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(); /////////////////////////////////////////////////////// // This is where the data could be transmitted or saved. /////////////////////////////////////////////////////// }
public ICryptoTransform GetCryptTransform() { byte[] key = Encoding.ASCII.GetBytes(keyword); switch (AlgoritmID) { case EncryptionAlgorithm.DES: DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; if (bWithKey) des.Key = key; Vector = des.IV; return des.CreateEncryptor(); case EncryptionAlgorithm.Rc2: RC2 rc = new RC2CryptoServiceProvider(); rc.Mode = CipherMode.CBC; if (bWithKey) rc.Key = key; Vector = rc.IV; return rc.CreateEncryptor(); case EncryptionAlgorithm.Rijndael: Rijndael rj = new RijndaelManaged(); rj.Mode = CipherMode.CBC; if (bWithKey) rj.Key = key; Vector = rj.IV; return rj.CreateEncryptor(); case EncryptionAlgorithm.TripleDes: TripleDES tDes = new TripleDESCryptoServiceProvider(); tDes.Mode = CipherMode.CBC; if (bWithKey) tDes.Key = key; Vector = tDes.IV; return tDes.CreateEncryptor(); default: throw new CryptographicException("Algorithm " + AlgoritmID + " Not Supported!"); } }
// encryptKey 5-16位字符串 // t为8个字符 public static string RC2Encrypt(string encryptString, string encryptKey, string t) { string returnValue; try { byte[] temp = UTF8Encoding.UTF8.GetBytes(t); //byte[] temp = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xFF }; 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 { returnValue = null; } return returnValue; }
public void Encrypt() { using (SymmetricAlgorithm rc2Csp = new RC2CryptoServiceProvider()) { rc2Csp.Key = getByts(this._CryptoKey); rc2Csp.IV = getByts(IV); using (ICryptoTransform encryptor = rc2Csp.CreateEncryptor()) { byte[] source = Encoding.UTF8.GetBytes(_NomalMessage); byte[] encrypted = encryptor.TransformFinalBlock(source, 0, source.Length); _EncryptionMessage = Convert.ToBase64String(encrypted); } } }
/// <summary> /// �����ṩ��ö����Ϣ,�����Ҫʹ�õļ����㷨�Ľӿ� /// </summary> /// <param name="algorithm">�㷨ö��</param> /// <returns></returns> internal ICryptoTransform GetEncryptoServiceProvider(EncryptionAlgorithm algorithm) { switch (algorithm) { case EncryptionAlgorithm.Des: { DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; if (null != m_Key) { des.Key = m_Key; } else { m_Key = des.Key; } if (null != m_initVec) { des.IV = m_initVec; } else { m_initVec = des.IV; } return des.CreateEncryptor(); } case EncryptionAlgorithm.Rc2: { RC2 rc = new RC2CryptoServiceProvider(); rc.Mode = CipherMode.CBC; if (null != m_Key) { rc.Key = m_Key; } else { m_Key = rc.Key; } if (null != m_initVec) { rc.IV = m_initVec; } else { m_initVec = rc.IV; } return rc.CreateEncryptor(); } case EncryptionAlgorithm.Rijndael: { Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; if (null != m_Key) { rijndael.Key = m_Key; } else { m_Key = rijndael.Key; } if (null != m_initVec) { rijndael.IV = m_initVec; } else { m_initVec = rijndael.IV; } return rijndael.CreateEncryptor(); } case EncryptionAlgorithm.TripleDes: { TripleDES edes = new TripleDESCryptoServiceProvider(); edes.Mode = CipherMode.CBC; if (null != m_Key) { edes.Key = m_Key; } else { m_Key = edes.Key; } if (null != m_initVec) { edes.IV = m_initVec; } else { m_initVec = edes.IV; } return edes.CreateEncryptor(); } default: throw new CryptographicException("Algorithm ID '" + algorithm + "' not supported."); } }
/// <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; if(null == bytesKey) { encKey = des.Key; } else { des.Key = bytesKey; encKey = des.Key; } if(null == initVec) { initVec = des.IV; } else { des.IV = initVec; } return des.CreateEncryptor(); case EncryptionAlgorithm.TripleDes: TripleDES des3 = new TripleDESCryptoServiceProvider(); des3.Mode = CipherMode.CBC; if(null == bytesKey) { encKey = des3.Key; } else { des3.Key = bytesKey; encKey = des3.Key; } if(null == initVec) { initVec = des3.IV; } else { des3.IV = initVec; } return des3.CreateEncryptor(); case EncryptionAlgorithm.Rc2: RC2 rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; if(null == bytesKey) { encKey = rc2.Key; } else { rc2.Key = bytesKey; encKey = rc2.Key; } if(null == initVec) { initVec = rc2.IV; } else { rc2.IV = initVec; } return rc2.CreateEncryptor(); case EncryptionAlgorithm.Rijndael: Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; if(null == bytesKey) { encKey = rijndael.Key; } else { rijndael.Key = bytesKey; encKey = rijndael.Key; } if(null == initVec) { initVec = rijndael.IV; } else { rijndael.IV = initVec; } return rijndael.CreateEncryptor(); default: throw new CryptographicException("Algorithm ID '" + algorithmID + "' not supported!"); } }
private static string RC2Encrypt(string algorithm, string PlainText, string PassWord) { byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue); PasswordDeriveBytes passwordBytes = new PasswordDeriveBytes(PassWord, saltValueBytes, algorithm, passwordIterations); byte[] keyBytes = passwordBytes.GetBytes(keySize / 8); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; ICryptoTransform encryptor = rc2.CreateEncryptor(keyBytes, initVectorBytes); MemoryStream memStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write); byte[] plainTextBytes = Encoding.ASCII.GetBytes(PlainText); cryptStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptStream.FlushFinalBlock(); byte[] cipherTextbytes = memStream.ToArray(); memStream.Close(); cryptStream.Close(); return Convert.ToBase64String(cipherTextbytes); }
internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { // Pick the provider. switch (_algorithmID) { case EncryptionAlgorithm.Des: { DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; // See if a key was provided if (null == bytesKey) { _encKey = des.Key; } else { des.Key = bytesKey; _encKey = des.Key; } // See if the client provided an initialization vector if (null == _initVec) { // Have the algorithm create one _initVec = des.IV; } else { //No, give it to the algorithm des.IV = _initVec; } return des.CreateEncryptor(); } case EncryptionAlgorithm.TripleDes: { TripleDES des3 = new TripleDESCryptoServiceProvider(); des3.Mode = CipherMode.CBC; // See if a key was provided if (null == bytesKey) { _encKey = des3.Key; } else { des3.Key = bytesKey; _encKey = des3.Key; } // See if the client provided an IV if (null == _initVec) { //Yes, have the alg create one _initVec = des3.IV; } else { //No, give it to the alg. des3.IV = _initVec; } return des3.CreateEncryptor(); } case EncryptionAlgorithm.Rc2: { RC2 rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; // Test to see if a key was provided if (null == bytesKey) { _encKey = rc2.Key; } else { rc2.Key = bytesKey; _encKey = rc2.Key; } // See if the client provided an IV if (null == _initVec) { //Yes, have the alg create one _initVec = rc2.IV; } else { //No, give it to the alg. rc2.IV = _initVec; } return rc2.CreateEncryptor(); } case EncryptionAlgorithm.Rijndael: { Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; // Test to see if a key was provided if(null == bytesKey) { _encKey = rijndael.Key; } else { rijndael.Key = bytesKey; _encKey = rijndael.Key; } // See if the client provided an IV if(null == _initVec) { //Yes, have the alg create one _initVec = rijndael.IV; } else { //No, give it to the alg. rijndael.IV = _initVec; } return rijndael.CreateEncryptor(); } default: { throw new CryptographicException("Algorithm ID '" + _algorithmID + "' not supported."); } } }
internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { // 选择加密客户端の提供者 switch (algorithmID) { case EncryptionAlgorithm.Des: { DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; // 判断密钥是否提供 if (null == bytesKey) { Key = des.Key; } else { des.Key = bytesKey; Key = des.Key; } //判断客户端是否提供一个初始化向量 if (null == IV)//不存在 { //创建向量 IV = des.IV; } else//存在 { //赋值给算法 des.IV = IV; } return des.CreateEncryptor(); } case EncryptionAlgorithm.TripleDes: { TripleDES tripleDES = new TripleDESCryptoServiceProvider(); tripleDES.Mode = CipherMode.CBC; if (null == bytesKey) { Key = tripleDES.Key; } else { tripleDES.Key = bytesKey; Key = tripleDES.Key; } if (null == IV) { IV = tripleDES.IV; } else { tripleDES.IV = IV; } return tripleDES.CreateEncryptor(); } case EncryptionAlgorithm.Rc2: { RC2 rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; if (null == bytesKey) { Key = rc2.Key; } else { rc2.Key = bytesKey; Key = rc2.Key; } if (null == IV) { IV = rc2.IV; } else { rc2.IV = IV; } return rc2.CreateEncryptor(); } case EncryptionAlgorithm.Rijndael: { Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; if (null == bytesKey) { Key = rijndael.Key; } else { rijndael.Key = bytesKey; Key = rijndael.Key; } if (null == IV) { IV = rijndael.IV; } else { rijndael.IV = IV; } return rijndael.CreateEncryptor(); } default: { throw new CryptographicException("不支持の" + "加密算法ID: '" + algorithmID + "' "); } } }
internal ICryptoTransform getServiceProvider(cryptoAction cAction, byte[] key, byte[] IV) { ICryptoTransform transform = null; switch (algorithm) { case cryptoProvider.DES: var des = new DESCryptoServiceProvider(); switch (cAction) { case cryptoAction.Encrypt: // si estamos cifrando, creamos el objeto cifrador. transform = des.CreateEncryptor(key, IV); break; case cryptoAction.Decrypt: // si estamos descifrando, creamos el objeto descifrador. transform = des.CreateDecryptor(key, IV); break; } return transform; case cryptoProvider.TripleDES: var des3 = new TripleDESCryptoServiceProvider(); switch (cAction) { case cryptoAction.Encrypt: transform = des3.CreateEncryptor(key, IV); break; case cryptoAction.Decrypt: transform = des3.CreateDecryptor(key, IV); break; } return transform; case cryptoProvider.RC2: var rc2 = new RC2CryptoServiceProvider(); switch (cAction) { case cryptoAction.Encrypt: transform = rc2.CreateEncryptor(key, IV); break; case cryptoAction.Decrypt: transform = rc2.CreateDecryptor(key, IV); break; } return transform; case cryptoProvider.Rijndael: var rijndael = new RijndaelManaged(); switch (cAction) { case cryptoAction.Encrypt: transform = rijndael.CreateEncryptor(key, IV); break; case cryptoAction.Decrypt: transform = rijndael.CreateDecryptor(key, IV); break; } return transform; default: throw new CryptographicException("Error al inicializar al proveedor de cifrado"); } }
/// <summary> /// RC2加密 /// </summary> /// <param name="value">明文</param> /// <param name="key">密钥</param> /// Author : 俞立钢 /// Company : 绍兴标点电子技术有限公司 /// Created : 2014-12-11 13:44:46 public static string EncrypteRc2(this string value, string key) { try { RC2CryptoServiceProvider mRc2Provider = new RC2CryptoServiceProvider(); ICryptoTransform cryptoTransform = mRc2Provider.CreateEncryptor(Encoding.Default.GetBytes(key), PublicFields.MbtIv); return EncrypteMethod(value, cryptoTransform); } catch (Exception) { return "RC2加密失败!"; } }
/// <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 void Test36() { UInt16 userId = 65535; DateTime now = DateTime.Now; DateTime y2010 = new DateTime(2010, 1, 1); DateTime y2040 = new DateTime(2040, 1, 1); TimeSpan span = y2040 - y2010; Assert.IsTrue(span.TotalSeconds < UInt32.MaxValue); UInt32 secs = (uint) span.TotalSeconds; byte[] userBytes = BitConverter.GetBytes(userId); byte[] secsBytes = BitConverter.GetBytes(secs); byte[] magicBytes = new byte[8]; // userBytes.CopyTo(magicBytes, 0); // secsBytes.CopyTo(magicBytes, 2); UInt64 magic = BitConverter.ToUInt64(magicBytes, 0); ulong i = UInt64.MaxValue; ulong p; ulong reminder; uint bas = 36; List<ulong> rems = new List<ulong>(); while (true) { p = i/bas; reminder = i%bas; i = p; rems.Add(reminder); if (p == 0) break; } StringBuilder sb = new StringBuilder(); // foreach (ulong rem in rems) // { // sb.Append(ConvertTo36((byte) rem)); // } MessageBox.Show(sb.ToString() + " " + rems.Count); RC2CryptoServiceProvider aes = new RC2CryptoServiceProvider(); MemoryStream ms = new MemoryStream(); byte[] rgbKey = Encoding.Default.GetBytes("cjkywtqwertyuiop"); byte[] rgbIV = Encoding.Default.GetBytes("cdtnbnasdfghjklz"); ; CryptoStream cryptoStream = new CryptoStream(ms, aes.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); foreach (byte b in BitConverter.GetBytes(int.MaxValue)) { cryptoStream.WriteByte(b); } cryptoStream.Close(); byte[] cipherTextinBytes = ms.ToArray(); }
public static byte[] smethod_12(byte[] byte_0, string string_0, string string_1) { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string_1); byte[] bytes2 = System.Text.Encoding.ASCII.GetBytes(string_0); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); System.Security.Cryptography.RC2CryptoServiceProvider rC2CryptoServiceProvider = new System.Security.Cryptography.RC2CryptoServiceProvider(); System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rC2CryptoServiceProvider.CreateEncryptor(bytes, bytes2), System.Security.Cryptography.CryptoStreamMode.Write); cryptoStream.Write(byte_0, 0, byte_0.Length); cryptoStream.FlushFinalBlock(); return(memoryStream.ToArray()); }
public static byte[] smethod_0(byte[] byte_0, string string_0) { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string_0); byte[] rgbIV = bytes; System.Array.Resize <byte>(ref byte_0, byte_0.Length + 1); byte_0[byte_0.Length - 1] = (byte)new System.Random().Next(0, 255); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); System.Security.Cryptography.RC2CryptoServiceProvider rC2CryptoServiceProvider = new System.Security.Cryptography.RC2CryptoServiceProvider(); System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rC2CryptoServiceProvider.CreateEncryptor(bytes, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write); cryptoStream.Write(byte_0, 0, byte_0.Length); cryptoStream.FlushFinalBlock(); return(memoryStream.ToArray()); }
/// <summary> /// RC2 加密(用变长密钥对大量数据进行加密) /// </summary> /// <param name="EncryptString">待加密密文</param> /// <param name="EncryptKey">加密密钥</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) { 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 void EncryptText(string openText) { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); ICryptoTransform encryptor = rc2CSP.CreateEncryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv)); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { byte[] toEncrypt = Encoding.Unicode.GetBytes(openText); csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); byte[] encrypted = msEncrypt.ToArray(); encry = Convert.ToBase64String(encrypted); } } }