public static void TestShims()
        {
            using (var alg = new AesCryptoServiceProvider())
            {
                alg.BlockSize = 128;
                Assert.Equal(128, alg.BlockSize);

                var emptyIV = new byte[alg.BlockSize / 8];
                alg.IV = emptyIV;
                Assert.Equal(emptyIV, alg.IV);
                alg.GenerateIV();
                Assert.NotEqual(emptyIV, alg.IV);

                var emptyKey = new byte[alg.KeySize / 8];
                alg.Key = emptyKey;
                Assert.Equal(emptyKey, alg.Key);
                alg.GenerateKey();
                Assert.NotEqual(emptyKey, alg.Key);

                alg.KeySize = 128;
                Assert.Equal(128, alg.KeySize);

                alg.Mode = CipherMode.ECB;
                Assert.Equal(CipherMode.ECB, alg.Mode);

                alg.Padding = PaddingMode.PKCS7;
                Assert.Equal(PaddingMode.PKCS7, alg.Padding);
            }
        }
		static NetAESEncryption()
		{
#if !IOS && !__ANDROID__
			AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
			List<int> temp = new List<int>();
			foreach (KeySizes keysize in aes.LegalKeySizes)
			{
				for (int i = keysize.MinSize; i <= keysize.MaxSize; i += keysize.SkipSize)
				{
					if (!temp.Contains(i))
						temp.Add(i);
					if (i == keysize.MaxSize)
						break;
				}
			}
			m_keysizes = temp;
			temp = new List<int>();
			foreach (KeySizes keysize in aes.LegalBlockSizes)
			{
				for (int i = keysize.MinSize; i <= keysize.MaxSize; i += keysize.SkipSize)
				{

					if (!temp.Contains(i))
						temp.Add(i);
					if (i == keysize.MaxSize)
						break;
				}
			}
			m_blocksizes = temp;
#endif
		}
        public static void EncryptDecryptKnownECB192()
        {
            byte[] plainTextBytes =
                new ASCIIEncoding().GetBytes("This is a sentence that is longer than a block, it ensures that multi-block functions work.");

            byte[] encryptedBytesExpected = new byte[]
            {
                0xC9, 0x7F, 0xA5, 0x5B, 0xC3, 0x92, 0xDC, 0xA6,
                0xE4, 0x9F, 0x2D, 0x1A, 0xEF, 0x7A, 0x27, 0x03,
                0x04, 0x9C, 0xFB, 0x56, 0x63, 0x38, 0xAE, 0x4F,
                0xDC, 0xF6, 0x36, 0x98, 0x28, 0x05, 0x32, 0xE9,
                0xF2, 0x6E, 0xEC, 0x0C, 0x04, 0x9D, 0x12, 0x17,
                0x18, 0x35, 0xD4, 0x29, 0xFC, 0x01, 0xB1, 0x20,
                0xFA, 0x30, 0xAE, 0x00, 0x53, 0xD4, 0x26, 0x25,
                0xA4, 0xFD, 0xD5, 0xE6, 0xED, 0x79, 0x35, 0x2A,
                0xE2, 0xBB, 0x95, 0x0D, 0xEF, 0x09, 0xBB, 0x6D,
                0xC5, 0xC4, 0xDB, 0x28, 0xC6, 0xF4, 0x31, 0x33,
                0x9A, 0x90, 0x12, 0x36, 0x50, 0xA0, 0xB7, 0xD1,
                0x35, 0xC4, 0xCE, 0x81, 0xE5, 0x2B, 0x85, 0x6B,
            };

            byte[] aes192Key = new byte[]
            {
                0xA6, 0x1E, 0xC7, 0x54, 0x37, 0x4D, 0x8C, 0xA5,
                0xA4, 0xBB, 0x99, 0x50, 0x35, 0x4B, 0x30, 0x4D,
                0x6C, 0xFE, 0x3B, 0x59, 0x65, 0xCB, 0x93, 0xE3,
            };

            using (var alg = new AesCryptoServiceProvider())
            {
                // The CipherMode and KeySize are different than the default values; this ensures the type
                // forwards the state properly to Aes.
                alg.Mode = CipherMode.ECB;
                alg.Key = aes192Key;

                byte[] encryptedBytes = alg.Encrypt(plainTextBytes);
                Assert.Equal(encryptedBytesExpected, encryptedBytes);

                byte[] decryptedBytes = alg.Decrypt(encryptedBytes);
                Assert.Equal(plainTextBytes, decryptedBytes);
            }
        }
        } //End method

        //Implements IEncryptionMachine.Decrypt2
        //Main user interface for the FortMachine library.
        //This method can be used to decrypt big files as it uses stream based operation for reading and
        //writing the data.
        //Returns true on success, false on failure.
        public bool Decrypt2(string passphrase, string inputpath, string outputpath)
        {
            FileStream   StreamIn       = null;
            FileStream   StreamOut      = null;
            CryptoStream decrypto       = null;
            FileStream   NewPlainStream = null;

            //Make sure our outputpath has correct encoding
            //byte[] filenamebytes = Encoding.Default.GetBytes(outputpath);
            //outputpath = Encoding.Default.GetString(filenamebytes);

            try
            {
                byte[] key;
                byte[] IV;
                byte[] salt;
                byte[] magic_header;
                int    BufferSize = 4096;
                byte[] buffer     = new byte[BufferSize];
                int    BytesRead;
                byte[] IntegrityHash;

                IV            = new byte[FortMachineConstants.IV_SIZE];
                salt          = new byte[FortMachineConstants.SALT_SIZE];
                magic_header  = new byte[FortMachineConstants.MAGIC_HEADER_SIZE];
                IntegrityHash = new byte[FortMachineConstants.DATA_INTEGRITY_HASH_SIZE];

                StreamIn  = new FileStream(inputpath, FileMode.Open, FileAccess.ReadWrite);
                StreamOut = new FileStream(outputpath, FileMode.OpenOrCreate, FileAccess.Write);

                //Ignore the magic header and move file pointer to the next bytes
                StreamIn.Read(magic_header, 0, FortMachineConstants.MAGIC_HEADER_SIZE);
                //Read the IV into the buffer
                StreamIn.Read(IV, 0, FortMachineConstants.IV_SIZE);
                //Read passphrase salt into a buffer
                StreamIn.Read(salt, 0, FortMachineConstants.SALT_SIZE);
                //Read data integrity hash
                StreamIn.Read(IntegrityHash, 0, FortMachineConstants.DATA_INTEGRITY_HASH_SIZE);

                key = this.ProcessKeyWithSalt(passphrase, salt);

                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

                aes.Key  = key;
                aes.IV   = IV;
                aes.Mode = CipherMode.CBC;

                decrypto = new CryptoStream(StreamOut, aes.CreateDecryptor(), CryptoStreamMode.Write);

                do
                {
                    BytesRead = StreamIn.Read(buffer, 0, BufferSize);
                    decrypto.Write(buffer, 0, BytesRead);
                } while (BytesRead != 0);

                decrypto.Close();
                StreamIn.Close();

                //Create new temporary stream from the decrypted file to verify data integrity
                NewPlainStream = new FileStream(outputpath, FileMode.Open, FileAccess.Read);

                //Verify data integrity
                if (!DataIntegrity.VerifyHash(NewPlainStream, key, IntegrityHash))
                {
                    this._IsDataTampered = true;
                }
                else
                {
                    this._IsDataTampered = false;
                }

                NewPlainStream.Close();

                File.Delete(inputpath);
            }
            catch (Exception ex)
            {
                //Clean up streams, if they where created
                if (decrypto != null)
                {
                    decrypto.Close();
                }

                if (StreamOut != null)
                {
                    StreamOut.Close();
                }

                if (StreamIn != null)
                {
                    StreamIn.Close();
                }

                if (NewPlainStream != null)
                {
                    NewPlainStream.Close();
                }

                //As decryption failed, check if the output file was created and delete it
                //because it would be incomplete.

                if (File.Exists(outputpath))
                {
                    File.Delete(outputpath);
                }

                this._LastErrorMessage = "Decryption failed: " + ex.Message;

                return(false);
            }

            return(true);
        } //End method
