Inheritance: SymmetricAlgorithm
示例#1
2
    static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
 		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        cs.FlushFinalBlock();
        CipherCalculated = ms.ToArray();
        cs.Close();

		Console.WriteLine("Computed this cyphertext:");
        PrintByteArray(CipherCalculated);
        

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
示例#2
0
        public void DecryptStream(Stream sourcestream, Stream deststream, string key)
        {
            byte[] _key = new byte[32];
            byte[] _IV  = new byte[16];

            byte[] myKey = Encoding.ASCII.GetBytes(key);

            for (int i = 0; i < _key.Length; i++)
            {
                _key[i] = 0;
            }
            for (int i = 0; (i < _key.Length) && (i < myKey.Length); i++)
            {
                _key[i] = myKey[i];
            }
            for (int i = 0; (i < _key.Length) && (i < _IV.Length); i++)
            {
                _IV[i] = _key[i];
            }
            _IV.Reverse();

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
            aes.IV  = _IV;
            aes.Key = _key;

            var decStream = new CryptoStream(sourcestream, aes.CreateDecryptor(), CryptoStreamMode.Read);

            deststream.SetLength(0);
            decStream.CopyTo(deststream);
        }
示例#3
0
                /// <summary>
                /// Encrypt a message
                /// </summary>
                /// <param name="messageToEncrypt">The message to be encrypted</param>
                /// <param name="secretKey">The 32 characters long secret key to be used on the encryption</param>
                /// <param name="secretVector">The 16 characters long secret vector to be used on the encryption</param>
                /// <returns>The encrypted message</returns>
                public static String Encrypt(String messageToEncrypt, String secretKey, String secretVector)
                {
                    String messageEncrypted = null;

                    using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
                    {
                        aes.Key = System.Text.Encoding.UTF8.GetBytes(secretKey);
                        aes.IV  = System.Text.Encoding.UTF8.GetBytes(secretVector);

                        ICryptoTransform iCryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV);

                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, iCryptoTransform, CryptoStreamMode.Write))
                            {
                                using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                                {
                                    streamWriter.Write(messageToEncrypt);
                                }

                                messageEncrypted = Convert.ToBase64String(memoryStream.ToArray());
                            }
                        }
                    }

                    return(messageEncrypted);
                }
示例#4
0
        public RijndaelManaged()
        {
            LegalBlockSizesValue = new KeySizes[] { new KeySizes(minSize: 128, maxSize: 128, skipSize: 0) };

            // This class wraps Aes
            _impl = Aes.Create();
        }
示例#5
0
文件: Aes.cs 项目: hiksa/nkn-sdk-net
        private static string DecryptStringFromBytesAes(byte[] cipherText, byte[] key, byte[] iv)
        {
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }

            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }

            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Padding = PaddingMode.None;
                aes.Mode    = CipherMode.CBC;
                aes.Key     = key;
                aes.IV      = iv;

                using (var output = new MemoryStream())
                    using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                        using (var ms = new MemoryStream(cipherText))
                            using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                            {
                                cs.CopyTo(output);

                                return(output.ToArray().ToHexString());
                            }
            }
        }
示例#6
0
 internal Client(TcpClient c, string u, Aes a)
 {
     this.c = c;
     this.u = u;
     this.a = a;
     s = c.GetStream();
 }
示例#7
0
 static Aes()
 {
     Provider           = AesProvider.Create();
     Provider.Mode      = CipherMode.ECB;
     Provider.Padding   = PaddingMode.None;
     Provider.BlockSize = BLOCK_SIZE;
 }
示例#8
0
        private void GetAllLoginsHandler(Request r, Response resp, Aes aes)
        {
            if (!VerifyRequest(r, aes))
                return;

            var list = new PwObjectList<PwEntry>();

            var root = host.Database.RootGroup;

            var parms = MakeSearchParameters();

            parms.SearchString = @"^[A-Za-z0-9:/-]+\.[A-Za-z0-9:/-]+$"; // match anything looking like a domain or url

            root.SearchEntries(parms, list);
            foreach (var entry in list)
            {
                var name = entry.Strings.ReadSafe(PwDefs.TitleField);
                var login = GetUserPass(entry)[0];
                var uuid = entry.Uuid.ToHexString();
                var e = new ResponseEntry(name, login, null, uuid, null);
                resp.Entries.Add(e);
            }
            resp.Success = true;
            resp.Id = r.Id;
            SetResponseVerifier(resp, aes);
            foreach (var entry in resp.Entries)
            {
                entry.Name = CryptoTransform(entry.Name, false, true, aes, CMode.ENCRYPT);
                entry.Login = CryptoTransform(entry.Login, false, true, aes, CMode.ENCRYPT);
                entry.Uuid = CryptoTransform(entry.Uuid, false, true, aes, CMode.ENCRYPT);
            }
        }
