public static string encriptar(string texto, string key)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            MD5 md5Hash = MD5.Create();
            string chave = GetMd5Hash(md5Hash, key);
            aes.Key = System.Text.Encoding.UTF8.GetBytes(chave);
            aes.BlockSize = 128;
            aes.IV = System.Text.Encoding.UTF8.GetBytes("6abraswa+hep&#Ac");
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            byte[] encrypted;

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(texto);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }

            return Convert.ToBase64String(encrypted);
        }
Пример #2
0
Файл: Aes.cs Проект: jamezoon/XF
        /// <summary>
        /// 解密字节数组
        /// </summary>
        /// <param name="inputData">要解密的字节数据</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public static byte[] Decrypt(byte[] inputData, string password)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider
            {
                Key = GetKeyArray(password),
                Mode = cipherMode,
                Padding = paddingMode
            };

            var transform = aes.CreateDecryptor();

            byte[] data = null;

            try
            {
                data = transform.TransformFinalBlock(inputData, 0, inputData.Length);
            }
            catch
            {
                return null;
            }

            aes.Clear();

            return data;
        }
Пример #3
0
        public string decrypt(byte[] msg, byte[] key)
        {
            using (var d = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                var iv = Enumerable.Repeat((byte)0, 16).ToArray();
                d.IV      = iv;
                d.Key     = key;
                d.Mode    = CipherMode.CBC;
                d.Padding = PaddingMode.None;

                var t = d.CreateDecryptor();

                using (var ms = new System.IO.MemoryStream(msg))
                {
                    using (var cs = new CryptoStream(ms, t, CryptoStreamMode.Read))
                    {
                        using (var sr = new System.IO.StreamReader(cs))
                        {
                            var r = sr.ReadToEnd();
                            return(r);
                        }
                    }
                }
            }
        }
Пример #4
0
        public static void DisableSslCertificateChecks()
        {
            // 2019-Feb-21: The TLS connection to Blockchain.Info's WebSocket still fails with a TLS connection, but
            // that appears to be unrelated to this issue; it fails a check whether TLS checks are enabled or not
            //
            // 2018-Dec-01: We're now requiring the freshest Mono repositories to be installed with Swarmops, and this DOES
            // force a cert repository to be installed (at long effing last). Therefore, we're disabling this entire
            // function, and basically checking if anything breaks as HTTPS becomes re-enabled across the board.

            return;

            // disable "unreachable code" for the rest of this function, as the disabling is deliberate
            // disable "variable declared but never used" because of the workaround last here
            // disable "variable is assigned a value that is never used" because of the workaround last here

            #pragma warning disable 0162, 0168, 0219

            // X.509 is SO SO SO broken. The reason we do this, btw, is that mono doesn't come with root certs. At all.
            // This disables certificate checking completely and accepts ALL certificates.

            // TODO: Does this install a new handler every time it's been called? How do you verify that this short-circuit is in place?

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) => true;

            // Further, instantiate an AesCryptoServiceProvider to make sure the linker doesn't optimize it away -- apparently
            // another known bug. The warning disabled here is "b is assigned a value that is never used".

            //#pragma warning disable 0219
            System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
            //#pragma warning restore 0219

            #pragma warning restore 0162, 0168, 0219
        }
Пример #5
0
        public CryptoProvider(string securityKey, ManualResetEvent cancelEvent)
        {
            _cancelEvent = cancelEvent;

            byte[] key = GenerateKey(securityKey);
            _aes = new AesCryptoServiceProvider {KeySize = key.Length * 8, Key = key};
        }
Пример #6
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);
        }
        public static string Request(string requestParams, string devKey, string devIV, string devID) {
            // Create an unencrypted request as an array of bytes
            byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams);
            byte[] key = UTF8Encoding.UTF8.GetBytes(devKey);
            byte[] iv = UTF8Encoding.UTF8.GetBytes(devIV);

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.Key = key;
            aes.IV = iv;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;

            // Get the transformer from the AES Encryptor
            ICryptoTransform cTransform = aes.CreateEncryptor();

            // Use the transformer to encrypt our request
            byte[] result = cTransform.TransformFinalBlock(request, 0, request.Length);
            aes.Clear();

            // Encode to base64
            string encryptedRequest = Convert.ToBase64String(result, 0, result.Length);

            // Send request to API
            string requestUri = "http://api.blackoutrugby.com/?d=" + devID + "&er=" + encryptedRequest;
            string xmlResponse = getWebResponse(requestUri);
            return XmlToJson(xmlResponse);
        }