Exemple #5
0
        // Note that extension methods must be defined in a non-generic static class.

        // Encrypt or decrypt the data in in_bytes[] and return the result.
        public static byte[] CryptBytes(string password, byte[] in_bytes, bool encrypt)
        {
            // Make an AES service provider.
            AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();

            // Find a valid key size for this provider.
            int key_size_bits = 0;

            for (int i = 1024; i > 1; i--)
            {
                if (aes_provider.ValidKeySize(i))
                {
                    key_size_bits = i;
                    break;
                }
            }
            Debug.Assert(key_size_bits > 0);
            Console.WriteLine("Key size: " + key_size_bits);

            // Get the block size for this provider.
            int block_size_bits = aes_provider.BlockSize;

            // Generate the key and initialization vector.
            byte[] key  = null;
            byte[] iv   = null;
            byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
            MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);

            // Make the encryptor or decryptor.
            ICryptoTransform crypto_transform;

            if (encrypt)
            {
                crypto_transform = aes_provider.CreateEncryptor(key, iv);
            }
            else
            {
                crypto_transform = aes_provider.CreateDecryptor(key, iv);
            }

            // Create the output stream.
            using (MemoryStream out_stream = new MemoryStream())
            {
                // Attach a crypto stream to the output stream.
                using (CryptoStream crypto_stream = new CryptoStream(out_stream,
                                                                     crypto_transform, CryptoStreamMode.Write))
                {
                    // Write the bytes into the CryptoStream.
                    crypto_stream.Write(in_bytes, 0, in_bytes.Length);
                    try
                    {
                        crypto_stream.FlushFinalBlock();
                    }
                    catch (CryptographicException)
                    {
                        // Ignore this exception. The password is bad.
                    }
                    catch
                    {
                        // Re-throw this exception.
                        throw;
                    }

                    // return the result.
                    return(out_stream.ToArray());
                }
            }
        }
Exemple #6
0
 public AESCrypt()
 {
     m_aesCryptoServiceProvider = new AesCryptoServiceProvider();
     m_containKey = true;
     m_message    = string.Empty;
 }
        } //End method

        //Implements IEncryptionMachine.Encrypt2
        //Main user interface for the FortMachine library.
        //This method can be used to encrypt big files as stream based operations are used and
        //data is not read into memory at once.
        public bool Encrypt2(string passphrase, string inputpath, string outputpath, bool KeepPlainFile = false)
        {
            FileStream   StreamIn  = null;
            FileStream   StreamOut = null;
            CryptoStream crypto    = null;

            try
            {
                byte[]  IV;
                FortKey key;
                byte[]  KeyBytes;
                int     BufferSize = 4096;
                byte[]  buffer     = new byte[BufferSize];
                int     BytesRead;
                byte[]  IntegrityHash;

                key      = this.CreateKey(passphrase);
                KeyBytes = key.GetNew();
                IV       = this.GetRandom16IV();

                StreamIn  = new FileStream(inputpath, FileMode.Open, FileAccess.Read);
                StreamOut = new FileStream(outputpath, FileMode.OpenOrCreate, FileAccess.Write);

                IntegrityHash = DataIntegrity.GetHMACHash(StreamIn, KeyBytes);
                StreamIn.Seek(0, SeekOrigin.Begin);

                //First write our magic header to mark that the file is encrypted with Fort
                StreamOut.Write(FortMachineConstants.MAGIC_HEADER, 0, FortMachineConstants.MAGIC_HEADER_SIZE);
                //Then, write IV into the file
                StreamOut.Write(IV, 0, FortMachineConstants.IV_SIZE);
                //Then, write the salt into the file
                StreamOut.Write(key.Salt, 0, FortMachineConstants.SALT_SIZE);
                //Then, write the integrity has into the file
                StreamOut.Write(IntegrityHash, 0, FortMachineConstants.DATA_INTEGRITY_HASH_SIZE);

                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

                aes.Key  = KeyBytes;
                aes.IV   = IV;
                aes.Mode = CipherMode.CBC;

                crypto = new CryptoStream(StreamOut, aes.CreateEncryptor(), CryptoStreamMode.Write);

                do
                {
                    BytesRead = StreamIn.Read(buffer, 0, BufferSize);
                    crypto.Write(buffer, 0, BytesRead);
                } while (BytesRead != 0);

                crypto.Close();
                StreamIn.Close();

                if (!KeepPlainFile)
                {
                    File.Delete(inputpath);
                }
            }
            catch (Exception ex)
            {
                if (crypto != null)
                {
                    crypto.Close();
                }

                if (StreamIn != null)
                {
                    StreamIn.Close();
                }

                if (File.Exists(outputpath))
                {
                    File.Delete(outputpath);
                }

                this._LastErrorMessage = "Encryption failed: " + ex.Message;
                return(false);
            }

            return(true);
        } //End method