示例#9
0
        public async Task <Stream> OpenReadAsync(CancellationToken ct)
        {
            Stream stream = null;

            System.Security.Cryptography.Aes aes = null;
            ICryptoTransform decryptor           = null;

            try
            {
                stream = await _fileInfo.OpenReadAsync(ct);

                var header = await AesHeader.ReadAsync(stream, ct);

                aes = CreateAes(header.Version);
                var key = FileSystem.ComputeKey(header.IV, header.Version);
                decryptor = CreateTransform(aes, key, header.IV, AesMode.Decrypt); // disposed by CryptoStream
                return(new CryptoStream(stream, decryptor, CryptoStreamMode.Read));
            }
            catch
            {
                decryptor?.Dispose();
                stream?.Dispose();
                throw;
            }
            finally
            {
                aes?.Dispose();
            }
        }
示例#10
0
 private AESCrypto()
 {
     var pdb = new Rfc2898DeriveBytes(aesPasswd, aesSalt);
     aes = new AesManaged();
     aes.Key = pdb.GetBytes(aes.KeySize / 8);
     aes.IV = pdb.GetBytes(aes.BlockSize / 8);
 }
示例#11
0
        internal RijndaelImplementation()
        {
            LegalBlockSizesValue = new KeySizes[] { new KeySizes(minSize: 128, maxSize: 128, skipSize: 0) };

            // This class wraps Aes
            _impl = Aes.Create();
        }
示例#12
0
        internal void ProcessEncryption(crypto.Aes cipher, CommandLine commandLine)
        {
            var key = new Rfc2898DeriveBytes(commandLine.Password, commandLine.KeySaltLength, commandLine.KeyIterations);

            cipher.GenerateIV();
            cipher.Key = key.GetBytes(cipher.KeySize / 8);

            Stream inputStream  = CreateInputStream(commandLine);
            Stream outputStream = CreateOutputStream(commandLine);

            // 2 bytes of version
            outputStream.Write(Constants.FormatVersionBytes, 0, Constants.FormatVersionBytes.Length);

            // stores 16 bytes of IV
            outputStream.Write(cipher.IV, 0, cipher.IV.Length);

            // stores 2 bytes of salt size (in network order)
            short saltLength = IPAddress.HostToNetworkOrder((short)key.Salt.Length);

            byte[] saltLengthBytes = BitConverter.GetBytes(saltLength);
            outputStream.Write(saltLengthBytes, 0, saltLengthBytes.Length);

            // stores n bytes of salt
            outputStream.Write(key.Salt, 0, key.Salt.Length);

            using (ICryptoTransform encryptor = cipher.CreateEncryptor())
            {
                using (Stream cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
                    inputStream.CopyTo(cryptoStream);
            }
        }
示例#13
0
        public override void init(int mode, byte[] key, byte[] iv)
        {
            if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE) throw new ArgumentOutOfRangeException();
            ms = new PipedMemoryStream();
            aesm = AesManaged.Create();
            aesm.BlockSize = blockSize * 8;
            aesm.Padding = PaddingMode.None;
            ICryptoTransform ict;
            if (key.Length > blockSize)
            {
                byte[] tmp = new byte[blockSize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }
            if (iv.Length > ivSize)
            {
                byte[] tmp = new byte[ivSize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (mode == ENCRYPT_MODE)
            {
                ict = aesm.CreateEncryptor(key, iv);
            }
            else
            {
                ict = aesm.CreateDecryptor(key, iv);
            }

            cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
        }
示例#14
0
        private static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(
                               msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return(encrypted);
        }
示例#15
0
        private static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherText))
                {
                    using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(
                               msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(plaintext);
        }
示例#16
0
        public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV  = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return(Convert.ToBase64String(array));
        }
示例#17
0
        public byte[] Decrypt(byte[] buffer)
        {
#if WINDOWS_STORE
            SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey aes    = provider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(this.key));
            IBuffer          result = CryptographicEngine.Decrypt(aes, CryptographicBuffer.CreateFromByteArray(buffer), CryptographicBuffer.CreateFromByteArray(this.iv));

            byte[] decrypted;
            CryptographicBuffer.CopyToByteArray(result, out decrypted);

            return(decrypted);
#else
            using (System.Security.Cryptography.Aes aes = AesManaged.Create())
            {
                aes.KeySize = 256;
                aes.Mode    = CipherMode.CBC;

                aes.IV  = iv;
                aes.Key = key;
                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                {
                    return(decryptor.TransformFinalBlock(buffer, 0, buffer.Length));
                }
            }
#endif
        }
        protected virtual ICryptoTransform CreateTransform(System.Security.Cryptography.Aes aes, byte[] key, byte[] iv, AesMode mode)
        {
            if (aes == null)
            {
                throw new ArgumentNullException(nameof(aes));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (iv == null)
            {
                throw new ArgumentNullException(nameof(iv));
            }

            switch (mode)
            {
            case AesMode.Decrypt:
                return(aes.CreateDecryptor(key, iv));

            case AesMode.Encrypt:
                return(aes.CreateEncryptor(key, iv));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#19
0
                /// <summary>
                /// Decrypt a message
                /// </summary>
                /// <param name="messageToDecrypt">The message to be decrypted</param>
                /// <param name="secretKey">The 32 characters long secret key to be used on the encryption</param>
                /// <param name="secretVector">The 16 characters long secret vector to be used on the encryption</param>
                /// <returns>The decrypted message</returns>
                public static String Decrypt(String messageToDecrypt, String secretKey, String secretVector)
                {
                    String messageDecrypted = null;

                    using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
                    {
                        aes.Key = System.Text.Encoding.UTF8.GetBytes(secretKey);
                        aes.IV  = System.Text.Encoding.UTF8.GetBytes(secretVector);

                        ICryptoTransform iCryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV);

                        using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(messageToDecrypt)))
                        {
                            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, iCryptoTransform, CryptoStreamMode.Read))
                            {
                                using (StreamReader streamReader = new StreamReader(cryptoStream))
                                {
                                    messageDecrypted = streamReader.ReadToEnd();
                                }
                            }
                        }
                    }

                    return(messageDecrypted);
                }
