/// <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!");
			}
		}
Example #2
0
    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)
    }
        /// <summary>
        /// Decrypt a Product Settings string.
        /// </summary>
        /// <param name="string">The string to decrypt.</param>
        /// <returns>The decrypted string.</returns>
        public static string Decrypt(string @string)
        {
            if (String.IsNullOrEmpty(@string))
                return @string;

            string result;
            try
            {
                byte[] bytes = Convert.FromBase64String(@string);
                using (MemoryStream dataStream = new MemoryStream(bytes))
                {
                    RC2CryptoServiceProvider cryptoService = new RC2CryptoServiceProvider
                    {
                        Key = Encoding.UTF8.GetBytes("ClearCanvas"),
                        IV = Encoding.UTF8.GetBytes("IsSoCool"),
                        UseSalt = false
                    };
                    using (CryptoStream cryptoStream = new CryptoStream(dataStream, cryptoService.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (StreamReader reader = new StreamReader(cryptoStream, Encoding.UTF8))
                        {
                            result = reader.ReadToEnd();
                            reader.Close();
                        }
                        cryptoStream.Close();
                    }
                    dataStream.Close();
                }
            }
            catch (Exception)
            {
                result = string.Empty;
            }
            return result;
        }
Example #4
0
        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());
                }
            }
        }
            static NetRC2Encryption()
            {

                RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
                List<int> temp = new List<int>();
                foreach (KeySizes keysize in rc2.LegalKeySizes)
                {
                    for (int i = keysize.MinSize; i <= keysize.MaxSize; i += keysize.SkipSize)
                    {
                        if (!temp.Contains(i))
                            temp.Add(i);
                        if (i == keysize.MaxSize)
                            break;
                    }
                }
                m_keysizes = temp;
                temp = new List<int>();
                foreach (KeySizes keysize in rc2.LegalBlockSizes)
                {
                    for (int i = keysize.MinSize; i <= keysize.MaxSize; i += keysize.SkipSize)
                    {

                        if (!temp.Contains(i))
                            temp.Add(i);
                        if (i == keysize.MaxSize)
                            break;
                    }
                }
                m_blocksizes = temp;
            }
        public static string DecryptPassword(string encryptedText)
        {
            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
            ICryptoTransform decryptor = rc2CSP.CreateDecryptor(rc2CSP.Key, rc2CSP.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 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 "";
            }
        }
Example #8
0
        public static SymmetricAlgorithm GetAlgorithmByName(String algorithmName)
        {
            SymmetricAlgorithm symmetricAlgorithm     = null;
            String             algorithmNameLoverCase = algorithmName.ToLower();

            switch (algorithmNameLoverCase)
            {
            case "aes":
                symmetricAlgorithm = new System.Security.Cryptography.AesCryptoServiceProvider();
                break;

            case "des":
                symmetricAlgorithm = new System.Security.Cryptography.DESCryptoServiceProvider();
                break;

            case "rc2":
                symmetricAlgorithm = new System.Security.Cryptography.RC2CryptoServiceProvider();
                break;

            case "rijndael":
                symmetricAlgorithm = new System.Security.Cryptography.RijndaelManaged();
                break;
            }
            return(symmetricAlgorithm);
        }
 static RC2 CreateRC2(string key)
 {
     MD5 md5 = new MD5CryptoServiceProvider();
     RC2 rc2 = new RC2CryptoServiceProvider();
     rc2.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
     rc2.IV = new byte[rc2.BlockSize / 8];
     return rc2;
 }
Example #10
0
 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 string Decrypt(string input, string key)
 {
     byte[] inputArray = System.Convert.FromBase64String(input);
     RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
     rc2.Key = UTF8Encoding.UTF8.GetBytes(key);
     rc2.Mode = CipherMode.ECB;
     rc2.Padding = PaddingMode.PKCS7;
     ICryptoTransform cTransform = rc2.CreateDecryptor();
     byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
     rc2.Clear();
     return UTF8Encoding.UTF8.GetString(resultArray);
 }
Example #12
0
        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 Cryptographer()
        {
            this.rc2         = new RC2CryptoServiceProvider();
            this.rc2.KeySize = 128;

            EncryptionKey = GetDefaultKey();
            IV            = GetDefaultVector();

            rc2.GenerateKey();
            rc2.Key = EncryptionKey;
            rc2.GenerateIV();
            rc2.IV = IV;
        }