Exemple #8
0
        private static async Task DecryptPacket(IPEndPoint sender, byte[] data)
        {
            if (data.Length < UDPSendSignByteArr.Length)
            {
                Logger.Error("sender: {0} , data: {1}", sender, data.ToHex());
                return;
            }
            try {
                var udpSendSign = Config.Encoding.GetString(
                    data,
                    0,
                    UDPSendSignByteArr.Length
                    );
                if (udpSendSign != UDPSendSign)
                {
                    Logger.Error("sender: {0} , data: {1}", sender, data.ToHex());
                    return;
                }
            } catch (Exception ex) {
                Logger.Error(
                    "sender: {0} , data: {1}\r\n{2}",
                    sender,
                    data.ToHex(),
                    ex.ToString()
                    );
                return;
            }
            byte[] orig;
            if (File.Exists("debug"))
            {
                orig = new byte[data.Length - UDPSendSignByteArr.Length];
                Array.Copy(
                    data,
                    UDPSendSignByteArr.Length,
                    orig,
                    0,
                    data.Length - UDPSendSignByteArr.Length
                    );
            }
            else
            {
                orig = null;
                var key       = new byte[16];
                var timestamp = Program.GetUnixTimestamp().ModFloor(300) - 300;
                Array.Copy(Config.SPBA, key, Config.SPBA.Length);
                using (var aes = new AesCryptoServiceProvider()) {
                    aes.Mode = CipherMode.CBC;
                    for (var i = 0; i < 3; ++i)
                    {
                        key.WriteUInt(Config.SPBA.Length, timestamp);
                        try {
                            using (var ss = new MemoryStream(
                                       data,
                                       UDPSendSignByteArr.Length,
                                       data.Length - UDPSendSignByteArr.Length,
                                       false
                                       ))
                                using (var dpt = aes.CreateDecryptor(key, IV))
                                    using (var cs = new CryptoStream(
                                               ss,
                                               dpt,
                                               CryptoStreamMode.Read
                                               ))
                                        using (var ds = new MemoryStream()) {
                                            cs.CopyTo(ds);
                                            orig = ds.ToArray();
                                            break;
                                        }
                        } catch (Exception ex) {
                            var exStr = ex.ToString();
                            if (!exStr.Contains("pad"))
                            {
                                Logger.Error(
                                    "sender: {0} , data: {1} , key: {2}\r\n{3}",
                                    sender,
                                    data.ToHex(),
                                    key.ToHex(),
                                    exStr
                                    );
                            }
                        }
                        timestamp += 300;
                    }
                }
                if (orig == null)
                {
                    return;
                }
            }
            string reqStr;

            try {
                reqStr = Config.Encoding.GetString(orig);
            } catch (Exception ex) {
                Logger.Error(
                    "sender: {0} , data: {1}\r\n{2}",
                    sender,
                    data.ToHex(),
                    ex.ToString()
                    );
                return;
            }
            try {
                var reqObj = JsonConvert.DeserializeObject <ReqObj>(reqStr);
                if (string.IsNullOrWhiteSpace(reqObj.MimeType))
                {
                    Logger.Error("sender: {0} , reqStr: {1}", sender, reqStr);
                    return;
                }
                string mimeCategory;
                string mimeSubCategory;
                {
                    var idx = reqObj.MimeType.IndexOf('/');
                    if (idx == -1)
                    {
                        Logger.Error("sender: {0} , reqStr: {1}", sender, reqStr);
                        return;
                    }
                    mimeCategory    = reqObj.MimeType.Substring(0, idx);
                    mimeSubCategory = reqObj.MimeType.Substring(idx + 1);
                }
                if (string.IsNullOrWhiteSpace(reqObj.Content))
                {
                    if (MimeTypeComplexTransferHandlerDict.TryGetValue(
                            mimeCategory,
                            out Func <string, HSParams, Task> handler
                            ))
                    {
                        var hsparams =
                            JsonConvert.DeserializeObject <HSParams>(
                                reqObj.Handshake
                                );
                        await handler(mimeSubCategory, hsparams)
                        .ConfigureAwait(false);

                        return;
                    }
                }
                else
                {
                    if (MimeTypeSimpleTransferHandlerDict.TryGetValue(
                            mimeCategory,
                            out Func <string, string, Task> handler
                            ))
                    {
                        await handler(mimeSubCategory, reqObj.Content)
                        .ConfigureAwait(false);

                        return;
                    }
                }
                Logger.Error(
                    "Unknown type: sender: {0} , reqStr: {1}", sender, reqStr
                    );
            } catch (Exception ex) {
                Logger.Error(
                    "sender: {0} , reqStr: {1}\r\n{2}",
                    sender, reqStr, ex.ToString()
                    );
                return;
            }
        }
