Example #1
0
        } //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
Example #2
0
        /// <summary>
        /// Generate new encryption key
        /// </summary>
        /// <param name="algId"></param>
        /// <returns></returns>
        public string GenerateKey(EncryptionAlgorithm algId)
        {
            byte[] NewKey = null;

            // Pick the provider.
            switch (algId)
            {
            case EncryptionAlgorithm.Des:
            {
                DES des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                des.GenerateKey();
                NewKey = des.Key;
                des    = null;
                break;
            }

            case EncryptionAlgorithm.TripleDes:
            {
                TripleDES des3 = new TripleDESCryptoServiceProvider();
                des3.Mode = CipherMode.CBC;
                des3.GenerateKey();
                NewKey = des3.Key;
                des3   = null;
                break;
            }

            case EncryptionAlgorithm.Rc2:
            {
                RC2 rc2 = new RC2CryptoServiceProvider();
                rc2.Mode = CipherMode.CBC;
                rc2.GenerateKey();
                NewKey = rc2.Key;
                rc2    = null;
                break;
            }

            case EncryptionAlgorithm.Rijndael:
            {
                Rijndael rijndael = new RijndaelManaged();
                rijndael.Mode      = CipherMode.CBC;
                rijndael.Padding   = PaddingMode.PKCS7;
                rijndael.KeySize   = 256;
                rijndael.BlockSize = 256;
                rijndael.GenerateKey();
                NewKey   = rijndael.Key;
                rijndael = null;
                break;
            }

            default:
            {
                throw new CryptographicException("Algorithm ID '" + algId +
                                                 "' not supported.");
            }
            }

            return(Encoding.ASCII.GetString(NewKey));
        }
Example #3
0
 /// <summary>
 /// RC2算法构造函数(KEY和IV随机生成)
 /// </summary>
 public RC2()
 {
     rc2 = new RC2CryptoServiceProvider();
     rc2.GenerateKey();
     rc2.GenerateIV();
     Key = Convert.ToBase64String(rc2.Key);
     IV  = Convert.ToBase64String(rc2.IV);
 }
