/// <summary>
        /// Decrypt data using a key
        /// </summary>
        /// <param name="encryption">The encryption to extend</param>
        /// <param name="encryptedDataBuffer">The data buffer which contains the data to decrypt</param>
        /// <param name="index">The index in <paramref name="encryptedDataBuffer"/> at which the data to decrypt begins</param>
        /// <param name="count">The length of the data in <paramref name="encryptedDataBuffer"/> to decrypt</param>
        /// <param name="key">The key to use when decrypting the data</param>
        /// <param name="iv">The initialisation vector to use when decrypting the data</param>
        /// <exception cref="ArgumentNullException"><paramref name="encryptedDataBuffer"/> or <paramref name="key"/> or <paramref name="iv"/> is <see langword="null"/></exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> or <paramref name="count"/> is less than zero, or the sum of <paramref name="count"/> and <paramref name="index"/> is greater than the length of <paramref name="encryptedDataBuffer"/></exception>
        public static byte[] Decrypt(this ISymmetricEncryption encryption, byte[] encryptedDataBuffer, int index, int count, byte[] key, byte[] iv)
        {
            if (encryption is null)
            {
                throw new ArgumentNullException(nameof(encryption));
            }
            if (encryptedDataBuffer is null)
            {
                throw new ArgumentNullException(nameof(encryptedDataBuffer));
            }
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            var output = new MemoryStream();
            var input  = new MemoryStream(encryptedDataBuffer, index, count);

            encryption.Decrypt(input, key, iv, output);

            return(output.ToArray());
        }
示例#2
0
 public AddUpdatePackageFilesAction(IStoredFileRepository filesRepository, IProjectRepository projectRepository,
                                    IAsymmetricCryptoHandler asymmetricCryptoHandler, ISymmetricEncryption symmetricEncryption)
 {
     _filesRepository         = filesRepository;
     _asymmetricCryptoHandler = asymmetricCryptoHandler;
     _symmetricEncryption     = symmetricEncryption;
     _projectRepository       = projectRepository;
 }
示例#3
0
文件: FileObject.cs 项目: ipbi/sones
        /// <summary>
        /// A constructor used for fast deserializing
        /// </summary>
        /// <param name="myObjectLocation">the location of this object (ObjectPath and ObjectName) of the requested file within the file system</param>
        /// <param name="mySerializedData">A bunch of bytes[] containing the serialized FileObject</param>
        public FileObject(ObjectLocation myObjectLocation, Byte[] mySerializedData, IIntegrityCheck myIntegrityCheckAlgorithm, ISymmetricEncryption myEncryptionAlgorithm)
        {
            if (myObjectLocation == null || myObjectLocation.Length == 0)
                throw new ArgumentNullException("Invalid myObjectLocation!");

            if (mySerializedData == null || mySerializedData.Length == 0)
                throw new ArgumentNullException("mySerializedData must not be null or its length be zero!");

            Deserialize(mySerializedData, myIntegrityCheckAlgorithm, myEncryptionAlgorithm, false);
            _isNew = false;
        }
示例#4
0
 public PaymentService(
     IPaymentsRepository paymentsRepository,
     ISymmetricEncryption symmetricEncryption,
     ICardsRepository cardsRepository,
     IBankGateway bankGateway)
 {
     _paymentsRepository  = paymentsRepository;
     _symmetricEncryption = symmetricEncryption;
     _cardsRepository     = cardsRepository;
     _bankGateway         = bankGateway;
 }