Exemple #9
0
        /// <summary>
        /// Returns a plain text message given an encrypted message.
        /// </summary>
        /// <param name="inputMessage">The encrypted message.</param>
        /// <param name="requireEncryption">A value to indicate that the data read from the server should be encrypted.</param>
        /// <returns>The plain text message bytes.</returns>
        internal byte[] DecryptMessage(string inputMessage, bool?requireEncryption)
        {
            CommonUtility.AssertNotNull("inputMessage", inputMessage);

            try
            {
                CloudQueueEncryptedMessage encryptedMessage = JsonConvert.DeserializeObject <CloudQueueEncryptedMessage>(inputMessage);

                if (requireEncryption.HasValue && requireEncryption.Value && encryptedMessage.EncryptionData == null)
                {
                    throw new StorageException(SR.EncryptionDataNotPresentError, null)
                          {
                              IsRetryable = false
                          };
                }

                if (encryptedMessage.EncryptionData != null)
                {
                    EncryptionData encryptionData = encryptedMessage.EncryptionData;

                    CommonUtility.AssertNotNull("ContentEncryptionIV", encryptionData.ContentEncryptionIV);
                    CommonUtility.AssertNotNull("EncryptedKey", encryptionData.WrappedContentKey.EncryptedKey);

                    // Throw if the encryption protocol on the message doesn't match the version that this client library understands
                    // and is able to decrypt.
                    if (encryptionData.EncryptionAgent.Protocol != Constants.EncryptionConstants.EncryptionProtocolV1)
                    {
                        throw new StorageException(SR.EncryptionProtocolVersionInvalid, null)
                              {
                                  IsRetryable = false
                              };
                    }

                    // Throw if neither the key nor the key resolver are set.
                    if (this.Key == null && this.KeyResolver == null)
                    {
                        throw new StorageException(SR.KeyAndResolverMissingError, null)
                              {
                                  IsRetryable = false
                              };
                    }

                    byte[] contentEncryptionKey = null;

                    // 1. Invoke the key resolver if specified to get the key. If the resolver is specified but does not have a
                    // mapping for the key id, an error should be thrown. This is important for key rotation scenario.
                    // 2. If resolver is not specified but a key is specified, match the key id on the key and and use it.
                    // Calling UnwrapKeyAsync synchronously is fine because for the storage client scenario, unwrap happens
                    // locally. No service call is made.
                    if (this.KeyResolver != null)
                    {
                        IKey keyEncryptionKey = CommonUtility.RunWithoutSynchronizationContext(() => this.KeyResolver.ResolveKeyAsync(encryptionData.WrappedContentKey.KeyId, CancellationToken.None).Result);

                        CommonUtility.AssertNotNull("keyEncryptionKey", keyEncryptionKey);
                        contentEncryptionKey = CommonUtility.RunWithoutSynchronizationContext(() => keyEncryptionKey.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, CancellationToken.None).Result);
                    }
                    else
                    {
                        if (this.Key.Kid == encryptionData.WrappedContentKey.KeyId)
                        {
                            contentEncryptionKey = CommonUtility.RunWithoutSynchronizationContext(() => this.Key.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, CancellationToken.None).Result);
                        }
                        else
                        {
                            throw new StorageException(SR.KeyMismatch, null)
                                  {
                                      IsRetryable = false
                                  };
                        }
                    }

                    switch (encryptionData.EncryptionAgent.EncryptionAlgorithm)
                    {
                    case EncryptionAlgorithm.AES_CBC_256:
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                        using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
#else
                        using (AesManaged myAes = new AesManaged())
#endif
                        {
                            myAes.Key = contentEncryptionKey;
                            myAes.IV  = encryptionData.ContentEncryptionIV;

                            byte[] src = Convert.FromBase64String(encryptedMessage.EncryptedMessageContents);
                            using (ICryptoTransform decryptor = myAes.CreateDecryptor())
                            {
                                return(decryptor.TransformFinalBlock(src, 0, src.Length));
                            }
                        }

                    default:
                        throw new StorageException(SR.InvalidEncryptionAlgorithm, null)
                              {
                                  IsRetryable = false
                              };
                    }
                }
                else
                {
                    return(Convert.FromBase64String(encryptedMessage.EncryptedMessageContents));
                }
            }
            catch (JsonException ex)
            {
                throw new StorageException(SR.EncryptedMessageDeserializingError, ex)
                      {
                          IsRetryable = false
                      };
            }
            catch (StorageException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new StorageException(SR.DecryptionLogicError, ex)
                      {
                          IsRetryable = false
                      };
            }
        }
        /// <summary>
        /// Return a decrypted entity. This method is used for decrypting entity properties.
        /// </summary>
        internal Dictionary <string, EntityProperty> DecryptEntity(IDictionary <string, EntityProperty> properties, HashSet <string> encryptedPropertyDetailsSet, string partitionKey, string rowKey, byte[] contentEncryptionKey, EncryptionData encryptionData, bool isJavav1)
        {
            try
            {
                Dictionary <string, EntityProperty> decryptedProperties = new Dictionary <string, EntityProperty>();

                switch (encryptionData.EncryptionAgent.EncryptionAlgorithm)
                {
                case EncryptionAlgorithm.AES_CBC_256:
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                    using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                    {
                        using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
#else
                    using (AesManaged myAes = new AesManaged())
                    {
                        using (SHA256Managed sha256 = new SHA256Managed())
#endif
                        {
                            myAes.Key = contentEncryptionKey;

                            foreach (KeyValuePair <string, EntityProperty> kvp in properties)
                            {
                                if (kvp.Key == Constants.EncryptionConstants.TableEncryptionKeyDetails || kvp.Key == Constants.EncryptionConstants.TableEncryptionPropertyDetails)
                                {
                                    // Do nothing. Do not add to the result properties.
                                }
                                else if (encryptedPropertyDetailsSet.Contains(kvp.Key))
                                {
                                    byte[] columnIV = sha256.ComputeHash(CommonUtility.BinaryAppend(encryptionData.ContentEncryptionIV, Encoding.UTF8.GetBytes(isJavav1 ? string.Concat(partitionKey, rowKey, kvp.Key) : string.Concat(rowKey, partitionKey, kvp.Key))));
                                    Array.Resize <byte>(ref columnIV, 16);
                                    myAes.IV = columnIV;

                                    byte[] src = kvp.Value.BinaryValue;
                                    using (ICryptoTransform transform = myAes.CreateDecryptor())
                                    {
                                        byte[] dest       = transform.TransformFinalBlock(src, 0, src.Length);
                                        string destString = Encoding.UTF8.GetString(dest, 0, dest.Length);
                                        decryptedProperties.Add(kvp.Key, new EntityProperty(destString));
                                    }
                                }
                                else
                                {
                                    decryptedProperties.Add(kvp.Key, kvp.Value);
                                }
                            }
                        }
                    }

                    return(decryptedProperties);

                default:
                    throw new StorageException(SR.InvalidEncryptionAlgorithm, null)
                          {
                              IsRetryable = false
                          };
                }
            }
            catch (JsonException ex)
            {
                throw new StorageException(SR.EncryptionMetadataError, ex)
                      {
                          IsRetryable = false
                      };
            }
            catch (StorageException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new StorageException(SR.DecryptionLogicError, ex)
                      {
                          IsRetryable = false
                      };
            }
        }
		/// <summary>
		/// Encrypt outgoing message
		/// </summary>
		public bool Encrypt(NetOutgoingMessage msg)
		{
			try
			{
#if IS_FULL_NET_AVAILABLE
				// nested usings are fun!
				using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider { KeySize = m_bitSize, Mode = CipherMode.CBC })
				{
					using (ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateEncryptor(m_key, m_iv))
					{
						using (MemoryStream memoryStream = new MemoryStream())
						{
							using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
																			 CryptoStreamMode.Write))
							{
								cryptoStream.Write(msg.m_data, 0, msg.m_data.Length);
							}
							msg.m_data = memoryStream.ToArray();
						}
					}
				}			
#endif
			}
			catch
			{
				return false;
			}
			return true;
		}