Пример #8
0
        public static byte[] DecryptCbc(byte[] key, byte[] data)
        {
            var result = new byte[data.Length];
            var c = new AesCryptoServiceProvider();
            c.Key = key;
            c.IV = new byte[16];
            c.Mode = CipherMode.CBC;
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.BlockSize = 128;
                aesAlg.KeySize = 128;
                aesAlg.Key = key;
                aesAlg.IV = new byte[16];
                aesAlg.Padding = PaddingMode.None;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msDecrypt = new MemoryStream(data))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        csDecrypt.Read(result, 0, result.Length);
                    }
                }
            }
            return result;
        }
Пример #9
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] AesEncrypt(string data, byte[] key)
        {
            if (key.Length != 16)
            {
                var ex = new Exception("the length of AES ecrypted key must be 16bit.");
                throw ex;
            }
            byte[] result;

            using (SymmetricAlgorithm algorithm = new AesCryptoServiceProvider())
            {
                algorithm.Mode = CipherMode.ECB;
                algorithm.Padding = PaddingMode.PKCS7;
                using (ICryptoTransform transform = algorithm.CreateEncryptor(key, key))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (Stream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            using (StreamWriter writer = new StreamWriter(cs))
                            {
                                writer.Write(data);
                            }
                            result = ms.ToArray();
                        }
                    }
                }
            }

            return result;
        }
Пример #10
0
        public static string EncryptString(string message, string passphrase = null)
        {
            if (string.IsNullOrEmpty(message))
            {
                throw new ArgumentException("message is empty!", message);
            }

            if (string.IsNullOrEmpty(passphrase))
            {
                passphrase = ConfigurationManager.AppSettings.Get("Common.Cryptography.DefaultPassPhrase");
            }

            // First hash the passphrase to get a 256bit key
            var sha = new SHA256CryptoServiceProvider();
            var passphraseHash = sha.ComputeHash(Encoding.UTF8.GetBytes(passphrase));

            var aes = new AesCryptoServiceProvider { KeySize = 256, Key = passphraseHash };

            var memoryStream = new MemoryStream();

            var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

            using (var writer = new StreamWriter(cryptoStream, Encoding.UTF8))
            {
                writer.Write(message);
            }

            var results = memoryStream.ToArray();

            var finalArray = new byte[aes.IV.Length + results.Length];
            Array.Copy(aes.IV, 0, finalArray, 0, aes.IV.Length);
            Array.Copy(results, 0, finalArray, aes.IV.Length, results.Length);

            return HttpServerUtility.UrlTokenEncode(finalArray);
        }
Пример #11
0
        /// <summary>
        /// Encrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="plaintext">The message (plaintext) to encrypt</param>
        /// <param name="key">An AES key</param>
        /// <param name="iv">The IV to use or null to use a 0 IV</param>
        /// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
        /// before it is encrypted.</param>
        /// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
        public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;
                aes.Mode = CipherMode.CBC;
                aes.IV = iv;

                // Encrypt the message with the key using CBC and InitializationVector=0
                byte[] cipherText;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        if (addHmac)
                        {
                            byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
                            cs.Write(hmac, 0, hmac.Length);
                        }
                        cs.Flush();
                    }
                    cipherText = ciphertext.ToArray();
                }

                return cipherText;
            }
        }
