示例#1
0
        // 當不傳Key進來用預設的Key值
        public string DecryptDerivedKey(string SrcString)
        {
            try
            {
                Byte[] edata1 = Convert.FromBase64String(SrcString);

                PasswordDeriveBytes pdb = new PasswordDeriveBytes(DefaultPassword, DefaultSalt);

                byte[] iv  = new byte[] { 0xA0, 0x16, 0xBC, 0xF2, 0x08, 0x3C, 0x55, 0x68 };
                byte[] key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, iv);


                TripleDES decAlg = TripleDES.Create();
                decAlg.Key = key;
                decAlg.IV  = new byte[] { 0x06, 0xA2, 0xCC, 0x53, 0x2B, 0x33, 0x28, 0x2F };



                MemoryStream decryptionStreamBacking = new MemoryStream();
                CryptoStream decrypt = new CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
                decrypt.Write(edata1, 0, edata1.Length);
                decrypt.Flush();
                decrypt.Close();
                pdb.Reset();
                string data2 = new UTF8Encoding(false).GetString(decryptionStreamBacking.ToArray());

                return(data2);
            }
            catch (Exception EX)
            {
                throw EX;
            }
        }
示例#2
0
        // 當不傳Key進來用預設的Key值
        public string EncryptDerivedKey(string SrcString)
        {
            try
            {
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(DefaultPassword, DefaultSalt);

                byte[] iv  = new byte[] { 0xA0, 0x16, 0xBC, 0xF2, 0x08, 0x3C, 0x55, 0x68 };
                byte[] key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, iv);

                // Encrypt the data.
                TripleDES encAlg = TripleDES.Create();
                encAlg.Key = key;
                encAlg.IV  = new byte[] { 0x06, 0xA2, 0xCC, 0x53, 0x2B, 0x33, 0x28, 0x2F };


                MemoryStream encryptionStream = new MemoryStream();
                CryptoStream encrypt          = new CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write);


                byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(SrcString);

                encrypt.Write(utfD1, 0, utfD1.Length);
                encrypt.FlushFinalBlock();
                encrypt.Close();
                byte[] edata1 = encryptionStream.ToArray();
                pdb.Reset();

                // 以Base-64編碼傳回
                return(Convert.ToBase64String(edata1));
            }
            catch (Exception EX)
            {
                throw EX;
            }
        }
        public void Properties()
        {
            // create object...
            PasswordDeriveBytes pd = new PasswordDeriveBytes("password", null, "MD5", 1000);

            Assert.AreEqual("MD5", pd.HashName, "HashName-MD5");
            Assert.AreEqual(1000, pd.IterationCount, "IterationCount-1000");
            // ...then change all its properties...
            pd.HashName = "SHA1";
            Assert.AreEqual("SHA1", pd.HashName, "HashName-SHA1");
            pd.Salt = salt;
            Assert.AreEqual(ssalt, BitConverter.ToString(pd.Salt), "Salt");
            pd.IterationCount = 1;
            Assert.AreEqual(1, pd.IterationCount, "IterationCount-1");
            byte[] expectedKey = { 0x0b, 0x61, 0x93, 0x96 };
            // ... before using it
            Assert.AreEqual(expectedKey, pd.GetBytes(4), "PKCS#5 test properties");
            // it should work but if we try to set any properties after GetBytes
            // they should all throw an exception
            try {
                pd.HashName = "SHA256";
                Assert.Fail("PKCS#5 can't set HashName after GetBytes - expected CryptographicException but got none");
            }
            catch (CryptographicException) {
                // do nothing, this is what we expect
            }
            catch (Exception e) {
                Assert.Fail("PKCS#5 can't set HashName after GetBytes - expected CryptographicException but got " + e.ToString());
            }
            try {
                pd.Salt = expectedKey;
                Assert.Fail("PKCS#5 can't set Salt after GetBytes - expected CryptographicException but got none");
            }
            catch (CryptographicException) {
                // do nothing, this is what we expect
            }
            catch (Exception e) {
                Assert.Fail("PKCS#5 can't set Salt after GetBytes - expected CryptographicException but got " + e.ToString());
            }
            try {
                pd.IterationCount = 10;
                Assert.Fail("PKCS#5 can't set IterationCount after GetBytes - expected CryptographicException but got none");
            }
            catch (CryptographicException) {
                // do nothing, this is what we expect
            }
            catch (Exception e) {
                Assert.Fail("PKCS#5 can't set IterationCount after GetBytes - expected CryptographicException but got " + e.ToString());
            }

            pd.Reset();
            // finally a useful reset :)
            pd.HashName       = "SHA256";
            pd.Salt           = expectedKey;
            pd.IterationCount = 10;
        }
 public static void SetSaltAfterGetBytes_Reset()
 {
     using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
     {
         deriveBytes.GetBytes(1);
         deriveBytes.Reset();
         deriveBytes.Salt = s_testSaltB;
         Assert.Equal(s_testSaltB, deriveBytes.Salt);
     }
 }
        public static void GetBytes_StableIfReset()
        {
            byte[] first;
            byte[] second;

            using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
            {
                first = deriveBytes.GetBytes(32);
                deriveBytes.Reset();
                second = deriveBytes.GetBytes(32);
            }

            Assert.Equal(first, second);
        }