示例#20
0
        private void AssociateHandler(Request r, Response resp, Aes aes)
        {
            if (!TestRequestVerifier(r, aes, r.Key))
                return;

            // key is good, prompt user to save
            using (var f = new ConfirmAssociationForm())
            {
                var win = host.MainWindow;
                win.Invoke((MethodInvoker)delegate
                {
                    ShowNotification("New key association requested", (s, e) => f.Activate());
                    f.Icon = win.Icon;
                    f.Key = r.Key;
                    f.Load += delegate { f.Activate(); };
                    f.ShowDialog(win);
                    if (f.KeyId != null)
                    {
                        var entry = GetConfigEntry(true);
                        entry.Strings.Set(ASSOCIATE_KEY_PREFIX + f.KeyId, new ProtectedString(true, r.Key));
                        entry.Touch(true);
                        resp.Id = f.KeyId;
                        resp.Success = true;
                        SetResponseVerifier(resp, aes);
                        UpdateUI(null);
                    }
                });
            }
        }
示例#21
0
        internal int ProcessDecryption(crypto.Aes cipher, CommandLine commandLine)
        {
            Stream inputStream  = CreateInputStream(commandLine);
            Stream outputStream = CreateOutputStream(commandLine);

            if (commandLine.SkipBytes > 0)
            {
                if (commandLine.SkipBytes >= inputStream.Length)
                {
                    return(0);
                }

                if (inputStream.CanSeek)
                {
                    inputStream.Position = commandLine.SkipBytes;
                }
                else
                {
                    for (int i = 0; i < commandLine.SkipBytes; i++)
                    {
                        inputStream.ReadByte();
                    }
                }
            }

            var versionBytes = new byte[2];

            inputStream.Read(versionBytes, 0, versionBytes.Length);
            ushort version = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(versionBytes, 0));

            if (version != Constants.FormatVersion)
            {
                Console.WriteLine($"Unsupported version, expected {Constants.FormatVersion}, found {version}.");
                return(1);
            }

            // reads 16 bytes of IV
            var iv = new byte[cipher.BlockSize / 8]; // cipher.BlockSize / 8 = 16 since block size is always 128 for AES algorithm

            inputStream.Read(iv, 0, iv.Length);

            // reads 2 bytes of salt size (in host order)
            byte[] saltLengthBytes = new byte[sizeof(ushort)];
            inputStream.Read(saltLengthBytes, 0, saltLengthBytes.Length);
            int saltLength = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(saltLengthBytes, 0));

            // reads n bytes of salt
            byte[] salt = new byte[saltLength];
            inputStream.Read(salt, 0, salt.Length);

            var key = new Rfc2898DeriveBytes(commandLine.Password, salt, commandLine.KeyIterations);

            cipher.IV  = iv;
            cipher.Key = key.GetBytes(cipher.KeySize / 8);

            using (Stream cryptoStream = new CryptoStream(inputStream, cipher.CreateDecryptor(), CryptoStreamMode.Read))
                cryptoStream.CopyTo(outputStream);

            return(0);
        }
示例#22
0
        /// <summary>
        /// AES加密(BouncyCastle模式)
        /// </summary>
        /// <param name="aes"></param>
        /// <param name="str">待加密的字符串</param>
        /// <param name="encoding">待加密的字符串编码格式</param>
        /// <param name="algorithm">加密模式、填充算法</param>
        /// <param name="key">密钥</param>
        /// <param name="iv">向量</param>
        /// <returns>base64编码格式加密字符串</returns>
        public static string EncryptBC(this System.Security.Cryptography.Aes aes,
                                       string str, Encoding encoding, string algorithm, byte[] key = null, byte[] iv = null)
        {
            var data   = encoding.GetBytes(str);
            var result = aes.EncryptBC(data, algorithm, key, iv);

            return(Convert.ToBase64String(result));
        }