Example #14
0
        /// <summary>
        /// 解密数据.
        /// </summary>
        /// <param name="toDecrypt">要解密的密文.</param>
        /// <returns></returns>
        private string RC2Decrypt(byte[] toDecrypt)
        {
            RC2CryptoServiceProvider myRC2 = new RC2CryptoServiceProvider();
            ICryptoTransform myCryptoTrans = myRC2.CreateDecryptor(Key, IV);
            MemoryStream ms = new MemoryStream(toDecrypt);
            CryptoStream cs = new CryptoStream(ms, myCryptoTrans, CryptoStreamMode.Read);
            byte[] tmp = new byte[toDecrypt.Length];

            cs.Read(tmp, 0, tmp.Length);
            ms.Close();
            cs.Close();
            return Encoding.UTF8.GetString(tmp);
        }
Example #15
0
 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());
 }
        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);
        }
Example #17
0
        public void Decrypt()
        {
            using (SymmetricAlgorithm rc2Csp = new RC2CryptoServiceProvider())
            {
                rc2Csp.Key = getByts(this._CryptoKey);
                rc2Csp.IV = getByts(IV);

                using (ICryptoTransform encryptor = rc2Csp.CreateDecryptor())
                {
                    byte[] source = Convert.FromBase64String(_EncryptionMessage);
                    byte[] decrypted = encryptor.TransformFinalBlock(source, 0, source.Length);

                    this._NomalMessage=Encoding.UTF8.GetString(decrypted);
                }
            }
        }
Example #18
0
 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();
 }
Example #19
0
 // 加密
 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);
     }
 }
Example #20
0
 // 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);
 }
Example #21
0
File: RC.cs Project: VqSoft/ZYFC
 /// <summary> 
 /// 进行RC2解密。 
 /// </summary> 
 /// <param name="pToDecrypt">要解密的以Base64</param> 
 /// <param name="sKey">初始化向量</param> 
 /// <param name="IV">密钥,且必须为8位。</param> 
 /// <returns>已解密的字符串。</returns> 
 public static string Decrypt(string pToDecrypt, byte[] key, byte[] IV)
 {
     byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
     using (RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider())
     {
         System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateDecryptor(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 = Encoding.UTF8.GetString(ms.ToArray());
         ms.Close();
         return str;
     }
 }
Example #22
0
 //����
 //����: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 "";
     }
 }
Example #23
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <param name="encryptedType"></param>
 /// <returns></returns>
 public override string DoDecrypt(string encryptedText, string key, Encoding encoding, DataMode encryptedType)
 {
     MemoryStream stream = new MemoryStream(200);
     stream.SetLength(0L);
     byte[] buffer = Convert.FromBase64String(encryptedText);
     RC2 rc = new RC2CryptoServiceProvider();
     rc.KeySize = 0x40;
     CryptoStream stream2 = new CryptoStream(stream, rc.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
     stream2.Write(buffer, 0, buffer.Length);
     stream2.FlushFinalBlock();
     stream.Flush();
     stream.Seek(0L, SeekOrigin.Begin);
     byte[] buffer2 = new byte[stream.Length];
     stream.Read(buffer2, 0, buffer2.Length);
     stream2.Close();
     stream.Close();
     return Encoding.Unicode.GetString(buffer2);
 }
        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);
                }
            }
        }
Example #25
0
        public void Decrypt(Stream streamIn, Stream streamOut, StreamReader streamKey)
        {
            using (RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider())
            {
                rc2.Padding = PaddingMode.None;

                rc2.IV = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));
                rc2.Key = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));

                //ICryptoTransform decryptor = aes.CreateDecryptor();
                using (ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key, rc2.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(streamIn, decryptor, CryptoStreamMode.Read))
                    {
                        cryptoStream.CopyTo(streamOut);
                    }
                }
            }
        }
Example #26
0
File: RC.cs Project: VqSoft/ZYFC
        /// <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;
            }
        }
Example #27
0
        public static string SymmetricEncrypt(this string plaintext, string key, SymmetricAlgorithm algorithm)
        {
            if (string.IsNullOrWhiteSpace(plaintext))
                throw new ArgumentNullException("plaintext", "Cannot encrypt an empty string.");
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException("key", "Cannot encrypt with an empty key.");

            byte[] keyBuffer = Convert.FromBase64String(key.Hash(HashAlgorithm.MD5));
            byte[] plainTextBuffer = Encoding.UTF8.GetBytes(plaintext);

            System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm;
            switch (algorithm)
            {
                //case SymmetricAlgorithmEnum.DES:
                //    symmetricAlgorithm = new DESCryptoServiceProvider();
                //    break;
                case SymmetricAlgorithm.RC2:
                    symmetricAlgorithm = new RC2CryptoServiceProvider();
                    break;
                case SymmetricAlgorithm.TripleDES:
                    symmetricAlgorithm = new TripleDESCryptoServiceProvider();
                    break;
                case SymmetricAlgorithm.Aes:
                default:
                    symmetricAlgorithm = new AesCryptoServiceProvider();
                    break;
            }

            symmetricAlgorithm.Key = keyBuffer;
            symmetricAlgorithm.Mode = CipherMode.ECB;
            // The legacy code did not indicate padding - not sure if this will effect the ouput much but we probably shouldn't change it
            // symmetricAlgorithm.Padding = PaddingMode.PKCS7;

            var encryptor = symmetricAlgorithm.CreateEncryptor();
            byte[] cipherBuffer = encryptor.TransformFinalBlock(plainTextBuffer, 0, plainTextBuffer.Length);
            symmetricAlgorithm.Clear();

            return Convert.ToBase64String(cipherBuffer);
        }