示例#5
0
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="item"></param>
        /// <param name="originalData"></param>
        /// <returns></returns>
        private static object EncryptPropertyValue(ORMappingItem item, object originalData)
        {
            object result = originalData;

            if (originalData != null && originalData != DBNull.Value)
            {
                if (originalData is string == false || (string)originalData != string.Empty)
                {
                    ISymmetricEncryption encryptor = ORMappingItemEncryptionHelper.GetEncryptor(item.EncryptorName);
                    result = encryptor.EncryptString(originalData.ToString()).ToBase16String();
                }
            }

            return(result);
        }
        public void Setup()
        {
            _paymentsRepositoryMock = new Mock <IPaymentsRepository>();
            _cardsRepositoryMock    = new Mock <ICardsRepository>();
            _bankGatewayMock        = new Mock <IBankGateway>();

            var encryptionKeyMock = new Mock <IEncryptionKeys>();

            encryptionKeyMock.Setup(x => x.GetKey()).Returns("SOME_KEY_TO_TEST");

            _symmetricEncryptionMock = new AesEncryption(encryptionKeyMock.Object);

            _paymentService = new PaymentService(
                _paymentsRepositoryMock.Object, _symmetricEncryptionMock,
                _cardsRepositoryMock.Object, _bankGatewayMock.Object);
        }
        /// <summary>
        /// Encrypt data using a key
        /// </summary>
        /// <param name="encryption">The encryption to extend</param>
        /// <param name="data">The data to encrypt</param>
        /// <param name="key">The key to use when encrypting the data</param>
        /// <param name="iv">The initialisation vector to use when encrypting the data</param>
        /// <returns><paramref name="data"/> encrypted</returns>
        /// <exception cref="ArgumentNullException"><paramref name="data"/> or <paramref name="key"/> or <paramref name="iv"/> is <see langword="null"/></exception>
        public static byte[] Encrypt(this ISymmetricEncryption encryption, byte[] data, byte[] key, byte[] iv)
        {
            if (encryption is null)
            {
                throw new ArgumentNullException(nameof(encryption));
            }
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var input  = new MemoryStream(data);
            var output = new MemoryStream();

            encryption.Encrypt(input, key, iv, output);

            return(output.ToArray());
        }
        /// <summary>
        /// Saves the IV's length and IV
        /// </summary>
        /// <param name="encryption">The encryption to extend</param>
        /// <param name="iv">The IV to save</param>
        /// <param name="output">The stream to save to</param>
        public static void WriteIvHeader(this ISymmetricEncryption encryption, byte[] iv, Stream output)
        {
            if (encryption is null)
            {
                throw new ArgumentNullException(nameof(encryption));
            }
            if (iv is null)
            {
                throw new ArgumentNullException(nameof(iv));
            }
            if (output is null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            var ivLength = BitConverter.GetBytes(iv.Length);

            output.Write(ivLength, 0, ivLength.Length);
            output.Write(iv, 0, iv.Length);
        }
        /// <summary>
        /// Reads the IV's length and IV
        /// </summary>
        /// <param name="encryption">The encryption to extend</param>
        /// <param name="input">The stream to read from</param>
        /// <returns>The IV read from <paramref name="input"/></returns>
        public static byte[] ReadIvHeader(this ISymmetricEncryption encryption, Stream input)
        {
            if (encryption is null)
            {
                throw new ArgumentNullException(nameof(encryption));
            }
            if (input is null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            var ivLengthBytes = new byte[4];

            input.Read(ivLengthBytes, 0, ivLengthBytes.Length);

            var ivLength = BitConverter.ToInt32(ivLengthBytes, 0);
            var iv       = new byte[ivLength];

            input.Read(iv);

            return(iv);
        }
示例#10
0
        /// <summary>
        /// 得到加密器
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ISymmetricEncryption GetEncryptor(string name)
        {
            ISymmetricEncryption result = null;

            using (ORMappingContext context = ORMappingContext.GetContext())
            {
                if (name.IsNullOrEmpty())
                {
                    name = "DefaultPropertyEncryptor";
                }

                result = context.ItemEncryptors[name];

                if (result == null)
                {
                    result = new ORMappintItemEncryption(name);
                    context.ItemEncryptors.Add((ORMappintItemEncryption)result);
                }
            }

            return(result);
        }
示例#11
0
        private static object DecryptPropertyValue(ORMappingItem item, object originalData)
        {
            object result = originalData;

            if (originalData is string)
            {
                string stringValue = (string)originalData;

                if (stringValue.IsNotEmpty())
                {
                    try
                    {
                        ISymmetricEncryption encryptor = ORMappingItemEncryptionHelper.GetEncryptor(item.EncryptorName);
                        result = encryptor.DecryptString(stringValue.ToBase16Bytes());
                    }
                    catch (System.FormatException)
                    {
                    }
                }
            }

            return(result);
        }
示例#12
0
        public Exceptional Deserialize(Byte[] mySerializedData, IIntegrityCheck myIntegrityCheckAlgorithm, ISymmetricEncryption myEncryptionAlgorithm, Boolean myIgnoreIntegrityCheckFailures)
        {
            #region Data

            Byte[] IntegrityCheckValue;
            int IntegrityCheckValue_Length;
            Int64 IntegrityCheckValue_Position;
            Byte[] actualIntegrityCheckValue;

            Byte[] EncryptionParameters;
            int EncryptionParameters_Length;

            int DataPadding_Length;
            int AdditionalPadding_Length = 0;

            #endregion

            #region Check if data is larger than the minimum allowed size

            if (mySerializedData == null)
                throw new GraphFSException_InvalidInformationHeader("The information header is invalid!");

            if (mySerializedData.Length < 8)
                throw new GraphFSException_InvalidInformationHeader("The information header is invalid!");

            #endregion

            try
            {

                #region Init reader

                var _SerializationReader = new SerializationReader(mySerializedData);

                #endregion

                #region Read HeaderVersion

                var _NewHeaderVersion = _SerializationReader.ReadByte();

                #endregion

                #region Read Length of the Integrity Check Value

                // Multiply the value of the first byte with 8
                IntegrityCheckValue_Length = _SerializationReader.ReadByte() << 3;

                if (IntegrityCheckValue_Length > mySerializedData.Length - HeaderLength)
                    throw new GraphFSException_InvalidIntegrityCheckLengthField("The length of the integrity check value is invalid!");

                // HACK: Remeber that a IntegrityCheckValue of 0 will circumvent the whole integrity checking!
                if (myIntegrityCheckAlgorithm != null)
                    if ((IntegrityCheckValue_Length > 0) && (IntegrityCheckValue_Length != myIntegrityCheckAlgorithm.HashSize))
                        throw new GraphFSException_InvalidIntegrityCheckLengthField("The length of the integrity check value is " + IntegrityCheckValue_Length + ", but " + myIntegrityCheckAlgorithm.HashSize + " was expected!");

                #endregion

                #region Read Length of the Encryption Parameters

                // Multiply the value of the second byte with 8
                EncryptionParameters_Length = _SerializationReader.ReadByte() << 3;

                if (EncryptionParameters_Length > mySerializedData.Length - HeaderLength - IntegrityCheckValue_Length)
                    throw new GraphFSException_InvalidEncryptionParametersLengthField("The length of the encryption parameters is invalid!");

                #endregion

                #region Read Padding lengths

                DataPadding_Length = (Int32)_SerializationReader.ReadByte();
                AdditionalPadding_Length = (Int32)(256 * _SerializationReader.ReadByte() + _SerializationReader.ReadByte()) << 3;

                if ((HeaderLength + IntegrityCheckValue_Length + EncryptionParameters_Length + AdditionalPadding_Length) >= mySerializedData.Length)
                    throw new GraphFSException_InvalidAdditionalPaddingLengthField("The length of the additional padding is invalid!");

                _SerializationReader.ReadBytesDirect(2);  // Read reserved bytes

                #endregion

                #region Read Integrity Check Value and Encryption Parameters

                IntegrityCheckValue_Position = _SerializationReader.BaseStream.Position;

                if (IntegrityCheckValue_Length > 0)
                    IntegrityCheckValue = _SerializationReader.ReadBytesDirect(IntegrityCheckValue_Length);

                if (EncryptionParameters_Length > 0)
                    EncryptionParameters = _SerializationReader.ReadBytesDirect(EncryptionParameters_Length);

                #endregion

                #region Verify the integrity of the data

                if (myIntegrityCheckAlgorithm != null && IntegrityCheckValue_Length > 0)
                {

                    // Save the read IntegrityCheckValue
                    IntegrityCheckValue = new Byte[IntegrityCheckValue_Length];
                    Array.Copy(mySerializedData, IntegrityCheckValue_Position, IntegrityCheckValue, 0, IntegrityCheckValue_Length);

                    // Zero the IntegrityCheckValue within the serialized data
                    Byte[] AllZeros = new Byte[IntegrityCheckValue_Length];
                    Array.Copy(AllZeros, 0, mySerializedData, IntegrityCheckValue_Position, IntegrityCheckValue_Length);

                    // Calculate the actual IntegrityCheckValue
                    actualIntegrityCheckValue = myIntegrityCheckAlgorithm.GetHashValueAsByteArray(mySerializedData);

                    // Compare read and actual IntegrityCheckValue
                    if (IntegrityCheckValue.CompareByteArray(actualIntegrityCheckValue) != 0 && myIgnoreIntegrityCheckFailures == false)
                        throw new GraphFSException_IntegrityCheckFailed(String.Concat("The IntegrityCheck failed as ", actualIntegrityCheckValue.ToHexString(), " is not equal to the expected ", IntegrityCheckValue.ToHexString()));

                }

                #endregion

                #region Decrypt the remaining data

                //EncryptedData_Length      = (UInt64) (mySerializedData.Length - (HeaderLength + IntegrityCheckValue_Length + EncryptionParameters_Length + AdditionalPadding_Length));
                //EncryptedData             = new Byte[EncryptedData_Length];
                //Array.Copy(mySerializedData, HeaderLength + IntegrityCheckValue_Length + EncryptionParameters_Length, EncryptedData, 0, (Int64) EncryptedData_Length);

                //#endregion

                //#region Decrypt Data

                // Decrypt Data, sooon...!

                //if ( (UInt64) DataPadding_Length >= EncryptedData_Length)
                //    throw new GraphFSException_InvalidDataPaddingLengthField("The length of the data padding is invalid!");

                //DecryptedData = new Byte[EncryptedData_Length - (UInt64) DataPadding_Length];
                //Array.Copy(EncryptedData, 0, DecryptedData, 0, (Int64) (EncryptedData_Length - (UInt64) DataPadding_Length));

                #endregion

                #region Deserialize Inner Object

                _StructureVersion = BitConverter.ToUInt16(_SerializationReader.ReadBytesDirect(2), 0);
                ObjectUUID = new ObjectUUID();
                ObjectUUID.Deserialize(ref _SerializationReader); // n or at least 16 Bytes

                Deserialize(ref _SerializationReader);

                #endregion

            }

            catch (GraphFSException_IntegrityCheckFailed e)
            {
                throw new GraphFSException_IntegrityCheckFailed("The AGraphStructure could not be deserialized as its integrity is corrupted!\n\n" + e);
            }

            catch (Exception e)
            {
                throw new GraphFSException_AGraphStructureCouldNotBeDeserialized("The AGraphStructure could not be deserialized!\n\n" + e);
            }

            _SerializedAGraphStructure = mySerializedData;

            return new Exceptional();
        }
 public EncryptionTest()
 {
     _symmetricEncryption = serviceProvider.GetRequiredService <ISymmetricEncryption>();
 }
 public SymmetricEncryptionController(ISymmetricEncryption symmetricEncryption)
 {
     _symmetricEncryption = symmetricEncryption;
 }
示例#15
0
文件: INode.cs 项目: TheByte/sones
 /// <summary>
 /// A constructor of the INode used for fast deserializing
 /// </summary>
 /// <param name="mySerializedData">A bunch of bytes[] containing the serialized INode</param>
 public INode(Byte[] mySerializedData, IIntegrityCheck myIntegrityCheckAlgorithm, ISymmetricEncryption myEncryptionAlgorithm)
 {
     Deserialize(mySerializedData, myIntegrityCheckAlgorithm, myEncryptionAlgorithm);
     _isNew = false;
 }
示例#16
0
 /// <summary>
 /// This will call the normal Deserialize method and afterwards it will
 /// copy the content of all AGraphStructure and AAFSObject properties
 /// to the clone.
 /// </summary>
 /// <param name="mySerializedData">The fastserialized object as an array of bytes</param>
 /// <param name="myAAFSObject">The AAFSObject to copy the content from</param>
 public void Deserialize(Byte[] mySerializedData, IIntegrityCheck myIntegrityCheckAlgorithm, ISymmetricEncryption myEncryptionAlgorithm, AFSObject myAAFSObject)
 {
     Deserialize(mySerializedData, myIntegrityCheckAlgorithm, myEncryptionAlgorithm, false);
     CloneObjectOntology(myAAFSObject);
 }
示例#17
0
        /// <summary>
        /// This will serialize the whole AFSObject including the common header of an
        /// AAFSObject and the actual AFSObject
        /// </summary>
        /// <param name="myIntegrityCheckAlgorithm"></param>
        /// <param name="myEncryptionAlgorithm"></param>
        /// <param name="myCacheSerializeData"></param>
        /// <returns></returns>
        public Byte[] Serialize(IIntegrityCheck myIntegrityCheckAlgorithm, ISymmetricEncryption myEncryptionAlgorithm, Boolean myCacheSerializeData)
        {
            #region Data

            Int32 IntegrityCheckValue_Length = 0;
            Byte[] IntegrityCheckValue = null;
            Int64 IntegrityCheckValue_Position = 0;

            Int32 EncryptionParameters_Length = 0;
            Byte DataPadding_Length = 0;
            Int32 AdditionalPadding_Length = 0;
            Byte[] _TmpSerializedAGraphStructure = null;

            #endregion

            try
            {

                #region Init SerializationWriter

                SerializationWriter writer = new SerializationWriter();

                #endregion

                #region Pad the length of the EncryptionParameters

                EncryptionParameters = Encoding.Default.GetBytes("-HIGHSECUREDATA-");
                EncryptionParameters_Length = sones.Lib.BufferHelper.AlignBufferLength(EncryptionParameters.Length, 8);

                #endregion

                #region Serialize AAFSObjectHeader

                Byte[] AAFSObjectHeader = new Byte[HeaderLength];

                AAFSObjectHeader[0] = HeaderVersion;

                if (myIntegrityCheckAlgorithm != null)
                    IntegrityCheckValue_Length = myIntegrityCheckAlgorithm.HashSize;

                if (IntegrityCheckValue_Length % 8 == 0)
                    AAFSObjectHeader[1] = (Byte)(IntegrityCheckValue_Length / 8);
                else AAFSObjectHeader[1] = (Byte)((IntegrityCheckValue_Length / 8) + 1);

                if (EncryptionParameters_Length % 8 == 0)
                    AAFSObjectHeader[2] = (Byte)(EncryptionParameters_Length / 8);
                else AAFSObjectHeader[2] = (Byte)((EncryptionParameters_Length / 8) + 1);

                AAFSObjectHeader[3] = (Byte)(DataPadding_Length);
                AAFSObjectHeader[4] = (Byte)(AdditionalPadding_Length / 256);
                AAFSObjectHeader[5] = (Byte)(AdditionalPadding_Length % 256);
                AAFSObjectHeader[6] = 0x00;
                AAFSObjectHeader[7] = 0x00;

                writer.WriteBytesDirect(AAFSObjectHeader);                      // 8 Bytes
                IntegrityCheckValue_Position = writer.BaseStream.Position;
                writer.WriteBytesDirect(new Byte[IntegrityCheckValue_Length]);      // n or at least 16 Bytes
                writer.WriteBytesDirect(EncryptionParameters);                      // m Bytes

                #endregion

                #region Serialize StructureVersion, ObjectUUID and the Inner Object

                writer.WriteBytesDirect(BitConverter.GetBytes(_StructureVersion));
                ObjectUUID.Serialize(ref writer);        // n or at least 16 Bytes

                Serialize(ref writer);

                #endregion

                _TmpSerializedAGraphStructure = writer.ToArray();

                #region Encrypt
                #endregion

                #region Add IntegrityCheck

                if (myIntegrityCheckAlgorithm != null && IntegrityCheckValue_Length > 0)
                {

                    IntegrityCheckValue = myIntegrityCheckAlgorithm.GetHashValueAsByteArray(_TmpSerializedAGraphStructure);

                    // If the returned array is shorter than expected => pad with 0x00
                    // And if it is longer just copy the number of expected bytes
                    Array.Copy(IntegrityCheckValue, 0, _TmpSerializedAGraphStructure, IntegrityCheckValue_Position, IntegrityCheckValue.Length);

                }

                #endregion

                isDirty = false;

                if (myCacheSerializeData)
                    _SerializedAGraphStructure = _TmpSerializedAGraphStructure;

                return _TmpSerializedAGraphStructure;

            }

            catch (SerializationException e)
            {
                throw new SerializationException(e.Message, e);
            }
        }
示例#18
0
 public CreateProjectUseCase(IAsymmetricKeyParametersFactory asymmetricKeyFactory, IProjectRepository repository, ISymmetricEncryption encryption)
 {
     _asymmetricKeyFactory = asymmetricKeyFactory;
     _repository           = repository;
     _encryption           = encryption;
 }