示例#23
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="aes"></param>
        /// <param name="str">待加密的字符串</param>
        /// <param name="encoding">待加密的字符串编码格式</param>
        /// <param name="key">加密密钥,为空则使用实体属性Key</param>
        /// <param name="mode">加密模式,为空则使用实体属性Mode</param>
        /// <param name="padding">填充算法,为空则使用实体属性Padding</param>
        /// <returns>base64编码格式加密字符串</returns>
        public static string Encrypt(this System.Security.Cryptography.Aes aes,
                                     string str, Encoding encoding, byte[] key = null, CipherMode?mode = null, PaddingMode?padding = null)
        {
            var data    = encoding.GetBytes(str);
            var encData = aes.Encrypt(data, key, mode, padding);

            return(Convert.ToBase64String(encData));
        }
示例#24
0
 public AesCrypt()
 {
     aes = Aes.Create();
     aes.Mode = CipherMode.CBC;
     aes.GenerateIV();
     aes.GenerateKey();
     aes.Padding = PaddingMode.PKCS7;
 }
示例#25
0
        /// <summary>
        /// AES加密(BouncyCastle模式)
        /// </summary>
        /// <param name="aes"></param>
        /// <param name="str">待加密的字符串</param>
        /// <param name="encoding">待加密的字符串编码格式</param>
        /// <param name="mode">加密模式</param>
        /// <param name="padding">填充算法</param>
        /// <param name="key">密钥</param>
        /// <param name="iv">向量</param>
        /// <returns>base64编码格式加密字符串</returns>
        public static string EncryptBC(this System.Security.Cryptography.Aes aes,
                                       string str, Encoding encoding, CipherModeBC mode, CipherPaddingBC padding, byte[] key = null, byte[] iv = null)
        {
            var data   = encoding.GetBytes(str);
            var result = aes.EncryptBC(data, mode, padding, key, iv);

            return(Convert.ToBase64String(result));
        }
示例#26
0
 public AES(byte[] key)
 {
     rsa = new AesManaged();
     rsa.GenerateKey();
     rsa.GenerateIV();
     _decoder = rsa.CreateDecryptor();
     _encoder = rsa.CreateEncryptor();
 }
示例#27
0
        private IEnumerable<PwEntry> FindMatchingEntries(Request r, Aes aes)
        {
            string submithost = null;
            string realm = null;
            var list = new PwObjectList<PwEntry>();
            string formhost, searchHost;
            formhost = searchHost = GetHost(CryptoTransform(r.Url, true, false, aes, CMode.DECRYPT));
            if (r.SubmitUrl != null) {
                submithost = GetHost(CryptoTransform(r.SubmitUrl, true, false, aes, CMode.DECRYPT));
            }
            if (r.Realm != null)
                realm = CryptoTransform(r.Realm, true, false, aes, CMode.DECRYPT);

            var origSearchHost = searchHost;
            var parms = MakeSearchParameters();

            var root = host.Database.RootGroup;

            while (list.UCount == 0 && (origSearchHost == searchHost || searchHost.IndexOf(".") != -1))
            {
                parms.SearchString = String.Format("^{0}$|/{0}/?", searchHost);
                root.SearchEntries(parms, list);
                searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1);
                if (searchHost == origSearchHost)
                    break;
            }
            Func<PwEntry, bool> filter = delegate(PwEntry e)
            {
                var title = e.Strings.ReadSafe(PwDefs.TitleField);
                var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField);
                var c = GetEntryConfig(e);
                if (c != null)
                {
                    if (c.Allow.Contains(formhost) && (submithost == null || c.Allow.Contains(submithost)))
                        return true;
                    if (c.Deny.Contains(formhost) || (submithost != null && c.Deny.Contains(submithost)))
                        return false;
                    if (realm != null && c.Realm != realm)
                        return false;
                }

                if (title.StartsWith("http://") || title.StartsWith("https://"))
                {
                    var u = new Uri(title);
                    if (formhost.Contains(u.Host))
                        return true;
                }
                if (entryUrl != null && entryUrl.StartsWith("http://") || entryUrl.StartsWith("https://"))
                {
                    var u = new Uri(entryUrl);
                    if (formhost.Contains(u.Host))
                        return true;
                }
                return formhost.Contains(title) || (entryUrl != null && formhost.Contains(entryUrl));
            };

            return from e in list where filter(e) select e;
        }
示例#28
0
 public AesExtensionsTest()
 {
     aes           = System.Security.Cryptography.Aes.Create();
     aes.Mode      = CipherMode.ECB;
     aes.Padding   = PaddingMode.PKCS7;
     aes.BlockSize = 128;
     aes.GenerateKey(8);
     aes.GenerateIV(8);
 }
示例#29
0
 public CrypterAES()
 {
     this.AES         = System.Security.Cryptography.Aes.Create();
     this.AES.Mode    = CrypterAES.mode;
     this.AES.Padding = CrypterAES.padding;
     this.AES.KeySize = CrypterAES.keySize;
     this.AES.GenerateIV();
     this.AES.GenerateKey();
 }
示例#30
0
 public KeePassConnection(string host, int port, string id, byte[] key)
 {
     this.Host = host;
     this.Port = port;
     this.Hash = null;
     this.Id = id;
     this.Key = key;
     this.aes = key != null ? new AesManaged {Key = key} : new AesManaged();
 }