Example #28
0
        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);
            }
        }
Example #29
0
        public static string RC2Decrypt(byte[] bytes, 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 dec = rc2.CreateDecryptor(key, IV);
            MemoryStream stream = new MemoryStream(bytes);
            CryptoStream cs = new CryptoStream(stream, dec, CryptoStreamMode.Read);
            byte[] block = new byte[8000];
            MemoryStream ms = new MemoryStream();
            int n;
            do
            {
                n = cs.Read(block, 0, block.Length);
                ms.Write(block, 0, n);
            } while (n == block.Length);
            return Encoding.ASCII.GetString(ms.ToArray());
        }
		internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
		{
			// Pick the provider.
			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.");
				}
			}
		} //end GetCryptoServiceProvider
        public ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            ICryptoTransform iCryptoTransform;

            switch (this.algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    DES dES = new DESCryptoServiceProvider();
                    dES.Mode = CipherMode.CBC;
                    dES.Key = bytesKey;
                    dES.IV = this.initVec;
                    iCryptoTransform = dES.CreateDecryptor();
                    break;

                case EncryptionAlgorithm.TripleDes:
                    TripleDES tripleDES = new TripleDESCryptoServiceProvider();
                    tripleDES.Mode = CipherMode.CBC;
                    iCryptoTransform = tripleDES.CreateDecryptor(bytesKey, this.initVec);
                    break;

                case EncryptionAlgorithm.Rc2:
                    RC2 rC2 = new RC2CryptoServiceProvider();
                    rC2.Mode = CipherMode.CBC;
                    iCryptoTransform = rC2.CreateDecryptor(bytesKey, this.initVec);
                    break;

                case EncryptionAlgorithm.Rijndael:
                    Rijndael rijndael = new RijndaelManaged();
                    rijndael.Mode = CipherMode.CBC;
                    iCryptoTransform = rijndael.CreateDecryptor(bytesKey, this.initVec);
                    break;

                default:
                    throw new CryptographicException(String.Concat("Algorithm ID \'", this.algorithmID,
                                                                   "\' not supported."));
            }
            return iCryptoTransform;
        }
Example #32
0
        /// <summary>
        /// Do Decrypt from encryptedBase64String.
        /// </summary>
        /// <param name="encryptedBase64String">Base64 string of encrypted.</param>
        /// <returns>Plain string.</returns>
        public string Decrypt(string encryptedBase64String)
        {
            // Create the file streams to handle the input and output files.
            MemoryStream fout = new MemoryStream(200);
            fout.SetLength(0);

            // Create variables to help with read and write.
            byte[] bin = Convert.FromBase64String(encryptedBase64String);
            RC2 rc = new RC2CryptoServiceProvider();
            rc.KeySize = 64;
            CryptoStream encStream = new CryptoStream(fout, rc.CreateDecryptor(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 System.Text.Encoding.Unicode.GetString(bout);
        }
Example #33
0
        /// <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);
        }
Example #34
0
 internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
 {
     // 获取解密服务端の提供者
     switch (algorithmID)
     {
         case EncryptionAlgorithm.Des:
             {
                 DES des = new DESCryptoServiceProvider();
                 des.Mode = CipherMode.CBC;
                 des.Key = bytesKey;
                 des.IV = IV;
                 return des.CreateDecryptor();
             }
         case EncryptionAlgorithm.TripleDes:
             {
                 TripleDES tripleDes = new TripleDESCryptoServiceProvider();
                 tripleDes.Mode = CipherMode.CBC;
                 return tripleDes.CreateDecryptor(bytesKey, IV);
             }
         case EncryptionAlgorithm.Rc2:
             {
                 RC2 rc2 = new RC2CryptoServiceProvider();
                 rc2.Mode = CipherMode.CBC;
                 return rc2.CreateDecryptor(bytesKey, IV);
             }
         case EncryptionAlgorithm.Rijndael:
             {
                 Rijndael rijndael = new RijndaelManaged();
                 rijndael.Mode = CipherMode.CBC;
                 return rijndael.CreateDecryptor(bytesKey, IV);
             }
         default:
             {
                 throw new CryptographicException("不支持の" + "解密算法ID: '" + algorithmID + "' ");
             }
     }
 }
Example #35
0
        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);
        }