Пример #1
0
        /// <summary>
        /// Serializes data.
        /// </summary>
        /// <typeparam name="_T">data type to be serialized</typeparam>
        /// <param name="dataToSerialize">data to be serialized</param>
        /// <returns>serialized data</returns>
        public object Serialize <_T>(_T dataToSerialize)
        {
            using (EneterTrace.Entering())
            {
                byte[][] aData = new byte[3][];

                // Generate random key for AES.
                AesManaged anAes = new AesManaged();
                anAes.KeySize = myAesBitSize;
                anAes.GenerateIV();
                anAes.GenerateKey();

                // Serialize data with AES using the random key.
                AesSerializer anAesSerializer = new AesSerializer(anAes.Key, anAes.IV, myUnderlyingSerializer);
                aData[2] = (byte[])anAesSerializer.Serialize <_T>(dataToSerialize);

                // Encrypt the random key with RSA using the public key.
                // Note: Only guy having the private key can decrypt it.
                RSACryptoServiceProvider aCryptoServiceProvider = new RSACryptoServiceProvider();
                aCryptoServiceProvider.ImportParameters(myPublicKey);
                aData[0] = aCryptoServiceProvider.Encrypt(anAes.Key, false);
                aData[1] = aCryptoServiceProvider.Encrypt(anAes.IV, false);

                // Serialize encrypted data, key and iv with the underlying serializer.
                object aSerializedData = myUnderlyingSerializer.Serialize <byte[][]>(aData);

                return(aSerializedData);
            }
        }
Пример #2
0
        /// <summary>
        /// Deserializes data.
        /// </summary>
        /// <typeparam name="_T">data type to be deserialized</typeparam>
        /// <param name="serializedData">serialized data</param>
        /// <returns>deserialized data type</returns>
        public _T Deserialize <_T>(object serializedData)
        {
            using (EneterTrace.Entering())
            {
                // Deserialize data
                byte[][] aData = myUnderlyingSerializer.Deserialize <byte[][]>(serializedData);

                // Use the private key to decrypt the key and iv for the AES.
                RSACryptoServiceProvider aCryptoServiceProvider = new RSACryptoServiceProvider();
                aCryptoServiceProvider.ImportParameters(myPrivateKey);
                byte[] aKey = aCryptoServiceProvider.Decrypt(aData[0], false);
                byte[] anIv = aCryptoServiceProvider.Decrypt(aData[1], false);

                // Decrypt data content which its encrypted with AES.
                AesSerializer anAes             = new AesSerializer(aKey, anIv, myUnderlyingSerializer);
                _T            aDeserializedData = anAes.Deserialize <_T>(aData[2]);

                return(aDeserializedData);
            }
        }