示例#31
0
        private static AesFw CreateAes()
        {
            var aes = AesFw.Create();

            aes.BlockSize = 128;
            aes.KeySize   = 256;
            aes.Padding   = PaddingMode.Zeros;
            return(aes);
        }
示例#32
0
        static MapleAESOFB()
        {
            AES = Aes.Create();
            AES.KeySize = 256;
            AES.BlockSize = 128;
            AES.Mode = CipherMode.CBC;

            Zeroes = new byte[((BlockLength >> 4) + 1) << 4];
        }
示例#33
0
        /**********************************************************************************************************
        *	UserData LoadUserData(string MasterPassword)
        *       Purpose:	Loads data, if it exists, from the disk. The data is encrypted using AES using the
        *					master password's hash as the secret key.
        **********************************************************************************************************/
        private UserData LoadUserData(string MasterPassword)
        {
            // Need 128 bits password for the encryption key.
            ApplicationEntry self     = new ApplicationEntry("MasterPass", 128 / sizeof(char) / 8, 0, true, true, true, false);
            HashedPassword   fileName = self.GeneratePassword(MasterPassword);
            HashedPassword   aesKey   = self.GeneratePassword(MasterPassword);
            HashedPassword   aesIV    = self.GeneratePassword(MasterPassword);

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();

            // Even if aes is broken the master password is unrecoverable.
            aes.Key = Encoding.Unicode.GetBytes(aesKey.Password);
            aes.IV  = Encoding.Unicode.GetBytes(aesIV.Password);

            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            ICryptoTransform decryptor = aes.CreateDecryptor();

            UserData loadedData = null;

            // If there is no data don't load it.
            if (File.Exists(fileName.Password + ".pass") == false)
            {
                return(loadedData);
            }

            // Open the file
            using (FileStream outputStream = new FileStream(fileName.Password + ".pass", FileMode.Open))
            {
                // Use a safe to file encryption method
                using (CryptoStream csDecrypt = new CryptoStream(outputStream, decryptor, CryptoStreamMode.Read))
                {
                    // Convert the object to a byte array
                    using (MemoryStream objectStream = new MemoryStream())
                    {
                        byte[] buffer    = new byte[1024];
                        int    bytesRead = csDecrypt.Read(buffer, 0, buffer.Length);

                        while (bytesRead > 0)
                        {
                            objectStream.Write(buffer, 0, bytesRead);
                            bytesRead = csDecrypt.Read(buffer, 0, buffer.Length);
                        }

                        csDecrypt.Flush();

                        objectStream.Position = 0;

                        IFormatter formatter = new BinaryFormatter();
                        loadedData = formatter.Deserialize(objectStream) as UserData;
                    }
                }
            }

            return(loadedData);
        }
示例#34
0
        /// <summary>
        /// Creates AES instance
        /// </summary>
        /// <param name="key">Key to be set as AES key</param>
        /// <param name="iVec">IVec to be set as AES iVec</param>
        public AesEncryptor(byte[] key, byte[] iVec)
        {
            this.key = key;
            this.iVec = iVec;

            aes = Aes.Create();
            aes.IV = iVec;
            aes.Key = key;
            aes.Padding = PaddingMode.Zeros;
        }
示例#35
0
        public SimpleAes(byte[] key)
        {
            aes = Aes.Create();
            aes.GenerateIV();

            aes.Key = key;

            encryptor = aes.CreateEncryptor(key, aes.IV);
            decryptor = aes.CreateDecryptor(key, aes.IV);
        }
示例#36
0
    static AESUtils()
    {
        AesEcb         = Aes.Create();
        AesEcb.Mode    = CipherMode.ECB;
        AesEcb.Padding = PaddingMode.None;

        AesCbc         = Aes.Create();
        AesCbc.Mode    = CipherMode.CBC;
        AesCbc.Padding = PaddingMode.None;
    }
示例#37
0
        /// <summary>
        /// AES加解密
        /// </summary>
        /// <param name="aes"></param>
        /// <param name="forEncryption">是否加密(false为解密)</param>
        /// <param name="data">待加解密的数据</param>
        /// <param name="key">加解密密钥,为空则使用实体属性Key</param>
        /// <param name="mode">加解密模式,为空则使用实体属性Mode</param>
        /// <param name="padding">填充算法,为空则使用实体属性Padding</param>
        /// <returns>加解密后数据</returns>
        public static byte[] Crypto(this System.Security.Cryptography.Aes aes,
                                    bool forEncryption, byte[] data, byte[] key = null, CipherMode?mode = null, PaddingMode?padding = null)
        {
            aes.Key     = key ?? aes.Key;
            aes.Mode    = mode ?? aes.Mode;
            aes.Padding = padding ?? aes.Padding;
            var cryptor = forEncryption ? aes.CreateEncryptor() : aes.CreateDecryptor();

            return(cryptor.TransformFinalBlock(data, 0, data.Length));
        }