Пример #12
0
        /// <summary>
        /// Decrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="ciphertext">The message encrypted with AES in CBC mode</param>
        /// <param name="key">The key used to encrypt the message</param>
        /// <param name="iv">The initialization vector provided, if one was provided.  If you are absolutely certain
        /// the key will only be used once, an IV is not necessary and zero will be used.</param>
        /// <param name="checkAndRemoveHmac">Set if an HMACHSA256 was placed at the end of the plaintext before encrypting.
        /// The HMAC will be removed before the plaintext is returned.  If the HMAC does not match, the method will throw a
        /// System.Security.Cryptography.CryptographicException.</param>
        /// <returns>The plaintext resulting from decrypting the ciphertext with the given key.</returns>
        public static byte[] DecryptAesCbc(byte[] ciphertext, byte[] key, byte[] iv = null, bool checkAndRemoveHmac = false)
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;

                aes.IV = iv;
                aes.Mode = CipherMode.CBC;

                // Decrypt the message 
                using (System.IO.MemoryStream plaintextStream = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(plaintextStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(ciphertext, 0, ciphertext.Length);
                    }
                    byte[] plaintext = plaintextStream.ToArray();
                    if (checkAndRemoveHmac)
                    {
                        byte[] hmacProvided = plaintext.Skip(plaintext.Length - Sha256HmacLength).ToArray();
                        plaintext = plaintext.Take(plaintext.Length - Sha256HmacLength).ToArray();
                        byte[] hmacCalculated = new HMACSHA256(key).ComputeHash(plaintext);
                        if (!hmacProvided.SequenceEqual(hmacCalculated))
                            throw new CryptographicException("Message authentication code validation failed.");
                    }
                    return plaintext;
                }
            }
        }
        public InsecureEncryptionAlgorithm()
        {
            using (var tripleDES = new MyTripleDESCryptoServiceProvider()) //Noncompliant
            {
                //...
            }

            using (var des = new DESCryptoServiceProvider()) //Noncompliant
            {
                //...
            }

            using (TripleDES TripleDESalg = TripleDES.Create()) //Noncompliant
            {
            }
            using (var des = DES.Create("fgdsgsdfgsd")) //Noncompliant
            {
            }

            using (var aes = new AesCryptoServiceProvider())
            {
                //...
            }

            SymmetricAlgorithm des1 = SymmetricAlgorithm.Create("DES"); //Noncompliant
            des1 = SymmetricAlgorithm.Create("TripleDES"); //Noncompliant
            des1 = SymmetricAlgorithm.Create("3DES"); //Noncompliant
        }
        public Stream DecryptedStream(Stream streamToDecrypt)
        {
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            using (ICspProxy csp = CspFactory.GetProvider())
            {
                // Get the AES key from the stream
                // The length will be the size of the RSA key which was used to encrypt
                // the 256 bit AES key (assuming the RSA key is always larger than 256 bit).
                byte[] encryptedKey = new byte[AsymmetricKeySize / 8];
                byte[] decryptedKey;
                streamToDecrypt.Read(encryptedKey, 0, encryptedKey.Length);
                decryptedKey = csp.Decrypt(encryptedKey);

                // Attempt to read IV from Stream
                byte[] ivBytes = new byte[aesAlg.BlockSize / 8];
                streamToDecrypt.Read(ivBytes, 0, ivBytes.Length);

                // Set key and initialization vector
                aesAlg.Key = decryptedKey;
                aesAlg.IV = ivBytes;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor();

                CryptoStream cryptoStream = new CryptoStream(streamToDecrypt, decryptor, CryptoStreamMode.Read);

                return cryptoStream;
            }
        }
Пример #15
0
		public void CTS_NotAllowed ()
		{
			// this check is normally (e.g. RijndaelManaged) done later
			using (var aes = new AesCryptoServiceProvider ()) {
				aes.Mode = CipherMode.CTS;
			}
		}
Пример #16
0
        private async static Task<byte[]> AliceSendsData(string message)
        {
            Console.WriteLine("Alice send message {0}", message);
            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using(var aliceAlgo = new ECDiffieHellmanCng(aliceKey))
            {
                using(CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.GenericPublicBlob))
                {
                    byte[] symmKey = aliceAlgo.DeriveKeyMaterial(bobPubKey);
                    Console.WriteLine("Alice create this symm key with Bobs public key information : {0}", Convert.ToBase64String(symmKey));
                    using(var aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using(ICryptoTransform encryptor = aes.CreateEncryptor())
                        {
                            using(MemoryStream ms = new MemoryStream())
                            {
                                var cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write);
                                await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
                                cs.Write(rawData, 0, rawData.Length);
                                cs.Close();
                                encryptedData = ms.ToArray();
                            }
                        }
                        aes.Clear();
                    }
                }
            }
            Console.WriteLine("Alice message is encrypted : {0}", Convert.ToBase64String(encryptedData));
            return encryptedData;
        }