Example #4
0
        public void GenerateKey(EncoderType type)
        {
            switch (type)
            {
            case EncoderType.AES:
                using (AesCryptoServiceProvider csp = new AesCryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.DES:
                using (DESCryptoServiceProvider csp = new DESCryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.RC2:
                using (RC2CryptoServiceProvider csp = new RC2CryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.TripleDES:
                using (TripleDESCryptoServiceProvider csp = new TripleDESCryptoServiceProvider())
                {
                    csp.GenerateIV();
                    IV = Convert.ToBase64String(csp.IV);
                    csp.GenerateKey();
                    Key = Convert.ToBase64String(csp.Key);
                }
                break;

            case EncoderType.RSA:
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    IV  = "";
                    Key = csp.ToXmlString(true);
                }
                break;

            default:
                break;
            }
        }
Example #5
0
            public RC2(string rc2Text)
            {
                orgText = Encoding.Default.GetBytes(rc2Text);
                RC2CryptoServiceProvider myRC2 = new RC2CryptoServiceProvider();

                myRC2.GenerateIV();
                myRC2.GenerateKey();
                Key = myRC2.Key;
                IV  = myRC2.IV;
            }
Example #6
0
        public CipherMessage EncryptMessage(string text)
        {
            // Convert string to a byte array
            CipherMessage message = new CipherMessage();

            byte[] plainBytes = Encoding.Unicode.GetBytes(text.ToCharArray());

            // A new key and iv are generated for every message
            rc2.GenerateKey();
            rc2.GenerateIV();

            // The rc2 initialization doesnt need to be encrypted, but will
            // be used in conjunction with the key to decrypt the message.
            message.rc2IV = rc2.IV;
            try
            {
                // Encrypt the RC2 key using RSA encryption
                message.rc2Key = rsa.Encrypt(rc2.Key, false);
            }
            catch (CryptographicException e)
            {
                // The High Encryption Pack is required to run this  sample
                // because we are using a 128-bit key. See the readme for
                // additional information.
                Console.WriteLine("Encryption Failed. Ensure that the" +
                                  " High Encryption Pack is installed.");
                Console.WriteLine("Error Message: " + e.Message);
                Environment.Exit(0);
            }
            // Encrypt the Text Message using RC2 (Symmetric algorithm)
            ICryptoTransform sse = rc2.CreateEncryptor();
            MemoryStream     ms  = new MemoryStream();
            CryptoStream     cs  = new CryptoStream(ms, sse, CryptoStreamMode.Write);

            try
            {
                cs.Write(plainBytes, 0, plainBytes.Length);
                cs.FlushFinalBlock();
                message.cipherBytes = ms.ToArray();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                ms.Close();
                cs.Close();
            }
            return(message);
        } // method EncryptMessage
Example #7
0
 /// <summary>
 /// RC2 数据加密
 /// </summary>
 /// <param name="Values">加密后的字符串</param>
 /// <returns>加密后的字符串</returns>
 public string RC2Encrypt(string Values)
 {
     try
     {
         RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
         rc2CSP.Mode = CipherMode.CBC;
         byte[] byt;
         //Key 和 IV 为 16或24字节
         if (null == this._Key)
         {
             rc2CSP.GenerateKey();
             _Key = Encoding.ASCII.GetString(rc2CSP.Key);
         }
         else
         {
             if (_Key.Length != 16)
             {
                 throw new Exception("加密数据出错,详细原因:Key的长度不为 16 byte.");
             }
         }
         if (null == this._IV)
         {
             rc2CSP.GenerateIV();
             _IV = Encoding.ASCII.GetString(rc2CSP.IV);
         }
         else
         {
             if (_IV.Length != 8)
             {
                 throw new Exception("加密数据出错,详细原因:IV的长度不为 8 byte.");
             }
         }
         //return _Key + ":" + Encoding.ASCII.GetBytes(_Key).Length.ToString() + "<br>"+ _IV + ":" + Encoding.ASCII.GetBytes(this._IV).Length.ToString();
         byt = Encoding.UTF8.GetBytes(Values);
         ICryptoTransform ct = rc2CSP.CreateEncryptor(Encoding.ASCII.GetBytes(this._Key), Encoding.ASCII.GetBytes(this._IV));
         rc2CSP.Clear();
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         CryptoStream           cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
         cs.Write(byt, 0, byt.Length);
         cs.FlushFinalBlock();
         cs.Close();
         return(Convert.ToBase64String(ms.ToArray()));
     }
     catch (Exception e)
     {
         throw new Exception("加密数据出错,详细原因:" + e.Message);
     }
 }
        public void _40(Int32 numberIterations)
        {
            RC2CryptoServiceProvider rm = new RC2CryptoServiceProvider();

            rm.KeySize = 128;
            rm.GenerateIV();
            rm.GenerateKey();
            ICryptoTransform enc = rm.CreateEncryptor();
            ICryptoTransform dec = rm.CreateDecryptor();

            for (int i = 0; i < numberIterations; ++i)
            {
                byte[] enrytped = enc.TransformFinalBlock(_testData, 0, 10);
                dec.TransformFinalBlock(enrytped, 0, enrytped.Length);
            }
        }
Example #9
0
        /// <summary>
        /// 获得密钥
        /// </summary>
        /// <returns>密钥</returns>
        private byte[] GetLegalKey()
        {
            string sTemp = Key;

            rc2.GenerateKey();
            byte[] bytTemp   = rc2.Key;
            int    KeyLength = bytTemp.Length;

            if (sTemp.Length > KeyLength)
            {
                sTemp = sTemp.Substring(0, KeyLength);
            }
            else if (sTemp.Length < KeyLength)
            {
                sTemp = sTemp.PadRight(KeyLength, ' ');
            }
            return(ASCIIEncoding.ASCII.GetBytes(sTemp));
        }
Example #10
0
        public static void Main()
        {
            byte[] originalBytes = ASCIIEncoding.ASCII.GetBytes("Here is some data.");

            //Create a new RC2CryptoServiceProvider.
            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();

            rc2CSP.UseSalt = true;

            rc2CSP.GenerateKey();
            rc2CSP.GenerateIV();

            //Encrypt the data.
            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, rc2CSP.CreateEncryptor(rc2CSP.Key, rc2CSP.IV), CryptoStreamMode.Write);

            //Write all data to the crypto stream and flush it.
            csEncrypt.Write(originalBytes, 0, originalBytes.Length);
            csEncrypt.FlushFinalBlock();

            //Get encrypted array of bytes.
            byte[] encryptedBytes = msEncrypt.ToArray();

            //Decrypt the previously encrypted message.
            MemoryStream msDecrypt = new MemoryStream(encryptedBytes);
            CryptoStream csDecrypt = new CryptoStream(msDecrypt, rc2CSP.CreateDecryptor(rc2CSP.Key, rc2CSP.IV), CryptoStreamMode.Read);

            byte[] unencryptedBytes = new byte[originalBytes.Length];

            //Read the data out of the crypto stream.
            csDecrypt.Read(unencryptedBytes, 0, unencryptedBytes.Length);

            //Convert the byte array back into a string.
            string plaintext = ASCIIEncoding.ASCII.GetString(unencryptedBytes);

            //Display the results.
            Console.WriteLine("Unencrypted text: {0}", plaintext);

            Console.ReadLine();
        }
        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)
                {
                    des.GenerateKey();
                    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
                    des.GenerateIV();
                    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)
                {
                    des3.GenerateKey();
                    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
                    des3.GenerateIV();
                    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)
                {
                    rc2.GenerateKey();
                    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
                    rc2.GenerateIV();
                    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;
                rijndael.Padding = PaddingMode.PKCS7;

                // Set the key and block size.
                // Although the key size defaults to 256, it's better to be explicit.
                rijndael.KeySize = 256;

                // BlockSize defaults to 128 bits, so let's set this
                // to 256 for better security
                rijndael.BlockSize = 256;

                // Test to see if a key was provided
                if (null == bytesKey)
                {
                    // GenerateKey method utilizes the RNGCryptoServiceProvider
                    // class to generate random bytes of necessary length.
                    rijndael.GenerateKey();
                    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
                    rijndael.GenerateIV();
                    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.");
            }
            }
        }