Exemple #12
0
        /* goodB2G() - use badsource and goodsink*/
        private void GoodB2G()
        {
            string password;

            password = ""; /* init password */
            /* Read data using an outbound tcp connection */
            {
                try
                {
                    /* Read data using an outbound tcp connection */
                    using (TcpClient tcpConn = new TcpClient("host.example.org", 39544))
                    {
                        /* read input from socket */
                        using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                        {
                            /* POTENTIAL FLAW: Read password using an outbound tcp connection */
                            password = sr.ReadLine();
                        }
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, "Error with stream reading", exceptIO);
                }
            }
            for (int k = 0; k < 1; k++)
            {
                if (password != null)
                {
                    /* FIX: Decrypt password before using in getConnection() */
                    {
                        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
                        {
                            aesAlg.Padding = PaddingMode.None;
                            aesAlg.Key     = Encoding.UTF8.GetBytes("ABCDEFGHABCDEFGH");
                            // Create a decryptor to perform the stream transform.
                            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                            // Create the streams used for decryption.
                            using (MemoryStream msDecrypt = new MemoryStream(Encoding.UTF8.GetBytes(password)))
                            {
                                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.
                                        password = srDecrypt.ReadToEnd();
                                    }
                                }
                            }
                        }
                    }
                    try
                    {
                        /* POTENTIAL FLAW: use password directly in SqlConnection() */
                        using (SqlConnection connection = new SqlConnection(@"Data Source=(local);Initial Catalog=CWE256;User ID=" + "sa" + ";Password="******"select * from test_table", connection))
                            {
                                command.ExecuteNonQuery();
                            }
                        }
                    }
                    catch (SqlException exceptSql)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, "Error with database connection", exceptSql);
                    }
                }
            }
        }
        internal byte[] DecryptMetadataAndReturnCEK(string partitionKey, string rowKey, EntityProperty encryptionKeyProperty, EntityProperty propertyDetailsProperty, out EncryptionData encryptionData, out bool isJavaV1)
        {
            // Throw if neither the key nor the resolver are set.
            if (this.Key == null && this.KeyResolver == null)
            {
                throw new StorageException(SR.KeyAndResolverMissingError, null)
                      {
                          IsRetryable = false
                      };
            }

            try
            {
                encryptionData = JsonConvert.DeserializeObject <EncryptionData>(encryptionKeyProperty.StringValue);
                EncryptionData encryptionDataCopy = encryptionData; // This is necessary because you cannot use "out" variables in a lambda.

                CommonUtility.AssertNotNull("ContentEncryptionIV", encryptionData.ContentEncryptionIV);
                CommonUtility.AssertNotNull("EncryptedKey", encryptionData.WrappedContentKey.EncryptedKey);

                // Throw if the encryption protocol on the entity doesn't match the version that this client library understands
                // and is able to decrypt.
                if (encryptionData.EncryptionAgent.Protocol != Constants.EncryptionConstants.EncryptionProtocolV1)
                {
                    throw new StorageException(SR.EncryptionProtocolVersionInvalid, null)
                          {
                              IsRetryable = false
                          };
                }

                isJavaV1 = (encryptionData.EncryptionAgent.Protocol == Constants.EncryptionConstants.EncryptionProtocolV1) &&
                           ((encryptionData.KeyWrappingMetadata == null) ||
                            (encryptionData.KeyWrappingMetadata.ContainsKey(Constants.EncryptionConstants.AgentMetadataKey) &&
                             encryptionData.KeyWrappingMetadata[Constants.EncryptionConstants.AgentMetadataKey].Contains("Java")));

                byte[] contentEncryptionKey = null;

                // 1. Invoke the key resolver if specified to get the key. If the resolver is specified but does not have a
                // mapping for the key id, an error should be thrown. This is important for key rotation scenario.
                // 2. If resolver is not specified but a key is specified, match the key id on the key and and use it.
                // Calling UnwrapKeyAsync synchronously is fine because for the storage client scenario, unwrap happens
                // locally. No service call is made.
                if (this.KeyResolver != null)
                {
                    IKey keyEncryptionKey = CommonUtility.RunWithoutSynchronizationContext(() => this.KeyResolver.ResolveKeyAsync(encryptionDataCopy.WrappedContentKey.KeyId, CancellationToken.None).Result);

                    CommonUtility.AssertNotNull("keyEncryptionKey", keyEncryptionKey);
                    contentEncryptionKey = CommonUtility.RunWithoutSynchronizationContext(() => keyEncryptionKey.UnwrapKeyAsync(encryptionDataCopy.WrappedContentKey.EncryptedKey, encryptionDataCopy.WrappedContentKey.Algorithm, CancellationToken.None).Result);
                }
                else
                {
                    if (this.Key.Kid == encryptionData.WrappedContentKey.KeyId)
                    {
                        contentEncryptionKey = CommonUtility.RunWithoutSynchronizationContext(() => this.Key.UnwrapKeyAsync(encryptionDataCopy.WrappedContentKey.EncryptedKey, encryptionDataCopy.WrappedContentKey.Algorithm, CancellationToken.None).Result);
                    }
                    else
                    {
                        throw new StorageException(SR.KeyMismatch, null)
                              {
                                  IsRetryable = false
                              };
                    }
                }

                // Decrypt the property details set and add it to entity properties.
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                {
                    using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
#else
                using (AesManaged myAes = new AesManaged())
                {
                    using (SHA256Managed sha256 = new SHA256Managed())
#endif
                    {
                        // Here we are correcting for a bug in Java's v1 encryption.
                        // Java v1 constructed the IV as PK + RK + column name.  Other libraries use RK + PK + column name.
                        string IVString   = isJavaV1 ? string.Concat(partitionKey, rowKey, Constants.EncryptionConstants.TableEncryptionPropertyDetails) : string.Concat(rowKey, partitionKey, Constants.EncryptionConstants.TableEncryptionPropertyDetails);
                        byte[] metadataIV = sha256.ComputeHash(CommonUtility.BinaryAppend(encryptionData.ContentEncryptionIV, Encoding.UTF8.GetBytes(IVString)));
                        Array.Resize <byte>(ref metadataIV, 16);
                        myAes.IV  = metadataIV;
                        myAes.Key = contentEncryptionKey;

                        using (ICryptoTransform transform = myAes.CreateDecryptor())
                        {
                            byte[] src = propertyDetailsProperty.BinaryValue;
                            propertyDetailsProperty.BinaryValue = transform.TransformFinalBlock(src, 0, src.Length);
                        }
                    }
                }

                return(contentEncryptionKey);
            }
            catch (JsonException ex)
            {
                throw new StorageException(SR.EncryptionMetadataError, ex)
                      {
                          IsRetryable = false
                      };
            }
            catch (StorageException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new StorageException(SR.DecryptionLogicError, ex)
                      {
                          IsRetryable = false
                      };
            }
        }
Exemple #14
0
        static void Main(string[] args)
        {
            byte[]                   msg;
            IPEndPoint               serverEndPoint;
            TcpClient                client       = null;
            NetworkStream            netStream    = null;
            ProtocolSI               protocol     = null;
            AesCryptoServiceProvider aes          = null;
            SymmetricsSI             symmetricsSI = null;
            RSACryptoServiceProvider rsaClient    = null;
            RSACryptoServiceProvider rsaServer    = null;

            try
            {
                Console.WriteLine("CLIENT");

                #region Defenitions
                // algortimos assimétricos
                rsaClient = new RSACryptoServiceProvider();
                rsaServer = new RSACryptoServiceProvider();

                // algoritmos simétrico a usar...
                aes          = new AesCryptoServiceProvider();
                symmetricsSI = new SymmetricsSI(aes);


                // Client/Server Protocol to SI
                protocol = new ProtocolSI();

                // Defenitions for TcpClient: IP:port (127.0.0.1:13000)
                serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000);
                #endregion

                Console.WriteLine(SEPARATOR);

                #region TCP Connection
                // Connects to Server ...
                Console.Write("Connecting to server... ");
                client = new TcpClient();
                client.Connect(serverEndPoint);
                netStream = client.GetStream();
                Console.WriteLine("ok");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Public Keys
                // Send public key...
                Console.Write("Sending public key... ");
                msg = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaClient.ToXmlString(false));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");

                // Receive server public key
                Console.Write("waiting for server public key...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                rsaServer.FromXmlString(protocol.GetStringFromData());
                Console.WriteLine("ok");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Secret Key
                // Send key...
                Console.Write("Sending  key... ");
                msg = protocol.Make(ProtocolSICmdType.SECRET_KEY, rsaServer.Encrypt(aes.Key, true));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine("   Sent: " + ProtocolSI.ToHexString(aes.Key));

                // Receive ack
                Console.Write("waiting for ACK...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");


                // Send iv...
                Console.Write("Sending  iv... ");
                msg = protocol.Make(ProtocolSICmdType.IV, rsaServer.Encrypt(aes.IV, true));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine("   Sent: " + ProtocolSI.ToHexString(aes.IV));

                // Receive ack
                Console.Write("waiting for ACK...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");

                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Data (Secure channel)
                // Send data...
                byte[] clearData = Encoding.UTF8.GetBytes("hello world!!!");
                Console.Write("Sending  data... ");
                byte[] encryptedData = symmetricsSI.Encrypt(clearData);
                msg = protocol.Make(ProtocolSICmdType.DATA, encryptedData);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine("   Data: {0} = {1}", ProtocolSI.ToString(clearData), ProtocolSI.ToHexString(clearData));
                Console.WriteLine("   Encrypted: {0}", ProtocolSI.ToHexString(encryptedData));

                // Receive answer from server
                Console.Write("waiting for ACK...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");
                #endregion



                #region Send Digital signature
                Console.Write("Sending digital signature... ");
                msg = protocol.Make(ProtocolSICmdType.DIGITAL_SIGNATURE, rsaClient.SignData(encryptedData, new SHA256CryptoServiceProvider()));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("OK");

                Console.Write("waiting... ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine(protocol.GetCmdType());

                #endregion
            } catch (Exception ex)
            {
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Exception: {0}", ex.ToString());
            }
            finally
            {
                // Close connections
                if (netStream != null)
                {
                    netStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Connection with server was closed.");
            }

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key...");
            Console.ReadKey();
        }
Exemple #15
0
        public override bool Execute()
        {
            if (this.SourceFiles.Length == 0)
            {
                return(true);
            }

            if (this.DestinationFiles != null && this.SourceFiles.Length != this.DestinationFiles.Length)
            {
                this.Log.LogError("Number of source files is different than number of destination files.");
                return(false);
            }

            if (this.DestinationFiles != null && this.DestinationFolder != null)
            {
                this.Log.LogError("You must specify only one attribute from DestinationFiles and DestinationFolder");
                return(false);
            }

            FileEncrypter encrypter = new FileEncrypter();

            encrypter.Logger = new ExecutionLogger(this);

            Aes provider = new AesCryptoServiceProvider();

            provider.Key = FileEncrypter.DeriveKey(this.EncryptionSeed);

            if (this.DestinationFiles != null && this.DestinationFiles.Length > 0)
            {
                for (int i = 0; i < this.SourceFiles.Length; i++)
                {
                    ITaskItem sourceItem      = this.SourceFiles [i];
                    ITaskItem destinationItem = this.DestinationFiles [i];
                    String    sourcePath      = sourceItem.GetMetadata("FullPath");
                    String    destinationPath = destinationItem.GetMetadata("FullPath");
                    if (!File.Exists(sourcePath))
                    {
                        this.Log.LogError("Cannot encrypt {0} to {1}, as the source file doesn't exist.", new object[] {
                            sourcePath,
                            destinationPath
                        });
                    }
                    else
                    {
                        String parentDestinationPath = Path.GetDirectoryName(destinationPath);
                        if (!Directory.Exists(parentDestinationPath))
                        {
                            Directory.CreateDirectory(parentDestinationPath);
                        }
                        encrypter.Encrypt(sourcePath, destinationPath, provider);
                    }
                }
                return(true);
            }

            if (this.DestinationFolder == null)
            {
                this.Log.LogError("You must specify DestinationFolder attribute.");
                return(false);
            }

            String destinationFolder = this.DestinationFolder.GetMetadata("FullPath");

            if (!Directory.Exists(destinationFolder))
            {
                Directory.CreateDirectory(destinationFolder);
            }

            for (int i = 0; i < this.SourceFiles.Length; i++)
            {
                ITaskItem sourceItem      = this.SourceFiles [i];
                String    sourcePath      = sourceItem.GetMetadata("FullPath");
                String    path            = sourceItem.GetMetadata("Filename") + sourceItem.GetMetadata("Extension");
                String    destinationPath = Path.Combine(destinationFolder, path);
                if (!File.Exists(sourcePath))
                {
                    this.Log.LogError("Cannot encrypt {0} to {1}, as the source file doesn't exist.", new object[] {
                        sourcePath,
                        destinationPath
                    });
                }
                else
                {
                    encrypter.Encrypt(sourcePath, destinationPath, provider);
                }
            }

            return(true);
        }
        /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
        private void GoodB2G2()
        {
            string password;

            if (IO.staticFive == 5)
            {
                password = ""; /* init password */
                /* read input from WebClient */
                {
                    try
                    {
                        using (WebClient client = new WebClient())
                        {
                            using (StreamReader sr = new StreamReader(client.OpenRead("http://www.example.org/")))
                            {
                                /* POTENTIAL FLAW: Read password from a web server with WebClient */

                                /* This will be reading the first "line" of the response body,
                                 * which could be very long if there are no newlines in the HTML */
                                password = sr.ReadLine();
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, "Error with stream reading", exceptIO);
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure password is inititialized before the Sink to avoid compiler errors */
                password = null;
            }
            if (IO.staticFive == 5)
            {
                if (password != null)
                {
                    /* FIX: Decrypt password before using in getConnection() */
                    {
                        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
                        {
                            aesAlg.Padding = PaddingMode.None;
                            aesAlg.Key     = Encoding.UTF8.GetBytes("ABCDEFGHABCDEFGH");
                            // Create a decryptor to perform the stream transform.
                            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                            // Create the streams used for decryption.
                            using (MemoryStream msDecrypt = new MemoryStream(Encoding.UTF8.GetBytes(password)))
                            {
                                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.
                                        password = srDecrypt.ReadToEnd();
                                    }
                                }
                            }
                        }
                    }
                    try
                    {
                        /* POTENTIAL FLAW: use password directly in SqlConnection() */
                        using (SqlConnection connection = new SqlConnection(@"Data Source=(local);Initial Catalog=CWE256;User ID=" + "sa" + ";Password="******"select * from test_table", connection))
                            {
                                command.ExecuteNonQuery();
                            }
                        }
                    }
                    catch (SqlException exceptSql)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, "Error with database connection", exceptSql);
                    }
                }
            }
        }
Exemple #17
0
 public AesEnryptionService()
 {
     aesInstance = new AesCryptoServiceProvider();
 }
Exemple #18
0
 /// <summary>
 /// 构造函数,默认
 /// </summary>
 public AESCrypt()
 {
     _aesCryptoServiceProvider = new AesCryptoServiceProvider();
     ContainKey = true;
     Message    = string.Empty;
 }
Exemple #19
0
 public AesEnryptionService(string plainTxt)
 {
     aesInstance = new AesCryptoServiceProvider();
     plainText = plainTxt;
 }
		/// <summary>
		/// Decrypt incoming message
		/// </summary>
		public bool Decrypt(NetIncomingMessage msg)
		{
#if !IOS && !__ANDROID__
			try
			{
				// nested usings are fun!
				using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider { KeySize = m_bitSize, Mode = CipherMode.CBC })
				{
					using (ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateDecryptor(m_key, m_iv))
					{
						using (MemoryStream memoryStream = new MemoryStream())
						{
							using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
																			 CryptoStreamMode.Write))
							{
								cryptoStream.Write(msg.m_data, 0, msg.m_data.Length);
							}
							msg.m_data = memoryStream.ToArray();
						}
					}
				}

			}
			catch
			{
				return false;
			}
			return true;
#else
			return false;