Пример #17
0
        public static void AESEncryption()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the AesCryptoServiceProvider 
                // class.  This generates a new key and initialization vector (IV). 
                using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                {

                    // Encrypt the string to an array of bytes.
                    byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);

                    // Decrypt the bytes to a string.
                    string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
Пример #18
0
    static System.Security.Cryptography.SymmetricAlgorithm CreateCam(string key, string IV, bool rij = true)
    {
        System.Security.Cryptography.SymmetricAlgorithm a = null;
        if (rij)
        {
            a = new System.Security.Cryptography.RijndaelManaged();
        }
        else
        {
            a = new System.Security.Cryptography.AesCryptoServiceProvider();
        }

        a.Mode      = System.Security.Cryptography.CipherMode.CBC;
        a.Padding   = System.Security.Cryptography.PaddingMode.Zeros;
        a.BlockSize = 128;
        a.KeySize   = 256;

        if (null != IV)
        {
            a.IV = System.Convert.FromBase64String(IV);
        }
        else
        {
            a.GenerateIV();
        }

        if (null != key)
        {
            a.Key = System.Convert.FromBase64String(key);
        }

        return(a);
    }
        /// <summary>
        /// Encrypts the content key to certificate.
        /// </summary>
        /// <param name="cert">The cert.</param>
        /// <param name="contentKey">The content key.</param>
        /// <returns>The encrypted content key.</returns>
        public static byte[] EncryptContentKeyToCertificate(X509Certificate2 cert, byte[] contentKey)
        {
            byte[] returnValue = null;

            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            if (contentKey == null)
            {
                throw new ArgumentNullException("contentKey");
            }

            if (contentKey.Length != EncryptionUtils.KeySizeInBytesForAes128)
            {
                throw new ArgumentOutOfRangeException("contentKey", "Common Encryption content keys are 128-bits (16 bytes) in length.");
            }

            using (AesCryptoServiceProvider key = new AesCryptoServiceProvider())
            {
                key.Key = contentKey;

                returnValue = EncryptionUtils.EncryptSymmetricKey(cert, key);
            }

            return returnValue;
        }
Пример #20
0
 public byte[] Unprotect(byte[] protectedData)
 {
     byte[] output = null;
     using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
     {
         aesAlg.Key = _key;
         aesAlg.IV = _IV;
         ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
         using (MemoryStream msDecrypt = new MemoryStream(protectedData))
         {
             using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
             {
                 byte[] buffer = new byte[8];
                 using (MemoryStream msOutput = new MemoryStream())
                 {
                     int read;
                     while ((read = csDecrypt.Read(buffer, 0, buffer.Length)) > 0)
                     {
                         msOutput.Write(buffer, 0, read);
                     }
                     output = msOutput.ToArray();
                 }
             }
         }
     }
     return output;
 }
Пример #21
0
        private static Aes CreateAes(ProgramOptions options, byte[] iv = null)
        {
            if (!options.EncryptionEnabled)
                return null;

            var salt = Convert.FromBase64String("hkuDTnecxj+oDytliJ69BQ==");
            using (var kdf = new Rfc2898DeriveBytes(options.EncryptionPassword, salt))
            {
                var aes = new AesCryptoServiceProvider();
                var keyLen = aes.KeySize/8;

                if (iv != null)
                {
                    aes.Key = kdf.GetBytes(keyLen);
                    aes.IV = iv;
                    return aes;
                }

                var ivLength = aes.BlockSize/8;
                var bytes = kdf.GetBytes(keyLen + ivLength);
                aes.Key = bytes.SubArray(0, keyLen);
                aes.IV = bytes.SubArray(keyLen, ivLength);
                return aes;
            }
        }
 public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv)
 {
     using (var provider = new AesCryptoServiceProvider {Padding = _paddingMode})
     {
         return provider.CreateEncryptor(key, iv);
     }
 }
Пример #23
0
 public static string AESDecryptor(string encryptedString, byte[] Key, byte[] IV)
 {
     byte[] data = Convert.FromBase64String(encryptedString);
     AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
     string decryptedString = ASCIIEncoding.ASCII.GetString(aes.CreateDecryptor(Key, IV).TransformFinalBlock(data, 0, data.Length));
     return decryptedString;
 }
Пример #24
0
        public static void EncryptAndUpload(string file, string awsPath, string key)
        {
            if (bool.Parse(ConfigurationManager.AppSettings["ManagedEncryption"]))
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, appKey);
                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
                    aes.IV = deriveBytes.GetBytes(aes.BlockSize / 8);
                    using (var temp = new FileStream(file + "_encrypted", FileMode.Create))
                    {
                        using (var stream = new CryptoStream(new FileStream(file, FileMode.Open), aes.CreateEncryptor(), CryptoStreamMode.Read))
                        {
                            stream.CopyTo(temp);
                        }
                    }

                    UploadFile(file + "_encrypted", awsPath);

                    File.Delete(file + "_encrypted");
                }
            }
            else
                UploadFile(file, awsPath);
        }
Пример #25
0
		internal static CipherBlock ServerCipher(BinaryReader rd, PrivateKeyByPublicKeyHash privateKeySelector)
		{
			var certificateHash = rd.ReadVarBytes();
			var iv = rd.ReadVarBytes();
			var encryptedKey = rd.ReadVarBytes();

			var privateKey = privateKeySelector(certificateHash);


			if (privateKey == null)
				throw new InvalidOperationException("You have to provide a private key");

			if (privateKey.PublicOnly)
				throw new InvalidOperationException($"The {nameof(CipherBlock)} accepts private keys only.");


			var aes = new AesCryptoServiceProvider
			{
				Padding = PaddingMode.Zeros,
				IV = iv,
				Key = new RSAOAEPKeyExchangeDeformatter(privateKey).DecryptKeyExchange(encryptedKey)
			};

			return new CipherBlock(aes, certificateHash);
		}
Пример #26
0
 public static string AESEncryptor(string plainText, byte[] Key, byte[] IV)
 {
     byte[] data = ASCIIEncoding.ASCII.GetBytes(plainText);
     AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
     string encryptedString = Convert.ToBase64String(aes.CreateEncryptor(Key, IV).TransformFinalBlock(data, 0, data.Length));
     return encryptedString;
 }
Пример #27
0
        /// <summary>
        /// Initialize the encryptor
        /// </summary>
        public AESEncryptor()
        {
            aesProvider = new AesCryptoServiceProvider();
            aesProvider.KeySize = AESKeySize;

            sha384 = SHA384.Create();
        }
Пример #28
0
    static Boolean Test()
    {
        Boolean bResult;

        Console.WriteLine("Testing AesManaged encrypt/decrypt...");
        AesManaged     aes = new AesManaged();
        EncDec      ed = new EncDec();
        EncDecMul   edm = new EncDecMul();

        bResult = ed.TestAlgorithm(aes);
        bResult = edm.TestAlgorithm(aes) && bResult;

        if (AesCSPSupported())
		{
			Console.WriteLine("Testing AesCryptoServiceProvider encrypt/decrypt...");
			AesCryptoServiceProvider     aescsp = new AesCryptoServiceProvider();
			ed = new EncDec();
			edm = new EncDecMul();

			bResult = ed.TestAlgorithm(aescsp);
			bResult = edm.TestAlgorithm(aescsp) && bResult;
		}

        return bResult;
    }
 public static byte[] EncryptString(string toEncrypt, byte[] encryptionKey)
 {
     if (string.IsNullOrEmpty(toEncrypt)) throw new ArgumentException("toEncrypt");
     if (encryptionKey == null || encryptionKey.Length == 0) throw new ArgumentException("encryptionKey");
     var toEncryptBytes = Encoding.UTF8.GetBytes(toEncrypt);
     using (var provider = new AesCryptoServiceProvider())
     {
         provider.Key = encryptionKey;
         provider.Mode = CipherMode.CBC;
         provider.Padding = PaddingMode.PKCS7;
         using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV))
         {
             using (var ms = new MemoryStream())
             {
                 ms.Write(provider.IV, 0, 16);
                 using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                 {
                     cs.Write(toEncryptBytes, 0, toEncryptBytes.Length);
                     cs.FlushFinalBlock();
                 }
                 return ms.ToArray();
             }
         }
     }
 }