Example #12
0
        public void EncryptFile(string fileInput,
                                string fileOutput,
                                EncryptingFileInfo fileInfo,
                                string publicKey
                                )
        {
            SymmetricAlgorithm symmetricAlgorithm = null;

            switch (fileInfo.Algorithm)
            {
            case Algorithm.AES:
                symmetricAlgorithm           = new AesCryptoServiceProvider();
                symmetricAlgorithm.KeySize   = 256;
                symmetricAlgorithm.BlockSize = 128;
                break;

            case Algorithm.DES:
                symmetricAlgorithm         = new DESCryptoServiceProvider();
                symmetricAlgorithm.KeySize = 64;
                break;

            case Algorithm.TripleDES:
                symmetricAlgorithm         = new TripleDESCryptoServiceProvider();
                symmetricAlgorithm.KeySize = 192;
                break;

            case Algorithm.Rijndael:
                symmetricAlgorithm           = new RijndaelManaged();
                symmetricAlgorithm.KeySize   = 256;
                symmetricAlgorithm.BlockSize = 256;
                break;

            case Algorithm.RC2:
                symmetricAlgorithm         = new RC2CryptoServiceProvider();
                symmetricAlgorithm.KeySize = 128;
                break;
            }
            var rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(publicKey);
            symmetricAlgorithm.Padding = (PaddingMode)fileInfo.PaddingMode;
            symmetricAlgorithm.Mode    = (CipherMode)fileInfo.CipherMode;
            symmetricAlgorithm.GenerateKey();
            symmetricAlgorithm.GenerateIV();

            var encryptedKey = rsa.Encrypt(symmetricAlgorithm.Key, false);

            fileInfo.Key = encryptedKey;
            fileInfo.IV  = symmetricAlgorithm.IV;

            //var ivLength = new byte[4];
            var fileInfoLen = new byte[4];

            byte[] fileInfoBytes;
            using (var memoryStream = new MemoryStream())
            {
                new BinaryFormatter().Serialize(memoryStream, fileInfo);
                fileInfoBytes = memoryStream.ToArray();
            }

            fileInfoLen = BitConverter.GetBytes(fileInfoBytes.Length);

            try
            {
                using (var outFs = new FileStream(fileOutput, FileMode.Create))
                {
                    var encryptor = symmetricAlgorithm.CreateEncryptor(symmetricAlgorithm.Key, symmetricAlgorithm.IV);
                    outFs.Write(fileInfoLen, 0, 4);
                    outFs.Write(fileInfoBytes, 0, fileInfoBytes.Length);

                    using (var outCs = new CryptoStream(outFs, encryptor, CryptoStreamMode.Write))
                    {
                        int count  = 0;
                        int offset = 0;

                        int    blockSizeBytes = symmetricAlgorithm.BlockSize / 8;
                        byte[] data           = new byte[blockSizeBytes];
                        int    bytesRead      = 0;

                        using (var inFs = new FileStream(fileInput, FileMode.Open))
                        {
                            do
                            {
                                count   = inFs.Read(data, 0, blockSizeBytes);
                                offset += count;
                                outCs.Write(data, 0, count);
                                bytesRead += blockSizeBytes;
                            }while (count > 0);
                            inFs.Close();
                        }
                        outCs.FlushFinalBlock();
                        outCs.Close();
                    }
                    outFs.Close();
                }

                //if (fileInfo.IsCompressed)
                //{
                //    var zipDirPath = Path.ChangeExtension(fileOutput, null);
                //    var zipFilePath = Path.ChangeExtension(zipDirPath, "zip");
                //    var encryptedFilePath = Path.Combine(zipDirPath, Path.GetFileName(fileOutput));

                //    Directory.CreateDirectory(zipDirPath);
                //    File.Move(fileOutput, encryptedFilePath);
                //    ZipFile.CreateFromDirectory(zipDirPath, zipFilePath);
                //    Directory.Delete(zipDirPath, true);
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }