示例#1
0
        /// <summary>
        /// Encrypts data
        /// </summary>
        /// <param name="publicKey">The public key to use to encrypt the data</param>
        /// <param name="data">The data to encrypt</param>
        /// <returns>The ecrypted data</returns>
        /// <exception cref="ArgumentNullException"><paramref name="publicKey"/> is null</exception>
        /// <exception cref="ArgumentNullException"><paramref name="data"/> is null</exception>
        public static byte[] Encrypt(string publicKey, byte[] data)
        {
            if (publicKey == null)
            {
                throw new ArgumentNullException(nameof(publicKey));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            byte[] result = null;

            // If the RSA key size allows us to encrypt the data without AES then... Let us do that
            if (Convert.FromBase64String(publicKey).Length - 10 >= data.Length)
            {
                var d = Rsa.Encrypt(publicKey, data);

                result = new byte[d.Length + 1];
                Array.Copy(d, 0, result, 0, d.Length);

                // The zero in the end of the encrypted data indicates us that
                // there is no AES in place
                result[result.Length - 1] = 0;
            }
            else
            {
                using (var randomPassword = (CryptoUtils.BrewPassword(80) + publicKey + DateTime.Now.ToString()).GetHash(Core.HashAlgorithms.Sha512).ToSecureString())
                {
                    var d         = Aes.Encrypt(randomPassword, data);
                    var k         = Rsa.Encrypt(publicKey, randomPassword.GetBytes());
                    var keyLength = k.Length.ToBytes();

                    result = new byte[k.Length + d.Length + 4 + 1];

                    Array.Copy(k, result, k.Length);
                    Array.Copy(d, 0, result, k.Length, d.Length);
                    Array.Copy(keyLength, 0, result, k.Length + d.Length, 4);

                    result[result.Length - 1] = 1;
                }
            }

            return(result);
        }