Пример #30
0
        public static byte[] Protect(byte[] encryptionKey, byte[] validationKey, byte[] initializationVector, byte[] plainText)
        {
            using (var provider = new AesCryptoServiceProvider())
            {
                using (ICryptoTransform transform = provider.CreateEncryptor(encryptionKey, initializationVector))
                {
                    using (var ms = new MemoryStream())
                    {
                        ms.Write(initializationVector, 0, initializationVector.Length);
                        using (var cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            // Encrypted payload
                            cryptoStream.Write(plainText, 0, plainText.Length);
                            cryptoStream.FlushFinalBlock();

                            // Compute signature
                            using (var sha = new HMACSHA256(validationKey))
                            {
                                checked
                                {
                                    byte[] signature = sha.ComputeHash(ms.GetBuffer(), 0, (int)ms.Length);

                                    // Write the signature to the paylod
                                    ms.Write(signature, 0, signature.Length);

                                    // Final bytes
                                    return ms.ToArray();
                                }
                            }
                        }
                    }
                }
            }
        }
        public static string DecryptString(byte[] encryptedString, byte[] encryptionKey)
        {
            using (var provider = new AesCryptoServiceProvider())
            {
                provider.Key = encryptionKey;
                using (var ms = new MemoryStream(encryptedString))
                {
                    // Read the first 16 bytes which is the IV.
                    byte[] iv = new byte[16];
                    ms.Read(iv, 0, 16);
                    provider.IV = iv;

                    using (var decryptor = provider.CreateDecryptor())
                    {
                        using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                        {
                            using (var sr = new StreamReader(cs))
                            {
                                return sr.ReadToEnd();
                            }
                        }
                    }
                }
            }
        }
Пример #32
0
        public static byte[] decrypt(byte[] encrypted, byte[] Key, byte[] IV)
        {
            try
            {
                byte[] plain;
                int count;
                using (MemoryStream mStream = new MemoryStream(encrypted))
                {
                    using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
                    {
                        aesProvider.Mode = CipherMode.CBC;
                        using (CryptoStream cryptoStream = new CryptoStream(mStream,
                         aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                        {
                            plain = new byte[encrypted.Length];
                            count = cryptoStream.Read(plain, 0, plain.Length);
                        }
                    }
                }

                byte[] returnValue = new byte[count];
                Array.Copy(plain, returnValue, count);
                return returnValue;
            }
            catch (Exception e)
            {
                Logger.log(e.StackTrace);
                throw e;
            }
        }
Пример #33
0
		static OAuthServerHelper()
		{
			RSAParameters privateRsaParameters;
			RSAParameters publicRsaParameters;
			using (var rsaKeyGen = new RSACryptoServiceProvider(RsaKeySize))
			{
				privateRsaParameters = rsaKeyGen.ExportParameters(true);
				publicRsaParameters = rsaKeyGen.ExportParameters(false);
			}

			Tuple<byte[], byte[]> aesKeyAndIV;
			using (var aesKeyGen = new AesCryptoServiceProvider())
			{
				aesKeyAndIV = Tuple.Create(aesKeyGen.Key, aesKeyGen.IV);
			}

			rsa = new ThreadLocal<RSACryptoServiceProvider>(() =>
			{
				var result = new RSACryptoServiceProvider();
				result.ImportParameters(privateRsaParameters);
				return result;
			});

			aes = new ThreadLocal<AesCryptoServiceProvider>(() =>
			{
				var result = new AesCryptoServiceProvider();
				result.Key = aesKeyAndIV.Item1;
				result.IV = aesKeyAndIV.Item2;
				return result;
			});

			rsaExponent = OAuthHelper.BytesToString(publicRsaParameters.Exponent);
			rsaModulus = OAuthHelper.BytesToString(publicRsaParameters.Modulus);
		}
Пример #34
0
 public SshAes192Cbc()
     : base()
 {
     _algorithm = new AesCryptoServiceProvider();
     _algorithm.Mode = CipherMode.CBC;
     _algorithm.KeySize = 192;
 }
Пример #35
0
 public static byte[] CreateAesKey()
 {
     System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
     crypto.KeySize = 256;
     crypto.GenerateKey();
     byte[] key = crypto.Key;
     return(key);
 }
Пример #36
0
 public static byte[] generateKey()
 {
     System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
     crypto.KeySize   = 128;
     crypto.BlockSize = 128;
     crypto.GenerateKey();
     byte[] keyGenerated = crypto.Key;
     return(keyGenerated);
 }
Пример #37
0
        public static void DisableSslCertificateChecks()
        {
            // X.509 is SO SO SO broken. The reason we do this, btw, is that mono doesn't come with root certs. At all.

            // This disables certificate checking completely and accepts ALL certificates.

            // TODO: Does this install a new handler every time it's been called? How do you verify that this short-circuit is in place?

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) => true;

            // Further, instantiate an AesCryptoServiceProvider to make sure the linker doesn't optimize it away -- apparently
            // another known bug

            System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
        }
Пример #38
0
        public string generateKey()
        {
            string Key;

            try
            {
                System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
                crypto.KeySize   = 128;
                crypto.BlockSize = 128;
                crypto.GenerateKey();
                byte[] keyGenerated = crypto.Key;
                Key = Convert.ToBase64String(keyGenerated);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(Key);
        }
Пример #39
0
        byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt)
        {
            /// <summary>Encrypt by using AES-256 algorithm.</summary>
            // Create an instance of the AES class.
            var cipher = new System.Security.Cryptography.AesCryptoServiceProvider();
            // Calculate salt to make it harder to guess key by using a dictionary attack.
            var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
            var salt = hmac.ComputeHash(passwordBytes);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key = secretKey.GetBytes(32);
            var iv  = secretKey.GetBytes(16);
            // Get cryptor as System.Security.Cryptography.ICryptoTransform class.
            var cryptor = encrypt
                                ? cipher.CreateEncryptor(key, iv)
                                : cipher.CreateDecryptor(key, iv);
            // Create new Input.
            var inputBuffer = new byte[dataBytes.Length];

            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the output bytes.
            var stream = new System.IO.MemoryStream();
            // Create a CryptoStream through which we are going to be processing our data.
            var mode         = System.Security.Cryptography.CryptoStreamMode.Write;
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);

            // Start the crypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            var outputBuffer = stream.ToArray();

            // Close both streams.
            stream.Close();
            cryptoStream.Close();
            return(outputBuffer);
        }