示例#38
0
        static DBCrypto()
        {
            aesAlg = Aes.Create();
            aesAlg.Key = AES_CBC_KEY;
            aesAlg.IV = AES_CBC_IV;
            aesAlg.Padding = PaddingMode.PKCS7;

            decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        }
示例#39
0
 static byte[] AESEncrypt(byte[] key, byte[] iv, Span <byte> dataToEncrypt)
 {
     using var result = new MemoryStream();
     using var aes    = Aes.Create();
     aes.Mode         = CipherMode.CBC;
     aes.Padding      = PaddingMode.None;
     using var cs     = new CryptoStream(result, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
     cs.Write(dataToEncrypt);
     cs.FlushFinalBlock();
     return(result.ToArray());
 }
示例#40
0
        private bool VerifyRequest(Request r, Aes aes)
        {
            var entry = GetConfigEntry(false);
            if (entry == null)
                return false;
            var s = entry.Strings.Get(ASSOCIATE_KEY_PREFIX + r.Id);
            if (s == null)
                return false;

            return TestRequestVerifier(r, aes, s.ReadString());
        }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="key"></param>
        /// <param name="counterBufferSegment"></param>
        /// <param name="aesFactory"></param>
        /// <exception cref="ArgumentException">
        /// <paramref name="counterBufferSegment"/> needs to have the same length as <see cref="AesConstants.STR_AES_BLOCK_SIZE"/>.
        /// </exception>
        public AesCtrCryptoTransform(byte[] key, ArraySegment<byte> counterBufferSegment, Func<Aes> aesFactory = null)
        {
            if (counterBufferSegment.Count != AesConstants.AES_BLOCK_SIZE)
                throw new ArgumentException($"{nameof(counterBufferSegment)}.Count must be {AesConstants.STR_AES_BLOCK_SIZE}.", nameof(counterBufferSegment));

            _aes = aesFactory?.Invoke() ?? CipherFactory.Aes();
            _aes.Mode = CipherMode.ECB;
            _aes.Padding = PaddingMode.None;

            Buffer.BlockCopy(counterBufferSegment.Array, counterBufferSegment.Offset, _counterBuffer.Value, 0, AesConstants.AES_BLOCK_SIZE);
            _cryptoTransform = _aes.CreateEncryptor(rgbKey: key, rgbIV: null);
        }
示例#42
0
        public void Decrypt(String inputFile, String outputFile, Aes aes)
        {
            if (!IsEncrypted (inputFile)) {
                return;
            }

            this.Logger.LogDebug (String.Format (CultureInfo.CurrentCulture, "Decrypting {0}...", inputFile));

            byte[] data = File.ReadAllBytes (inputFile);
            byte[] output = Decrypt (data, aes);
            File.WriteAllBytes (outputFile, output);
        }
		/// <summary>ctor</summary>
		public AesCtrCryptoTransform(byte[] key, ArraySegment<byte> counterBufferSegment, Func<Aes> aesFactory = null)
		{
			if (counterBufferSegment.Count != AesConstants.AES_BLOCK_SIZE)
				throw new ArgumentException("counterBufferSegment.Count must be " + AesConstants.STR_AES_BLOCK_SIZE + ".");

			this.aes = aesFactory == null ? AesFactories.Aes() : aesFactory();
			this.aes.Mode = CipherMode.ECB;
			this.aes.Padding = PaddingMode.None;

			Utils.BlockCopy(counterBufferSegment.Array, counterBufferSegment.Offset, counterBuffer, 0, AesConstants.AES_BLOCK_SIZE);
			this.cryptoTransform = aes.CreateEncryptor(rgbKey: key, rgbIV: null);
		}// ctor
 internal static byte[] AES256Decrypt(byte[] block, byte[] key)
 {
     using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
     {
         aes.Key     = key;
         aes.Mode    = System.Security.Cryptography.CipherMode.ECB;
         aes.Padding = System.Security.Cryptography.PaddingMode.None;
         using (System.Security.Cryptography.ICryptoTransform decryptor = aes.CreateDecryptor())
         {
             return(decryptor.TransformFinalBlock(block, 0, block.Length));
         }
     }
 }
示例#45
0
        /// <summary>
        /// Creates AES instance
        /// </summary>
        public AesEncryptor()
        {
            aes = Aes.Create();
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
                rng.GetBytes(iVec);
            }

            aes.IV = iVec;
            aes.Key = key;
            aes.Padding = PaddingMode.Zeros;
        }
示例#46
0
 public override void init(int mode, byte[] key, byte[] iv)
 {
     for (int i = 0; i < counter.Length; i++)
         counter[i] = 0;
     for (int i = 0; i < counterBytes.Length; i++)
         counterBytes[i] = 0;
     aesm = AesManaged.Create();
     aesm.BlockSize = blockSize*8;
     //aesm.KeySize = blockSize*8;
     aesm.Key = key;
     aesm.IV = iv;
     ms = new MemoryStream(blockSize);
 }
示例#47
0
        private string CryptoTransform(string input, bool base64in, bool base64out, Aes cipher, CMode mode)
        {
            byte[] bytes;
            if (base64in)
                bytes = decode64(input);
            else
                bytes = Encoding.UTF8.GetBytes(input);


            using (var c = mode == CMode.ENCRYPT ? cipher.CreateEncryptor() : cipher.CreateDecryptor()) {
            var buf = c.TransformFinalBlock(bytes, 0, bytes.Length);
            return base64out ? encode64(buf) : Encoding.UTF8.GetString(buf);
            }
        }
示例#48
0
        public static byte[] EncryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(plainText, null) || plainText.Length <= 0)
            {
                throw (new ArgumentNullException("plainText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            byte[] encrypted = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // 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(plainText);
                        }


                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream
            return(encrypted);
        }
        /// <summary>
        /// Decrypts data.
        /// </summary>
        /// <param name="aes">Aes object.</param>
        /// <param name="encrypted">Encrypted data to be decrypted.</param>
        /// <param name="key">Encryption key.</param>
        /// <param name="iv">Initial vector.</param>
        /// <returns>Decrypted data.</returns>
        public static byte[] Decrypt(Aes aes, byte[] encrypted, byte[] key, byte[] iv)
        {
            byte[] buffer = new byte[encrypted.Length];

            var decryptor = aes.CreateDecryptor(key, iv);

            using (MemoryStream ms = new MemoryStream(encrypted))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    int length = cs.Read(buffer, 0, encrypted.Length);
                    return buffer.Take(length).ToArray();
                }
            }
        }
示例#50
0
 /// <summary>
 /// Instantiate a transformation
 /// </summary>
 /// <param name="key">The key</param>
 /// <param name="iv">Initial Vector</param>
 /// <param name="cipherMode">Mode of operation, typically CBC</param>
 /// <param name="paddingMode">Padding mode, typically PCS7</param>
 public AesCrypto(AesKey key, AesIV iv, CipherMode cipherMode, PaddingMode paddingMode)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     if (iv == null)
     {
         throw new ArgumentNullException("iv");
     }
     _aes = new AesManaged();
     _aes.Key = key.GetBytes();
     _aes.Mode = cipherMode;
     _aes.IV = iv.GetBytes();
     _aes.Padding = paddingMode;
 }
        public VelostiScsi()
        {
            this.Aes = AesManaged.Create();
            this.Aes.KeySize = 256;
            this.IsBusy = false;

            this.Worker = new BackgroundWorker();
            this.Worker.WorkerReportsProgress = true;
            this.Worker.WorkerSupportsCancellation = true;
            this.Worker.DoWork += new DoWorkEventHandler(TaskWorker_DoWork);
            this.Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(TaskWorker_RunWorkerCompleted);

            this.timer = new Thread(timer_Elapsed);
            this.timer.IsBackground = true;
            this.timer.Start();
        }
        private bool disposedValue = false; // To detect redundant calls

        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _cryptor.Dispose();
                    _cryptor = null;
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
示例#53
0
        /// <summary>
        /// Encrypt the giving <see cref="Byte"> <see cref="Array"/>.
        /// </summary>
        /// <param name="plainText">The <see cref="Byte"> <see cref="Array"/> that contains data to encrypt.</param>
        /// <param name="Key">The <see cref="Byte"> <see cref="Array"/> that contains the key.</param>
        /// <param name="IV">The <see cref="Byte"> <see cref="Array"/> that contains the initialize vector.</param>
        /// <returns>The encrypted data.</returns>
        public static byte[] Encrypt(byte[] plainText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(plainText, null) || plainText.Length <= 0)
            {
                throw (new ArgumentNullException("plainText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("IV"));
            }

            byte[] encrypted = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = AesManaged.Create())
            {
                aesAlg.Key     = Key;
                aesAlg.IV      = IV;
                aesAlg.Padding = PaddingMode.Zeros;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(plainText, 0, plainText.Length);
                        csEncrypt.Flush();
                        csEncrypt.Close();
                    }

                    encrypted = msEncrypt.ToArray();
                }
            }

            // Return the encrypted bytes from the memory stream
            return(encrypted);
        }
示例#54
0
        /// <summary>
        /// Decrypt the giving <see cref="Byte"> <see cref="Array"/>.
        /// </summary>
        /// <param name="cipherText">The <see cref="Byte"> <see cref="Array"/> that contains data to decrypt.</param>
        /// <param name="Key">The <see cref="Byte"> <see cref="Array"/> that contains the key.</param>
        /// <param name="IV">The <see cref="Byte"> <see cref="Array"/> that contains the initialize vector.</param>
        /// <returns>The decrypted data.</returns>
        public static byte[] Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(cipherText, null) || cipherText.Length <= 0)
            {
                throw (new ArgumentNullException("cipherText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("IV"));
            }

            // Declare the string used to hold the decrypted text
            byte[] clearBytes = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = AesManaged.Create())
            {
                aesAlg.Key     = Key;
                aesAlg.IV      = IV;
                aesAlg.Padding = PaddingMode.Zeros;

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

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
                    {
                        csDecrypt.Write(cipherText, 0, cipherText.Length);
                        csDecrypt.Flush();
                        csDecrypt.Close();
                    }

                    clearBytes = msDecrypt.ToArray();
                }
            }

            return(clearBytes);
        }