#endif
		}
        /// <summary>
        /// Return an encrypted entity. This method is used for encrypting entity properties.
        /// </summary>
        internal Dictionary <string, EntityProperty> EncryptEntity(IDictionary <string, EntityProperty> properties, string partitionKey, string rowKey, Func <string, string, string, bool> encryptionResolver)
        {
            CommonUtility.AssertNotNull("properties", properties);

            // The Key should be set on the policy for encryption. Otherwise, throw an error.
            if (this.Key == null)
            {
                throw new InvalidOperationException(SR.KeyMissingError, null);
            }

            EncryptionData encryptionData = new EncryptionData();

            encryptionData.EncryptionAgent     = new EncryptionAgent(Constants.EncryptionConstants.EncryptionProtocolV1, EncryptionAlgorithm.AES_CBC_256);
            encryptionData.KeyWrappingMetadata = new Dictionary <string, string>();
            encryptionData.KeyWrappingMetadata[Constants.EncryptionConstants.AgentMetadataKey] = Constants.EncryptionConstants.AgentMetadataValue;

            Dictionary <string, EntityProperty> encryptedProperties = new Dictionary <string, EntityProperty>();
            HashSet <string> encryptionPropertyDetailsSet           = new HashSet <string>();

#if WINDOWS_DESKTOP && !WINDOWS_PHONE
            using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
            {
                using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
#else
            using (AesManaged myAes = new AesManaged())
            {
                using (SHA256Managed sha256 = new SHA256Managed())
#endif
                {
                    encryptionData.ContentEncryptionIV = myAes.IV;

                    // Wrap always happens locally, irrespective of local or cloud key. So it is ok to call it synchronously.
                    Tuple <byte[], string> wrappedKey = CommonUtility.RunWithoutSynchronizationContext(() => this.Key.WrapKeyAsync(myAes.Key, null /* algorithm */, CancellationToken.None).Result);
                    encryptionData.WrappedContentKey = new WrappedKey(this.Key.Kid, wrappedKey.Item1, wrappedKey.Item2);

                    foreach (KeyValuePair <string, EntityProperty> kvp in properties)
                    {
                        if (encryptionResolver != null && encryptionResolver(partitionKey, rowKey, kvp.Key))
                        {
                            // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity case
                            // where a user adds a new property as follows - ent.Properties.Add("foo2", null);
                            if (kvp.Value == null)
                            {
                                throw new InvalidOperationException(SR.EncryptingNullPropertiesNotAllowed);
                            }

                            kvp.Value.IsEncrypted = true;
                        }

                        // IsEncrypted is set to true when either the EncryptPropertyAttribute is set on a property or when it is
                        // specified in the encryption resolver or both.
                        if (kvp.Value != null && kvp.Value.IsEncrypted)
                        {
                            // Throw if users try to encrypt non-string properties.
                            if (kvp.Value.PropertyType != EdmType.String)
                            {
                                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.UnsupportedPropertyTypeForEncryption, kvp.Value.PropertyType));
                            }

                            byte[] columnIV = sha256.ComputeHash(CommonUtility.BinaryAppend(encryptionData.ContentEncryptionIV, Encoding.UTF8.GetBytes(string.Join(partitionKey, rowKey, kvp.Key))));
                            Array.Resize <byte>(ref columnIV, 16);
                            myAes.IV = columnIV;

                            using (ICryptoTransform transform = myAes.CreateEncryptor())
                            {
                                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity or POCO
                                // case when the property value is null.
                                if (kvp.Value.IsNull)
                                {
                                    throw new InvalidOperationException(SR.EncryptingNullPropertiesNotAllowed);
                                }

                                byte[] src  = Encoding.UTF8.GetBytes(kvp.Value.StringValue);
                                byte[] dest = transform.TransformFinalBlock(src, 0, src.Length);

                                // Store the encrypted properties as binary values on the service instead of base 64 encoded strings because strings are stored as a sequence of
                                // WCHARs thereby further reducing the allowed size by half. During retrieve, it is handled by the response parsers correctly
                                // even when the service does not return the type for JSON no-metadata.
                                encryptedProperties.Add(kvp.Key, new EntityProperty(dest));
                                encryptionPropertyDetailsSet.Add(kvp.Key);
                            }
                        }
                        else
                        {
                            encryptedProperties.Add(kvp.Key, kvp.Value);
                        }
                    }

                    // Encrypt the property details set and add it to entity properties.
                    byte[] metadataIV = sha256.ComputeHash(CommonUtility.BinaryAppend(encryptionData.ContentEncryptionIV, Encoding.UTF8.GetBytes(string.Join(partitionKey, rowKey, Constants.EncryptionConstants.TableEncryptionPropertyDetails))));
                    Array.Resize <byte>(ref metadataIV, 16);
                    myAes.IV = metadataIV;

                    using (ICryptoTransform transform = myAes.CreateEncryptor())
                    {
                        byte[] src  = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(encryptionPropertyDetailsSet));
                        byte[] dest = transform.TransformFinalBlock(src, 0, src.Length);
                        encryptedProperties.Add(Constants.EncryptionConstants.TableEncryptionPropertyDetails, new EntityProperty(dest));
                    }
                }
            }

            // Add the key details to entity properties.
            encryptedProperties.Add(Constants.EncryptionConstants.TableEncryptionKeyDetails, new EntityProperty(JsonConvert.SerializeObject(encryptionData)));
            return(encryptedProperties);
        }
Exemple #22
0
 public AesCryptor()
 {
     aes = new AesCryptoServiceProvider();
 }
 public static void VerifyDefaults()
 {
     using (var alg = new AesCryptoServiceProvider())
     {
         Assert.Equal(128, alg.BlockSize);
         Assert.Equal(256, alg.KeySize);
         Assert.Equal(CipherMode.CBC, alg.Mode);
         Assert.Equal(PaddingMode.PKCS7, alg.Padding);
     }
 }
Exemple #24
0
        //Створення при зчитувані з файлу
        public Header(Stream memoryStream, UInt64 startPos, SafeStreamAccess headersStream, AesCryptoServiceProvider AES)
        {
            memoryData = memoryStream;
            //Зчитуємо незакодовані дані, IV (16 байт) і Exists (1 байт)
            byte[] buf = new byte[17];
            _StartPos             = startPos;
            memoryStream.Position = (int)startPos;
            memoryStream.Read(buf, 0, buf.Length);

            //Записуємо зчитані дані в відповідні параметри
            _IV = new byte[16];
            Buffer.BlockCopy(buf, 0, _IV, 0, 16);
            _Exists = buf[16] < 128;

            _AES = AES;
            SetAESValue();
            Crypto.AES_Decrypt(memoryStream, buf, 16, this.AES);

            _InfSize = BitConverter.ToUInt16(buf, 13);
            _ElType  = (ElementType)(buf[15] / 128);

            writedInFile = true;

            _headersFileStream = headersStream;

            if (_Exists)
            {
                infDdata = new byte[_InfSize];

                SetAESValue();

                //memoryData.Position = (int)_StartPos + Length;
                Crypto.AES_Decrypt(memoryData, infDdata, infDdata.Length, AES);
            }
        }
 public AESEncryption()
 {
     myAes = new AesCryptoServiceProvider();
 }
Exemple #26
0
        private string Encrypt(string text, string strMeterID)
        {
            string strAESKey = string.Empty;

            //Need to check does the key exist

            using (var db = new uwkeydataEntities1())
            {
                foreach (MeterKey mk in db.MeterKeys)
                {
                    if (mk.MeterID == strMeterID)
                    {
                        strAESKey = mk.AesKey;
                    }
                }
            }

            //if key does not already exist
            if (strAESKey == string.Empty)
            {
                //make key on the fly
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {
                    myRijndael.KeySize = 128;
                    myRijndael.GenerateKey();
                    // we dont need iv just key value
                    //myRijndael.GenerateIV();

                    byte[] xkey = myRijndael.Key;
                    //var xIV = myRijndael.IV;

                    AesCryptoServiceProvider aes;
                    // AesCryptoServiceProvider
                    using (aes = new AesCryptoServiceProvider())
                    {
                        aes.BlockSize = 128;
                        aes.KeySize   = 128;
                        aes.IV        = Encoding.UTF8.GetBytes(AesIV);
                        aes.Key       = xkey;
                        aes.Mode      = CipherMode.CBC;
                        aes.Padding   = PaddingMode.PKCS7;

                        //store meterID AES Key AES IV in Database

                        using (var db = new uwkeydataEntities1())
                        {
                            MeterKey mk = new MeterKey();
                            mk.MeterID = strMeterID;
                            mk.AesKey  = Convert.ToBase64String(aes.Key);
                            db.MeterKeys.Add(mk);
                            db.SaveChanges();
                        }

                        //byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
                        // Convert string to byte array
                        byte[] src = Encoding.Unicode.GetBytes(text);

                        // encryption
                        using (ICryptoTransform encrypt = aes.CreateEncryptor())
                        {
                            byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                            aes.Clear();
                            aes.Dispose();
                            encrypt.Dispose();
                            // Convert byte array to Base64 strings
                            return(Convert.ToBase64String(dest));
                        }
                    }
                }
            }
            else
            {
                //we have the key
                AesCryptoServiceProvider aes;
                // AesCryptoServiceProvider
                using (aes = new AesCryptoServiceProvider())
                {
                    aes.BlockSize = 128;
                    aes.KeySize   = 128;
                    aes.IV        = Encoding.UTF8.GetBytes(AesIV);
                    //aes.Key = Encoding.UTF8.GetBytes(strAESKey);
                    aes.Key     = System.Convert.FromBase64String(strAESKey);
                    aes.Mode    = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;

                    //byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
                    // Convert string to byte array
                    byte[] src = Encoding.Unicode.GetBytes(text);

                    // encryption
                    using (ICryptoTransform encrypt = aes.CreateEncryptor())
                    {
                        byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                        aes.Clear();
                        aes.Dispose();
                        encrypt.Dispose();
                        // Convert byte array to Base64 strings
                        return(Convert.ToBase64String(dest));
                    }
                }
            }
        }