示例#6
0
        [Category("NotWorking")]  // bug #79499
        public void LongMultipleGetBytes()
        {
            // based on http://bugzilla.ximian.com/show_bug.cgi?id=79499
            PasswordDeriveBytes pd = new PasswordDeriveBytes("mono", new byte[20]);
            string key             = BitConverter.ToString(pd.GetBytes(32));

            Assert.AreEqual("88-0A-AE-0A-41-61-02-78-FD-E2-70-9F-25-13-14-28-1F-C7-D9-72-9A-AE-CA-3F-BD-31-B4-F0-BD-8E-5B-98", key, "key");
            string iv = BitConverter.ToString(pd.GetBytes(16));

            Assert.AreEqual("FD-E2-70-9F-25-13-14-28-4D-3F-9B-F8-EE-AA-95-ED", iv, "iv");
            pd.Reset();
            // bytes from 32-40 are different from calling GetBytes separately
            Assert.AreEqual(key + "-F6-55-6C-3E-54-8B-F3-73-4D-3F-9B-F8-EE-AA-95-ED", BitConverter.ToString(pd.GetBytes(48)), "same");
        }
示例#7
0
    /// <summary>
    ///		Reset and ensure same
    /// </summary>
    private static bool Reset()
    {
        string password = "******";

        byte[] salt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };

        PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA512", 1025);

        byte[] res1 = pdb.GetBytes(1025);

        pdb.Reset();
        byte[] res2 = pdb.GetBytes(1025);

        return(Util.CompareBytes(res1, res2));
    }
示例#8
0
 // generate the key up to HashSize and reset between operations
 public void ShortRun(string msg, PasswordDeriveBytes pd, byte[] finalKey)
 {
     for (int i = 0; i < finalKey.Length; i++)
     {
         int    j       = 0;
         bool   compare = true;
         byte[] key     = pd.GetBytes(i + 1);
         for (; j < i; j++)
         {
             if (finalKey [j] != key[j])
             {
                 compare = false;
                 break;
             }
         }
         Assert.IsTrue(compare, msg + " #" + j);
         pd.Reset();
     }
 }
        public static void GetBytes_StableIfReset()
        {
            byte[] first;
            byte[] second;

            using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
            {
                first = deriveBytes.GetBytes(32);
                deriveBytes.Reset();
                second = deriveBytes.GetBytes(32);
            }

            Assert.Equal(first, second);
        }
示例#10
0
 public static void SetSaltAfterGetBytes_Reset()
 {
     using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
     {
         deriveBytes.GetBytes(1);
         deriveBytes.Reset();
         deriveBytes.Salt = s_testSaltB;
         Assert.Equal(s_testSaltB, deriveBytes.Salt);
     }
 }
示例#11
0
	/// <summary>
	///		Reset and ensure same
	/// </summary>
	private static bool Reset()
	{
		string password = "******";
		byte[] salt = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
		
		PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA512", 1025);
		byte[] res1 = pdb.GetBytes(1025);

		pdb.Reset();
		byte[] res2 = pdb.GetBytes(1025);

		return Util.CompareBytes(res1, res2);
	}
示例#12
0
        public string Encrypt(string plainText, string passPhrase, string saltValue)
        {
            int hashSize = 0;

            string hashAlgorithm      = "SHA512";
            int    passwordIterations = 1000;
            string initVector         = "";
            int    keySizeInBytes     = 32;

            if (hashAlgorithm == "MD5")
            {
                hashSize = 16;
            }
            else if (hashAlgorithm == "SHA1")
            {
                hashSize = 16;
            }
            else if (hashAlgorithm == "SHA256")
            {
                hashSize = 32;
            }
            else if (hashAlgorithm == "SHA384")
            {
                hashSize = 48;
            }
            else if (hashAlgorithm == "SHA512")
            {
                hashSize = 64;
            }

            if (keySizeInBytes > hashSize)
            {
                throw new Exception("Selected hash algorithm is not capable of returning the keysize");
            }

            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Convert our passPhrase into a byte array.
            byte[] passPhraseBytes = Encoding.UTF8.GetBytes(passPhrase);


            // First, we must create a password, from which the key will be derived.
            // This password will be generated from the specified passphrase and
            // salt value. The password will be created using the specified hash
            // algorithm. Password creation can be done in several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(passPhraseBytes, saltValueBytes, hashAlgorithm, passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySizeInBytes);

            byte[] initVectorBytes;
            if (initVector == "")
            {
                password.Reset();
                initVectorBytes = password.GetBytes(16);
            }
            else
            {
                initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            }

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Padding = PaddingMode.PKCS7;

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate encryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

            // Start encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] cipherTextBytes = memoryStream.ToArray();

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert encrypted data into a base64-encoded string.
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return(cipherText);
        }
示例#13
0
        public static string Decrypt(string cipherText, string passPhrase, string saltValue)
        {
            string hashAlgorithm      = "SHA512";
            int    passwordIterations = 1000;
            string initVector         = "";
            int    keySizeInBytes     = 32;

            //if (keySize >= 256 && (hashAlgorithm != "SHA256" && hashAlgorithm != "SHA384" && hashAlgorithm != "SHA512"))
            //    throw new Exception("Selected hash algorithm is not capable of returning the keysize");

            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our ciphertext into a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // Convert our passPhrase into a byte array.
            byte[] passPhraseBytes = Encoding.UTF8.GetBytes(passPhrase);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(passPhraseBytes, saltValueBytes, hashAlgorithm, passwordIterations);

            //Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes, passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySizeInBytes);

            byte[] initVectorBytes;
            if (initVector == "")
            {
                password.Reset();
                initVectorBytes = password.GetBytes(16);
            }
            else
            {
                initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            }

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Padding = PaddingMode.PKCS7;

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data into a string.
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

            // Return decrypted string.
            plainText = plainText.Replace("\0", "");
            return(plainText);
        }