Пример #40
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainBytes">明文字节数组</param>
        /// <returns>返回密文字节数组</returns>
        public byte[] Encrypt(byte[] plainBytes)
        {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();

            aes.Mode    = this.CipherMode;
            aes.Padding = this.PaddingMode;
            aes.Key     = GetKeyBytes();
            if (aes.Mode == CipherMode.CBC && IV == null)
            {
                IV = initIV(keyBytes.Length);
            }
            if (IV != null)
            {
                aes.IV = IV;
            }
            var encryptor = aes.CreateEncryptor();
            var bResult   = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);

            return(bResult);
        }
Пример #41
0
        private static byte[] _DecryptData(byte[] data, byte[] IV, int bitLength, byte[] passphrase)
        {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();
            var iv  = new byte[16];                                  //always 16 for AES
            var key = new byte[IV.Length == 7 ? 32 : IV.Length / 8]; //HACK: for "AES-56", convert to AES-256
            var ret = new byte[data.Length];

            //Pad the IV if necessary
            Array.Copy(IV, iv, IV.Length);

            //Derive the key
            var derived = _DeriveEncryptionKey(bitLength, passphrase);

            Array.Copy(derived, key, derived.Length);

            //Decrypt it!
            aes.CreateDecryptor(key, iv).TransformBlock(data, 0, data.Length, ret, 0);

            return(ret);
        }
Пример #42
0
        static public string AesLoginDynamicKey = @"d_&^t";            // 5

        /// <summary>
        /// 문자열을 AES로 암호화 한다
        /// </summary>
        public static string Encrypt(string dynamincKey, string text)
        {
            var comleteAesKey = dynamincKey.Substring(0, 5) + AesKey;

            System.Security.Cryptography.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize   = 128;
            aes.IV        = Encoding.UTF8.GetBytes(AesIV);
            aes.Key       = Encoding.UTF8.GetBytes(comleteAesKey);
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;

            // 문자열을 바이트형 배열로 변환
            byte[] src = Encoding.Unicode.GetBytes(text);

            // 암호화 한다
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // 바이트형 배열에서 Base64형식의 문자열로 변환
                return(Convert.ToBase64String(dest));
            }
        }
Пример #43
0
 public void Include(AesCryptoServiceProvider a)
 {
     System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
 }