示例#55
0
        public static string DecryptStringFromBytes_AES(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(cipherText, null) || cipherText.Length <= 0)
            {
                throw (new ArgumentNullException("cipherText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            // Declare the string used to hold the decrypted text
            string plaintext = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

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

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream and place them in a string
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(plaintext);
        }
        /// <summary>
        /// Encrypt a byte array by using the AES algorightm.
        /// <para>The input is: [Magic Number (4 bytes)] [AES IV (16 bytes)] [AES(data) (xx bytes)] [HMAC(IV || AES(data)) (32 bytes)]</para>
        /// <para>The output is: [data]</para>
        /// </summary>
        public static byte[] Decrypt(byte[] content, Aes aes)
        {
            byte[] headerBytes = new byte[4];
            byte[] ivBytes = new byte[16];
            byte[] dataBytes = new byte[content.Length - 4 - 16 - 32];
            byte[] cypherBytes = new byte[ivBytes.Length + dataBytes.Length];
            byte[] hmacBytes = new byte[32];

            Array.Copy (content, 0, headerBytes, 0, headerBytes.Length);
            Array.Copy (content, 4, ivBytes, 0, ivBytes.Length);
            Array.Copy (content, 4 + 16, dataBytes, 0, dataBytes.Length);
            Array.Copy (content, 4, cypherBytes, 0, cypherBytes.Length);
            Array.Copy (content, content.Length - 32, hmacBytes, 0, hmacBytes.Length);

            // Compute the HMAC of the cypher
            using (HMACSHA256 hmac = new HMACSHA256 (DeriveKey (aes.Key))) {
                byte[] newHmacBytes = hmac.ComputeHash (cypherBytes);

                // Check for HMAC equality
                for (int i = 0; i < newHmacBytes.Length; i++) {
                    if (newHmacBytes [i] != hmacBytes [i]) {
                        throw new CryptographicException ("Content has been tampered. HMAC don't match.");
                    }
                }
            }

            using (MemoryStream outputStream = new MemoryStream()) {
                // Report the IV
                aes.IV = ivBytes;

                // Write the AES decrypted content
                using (ICryptoTransform transform = aes.CreateDecryptor ()) {
                    using (CryptoStream cryptoStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write)) {
                        cryptoStream.Write (dataBytes, 0, dataBytes.Length);
                    }
                }

                // Collect cypher result
                outputStream.Flush ();
                outputStream.Close ();
                byte[] outputBytes = outputStream.ToArray ();

                return outputBytes;
            }
        }
示例#57
0
        public ScryptAesCtr(byte[] key, long nonce)
        {
            if (key == null) throw new ArgumentNullException("key");

            aes = Aes.Create();
            if (aes == null)
            {
                throw new InvalidOperationException("Can't find an implementation of AES");
            }

            aes.KeySize = 256;
            aes.Key = key;
            aes.IV = Enumerable.Repeat((byte)0, 16).ToArray();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.None;

            this.nonce = nonce;
        }
        public void Start(int port, CryptoAlgoId_Values cryptoAlgoId, byte[] content, EventQueue eventQueue)
        {
            this.cryptoAlgoId = cryptoAlgoId;
            this.content = content;
            this.eventQueue = eventQueue;
            this.aes = PccrrUtitlity.CreateAes(cryptoAlgoId);
            this.iv = new byte[16];
            for (int i = 0; i < iv.Length; i++)
            {
                this.iv[i] = (byte)i;
            }

            pccrrServer = new PccrrServer(port);

            pccrrServer.MessageArrived += new MessageArrivedEventArgs(pccrrServer_MessageArrived);

            pccrrServer.StartListening();
        }
示例#59
0
        private bool TestRequestVerifier(Request r, Aes aes, string key)
        {
            var success = false;
            var crypted = decode64(r.Verifier);

            aes.Key = decode64(key);
            aes.IV = decode64(r.Nonce);

            using (var dec = aes.CreateDecryptor())
            {
                try {
                    var buf = dec.TransformFinalBlock(crypted, 0, crypted.Length);
                    var value = Encoding.UTF8.GetString(buf);
                    success = value == r.Nonce;
                } catch (CryptographicException) { } // implicit failure
            }
            return success;
        }
    static Boolean Test(Aes aes, CipherMode md)
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 1,2,2,2,2,2,2,2,2};
        Byte[]  IV = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        aes.Mode = md;

        Console.WriteLine("AES default key size = " + aes.KeySize);
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        Console.WriteLine("SSE mode = " + aes.Mode);
        MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

        ICryptoTransform ssd = aes.CreateDecryptor(Key, IV);
        Console.WriteLine("SSD mode = " + aes.Mode);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[PlainText.Length];
        cs.Read(NewPlainText,0,PlainText.Length);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }