示例#1
0
        public byte[] Decrypt( byte[] cipherTextBytes )
        {
            DataBlob plainTextBlob = new DataBlob ( );
            DataBlob cipherTextBlob = new DataBlob ( cipherTextBytes );
            DataBlob entropyBlob = new DataBlob ( entropy );

            description = "";

            try {
                CryptProtectFlags flags = CryptProtectFlags.UIForbidden;

                if ( !CryptUnprotectData ( ref cipherTextBlob, ref description, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, flags, ref plainTextBlob ) )
                    throw new COMException ( "CryptUnprotectData failed. ", Marshal.GetLastWin32Error ( ) );

                byte[] plainTextBytes = new byte[ plainTextBlob.cbData ];

                Marshal.Copy ( plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData );
                return plainTextBytes;
            } catch ( Exception ex ) {
                throw new Exception ( "DPAPI was unable to decrypt data. " + ex.Message );
            } finally {
                if ( plainTextBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( plainTextBlob.pbData );

                if ( cipherTextBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( cipherTextBlob.pbData );

                if ( entropyBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( entropyBlob.pbData );
            }
        }
示例#2
0
 public static extern bool CryptUnprotectData(
     ref DataBlob dataInPointer,
     String dataDescr,
     ref DataBlob optionalEntropyPointer,
     IntPtr reservedVoidPointer,
     ref CryptProtectPromptStruct promptStructPointer,
     int flags,
     ref DataBlob dataOutPointer);
示例#3
0
        public static Bitmap channelsToBitmap(DataBlob data) {
            if (data == null || data.channels == null) {
                return null;
            }

            Bitmap bmp = new Bitmap(data.imageWidth, data.imageHeight, PixelFormat.Format24bppRgb);

            BitmapData bmpData = bmp.LockBits(
                                new Rectangle(0, 0, bmp.Width, bmp.Height),
                                ImageLockMode.ReadWrite,
                                bmp.PixelFormat);

            IntPtr ptr = bmpData.Scan0;


            //copy bytes
            int nBytes = Math.Abs(bmpData.Stride) * bmp.Height;
            byte[] rgbValues = new byte[nBytes];

            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, nBytes);
            int pixel;
            int iY, iCrb;
            int channelYStride = data.channelWidth;
            //TODO: don't assume padded. :P
            int channelCRBStride = Subsample.getCbCrStride(data);

            for (int y = 0; y < data.imageHeight; y++) {
                pixel = y * bmpData.Stride;
                iY = y * channelYStride;
                iCrb = (data.samplingMode == DataBlob.Samples.s420 ? y / 2 : y) * channelCRBStride;
                for (int x = 0; x < data.imageWidth; x++) {
                    rgbValues[pixel + 2] = data.channels[0][iY];
                    rgbValues[pixel + 1] = data.channels[1][iCrb];
                    rgbValues[pixel] = data.channels[2][iCrb];
                    pixel += 3;
                    iY++;

                    if (data.samplingMode == DataBlob.Samples.s420 || data.samplingMode == DataBlob.Samples.s422) {
                        if (x % 2 == 1) {
                            iCrb++;
                        }
                    } else if (data.samplingMode == DataBlob.Samples.s444) {
                        iCrb++;
                    } else if (data.samplingMode == DataBlob.Samples.s411) {
                        if (x % 4 == 3) {
                            iCrb++;
                        }
                    }

                }
            }
            
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, nBytes);

            bmp.UnlockBits(bmpData);

            return bmp;
        }
示例#4
0
文件: Node.cs 项目: JoePelz/NodeShop
 protected virtual void init() {
     properties = new Dictionary<string, Property>();
     state = new DataBlob();
     PropertyString p = new PropertyString("default", "Name of the control");
     p.eValueChanged += (s, e) => fireOutputChanged(e);
     properties.Add("name", p);
     createProperties();
     id = generateID();
 }
示例#5
0
        protected override void clean() {
            base.clean();

            state = null;
            vState = null;

            Address upstreamNow = properties["inChannelsNow"].input;
            if (upstreamNow == null) {
                return;
            }
            Address upstreamPast = properties["inChannelsPast"].input;
            if (upstreamPast == null) {
                return;
            }

            DataBlob stateNow = upstreamNow.node.getData(upstreamNow.port);
            if (stateNow == null) {
                return;
            }
            DataBlob statePast = upstreamPast.node.getData(upstreamPast.port);
            if (statePast == null) {
                return;
            }

            if (stateNow.type != DataBlob.Type.Channels || stateNow.channels == null) {
                return;
            }
            if (statePast.type != DataBlob.Type.Channels || statePast.channels == null) {
                return;
            }

            //check resolutions match
            if (stateNow.channels[0].Length != statePast.channels[0].Length
                || stateNow.channels[1].Length != statePast.channels[1].Length
                || stateNow.channels[2].Length != statePast.channels[2].Length) {
                return;
            }

            state = stateNow.clone();
            vState = stateNow.clone();

            //create copy of channels for local use.
            byte[][] diffChannels = new byte[state.channels.Length][];
            diffChannels[0] = new byte[state.channels[0].Length];
            diffChannels[1] = new byte[state.channels[1].Length];
            diffChannels[2] = new byte[state.channels[2].Length];
            byte[][] vectors = new byte[3][];
            state.channels = diffChannels;
            vState.channels = vectors;
            state.bmp = null;
            vState.bmp = null;
            state.type = DataBlob.Type.Channels;
            vState.type = DataBlob.Type.Vectors;

            calcMoVec(statePast.channels, stateNow.channels);
        }
 private static extern bool CryptProtectData
 (
     ref DataBlob pDataIn,
     String szDataDescr,
     ref DataBlob pOptionalEntropy,
     IntPtr pvReserved,
     ref CryptprotectPromptstruct
     pPromptStruct,
     int dwFlags,
     ref DataBlob pDataOut);
示例#7
0
        protected static void writeChannels(BinaryWriter writer, DataBlob ch)
        {
            Chunker c = new Chunker(8, ch.channelWidth, ch.channelHeight, ch.channelWidth, 1);

            writeChannel(writer, ch.channels[0], c);
            Size s = Subsample.deduceCbCrSize(ch);

            c = new Chunker(8, s.Width, s.Height, s.Width, 1);
            writeChannel(writer, ch.channels[1], c);
            writeChannel(writer, ch.channels[2], c);
        }
示例#8
0
        private void readChannels(BinaryReader reader, DataBlob ch)
        {
            Chunker c = new Chunker(8, ch.channelWidth, ch.channelHeight, ch.channelWidth, 1);

            readChannel(reader, ch.channels[0], c);
            Size s = Subsample.deduceCbCrSize(ch);

            c = new Chunker(8, s.Width, s.Height, s.Width, 1);
            readChannel(reader, ch.channels[1], c);
            readChannel(reader, ch.channels[2], c);
        }
示例#9
0
        protected virtual void init()
        {
            properties = new Dictionary <string, Property>();
            state      = new DataBlob();
            PropertyString p = new PropertyString("default", "Name of the control");

            p.eValueChanged += (s, e) => fireOutputChanged(e);
            properties.Add("name", p);
            createProperties();
            id = generateID();
        }
示例#10
0
        private DataBlob readHeader(BinaryReader reader)
        {
            DataBlob metadata = new DataBlob();

            metadata.imageWidth      = reader.ReadUInt16();
            metadata.imageHeight     = reader.ReadUInt16();
            metadata.channelWidth    = reader.ReadUInt16();
            metadata.channelHeight   = reader.ReadUInt16();
            metadata.quantizeQuality = reader.ReadByte();
            metadata.samplingMode    = (DataBlob.Samples)reader.ReadByte();
            return(metadata);
        }
示例#11
0
 public static Size deduceCbCrSize(DataBlob data) {
     Size size = getCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);
     if (data.channels[1].Length == size.Width * size.Height) {
         return size;
     }
     size = getPaddedCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);
     if (data.channels[1].Length == size.Width * size.Height) {
         return size;
     }
     size.Width = 0;
     size.Height = 0;
     return size;
 }
示例#12
0
文件: Merge.cs 项目: JoePelz/NodeShop
        protected override void clean()
        {
            base.clean();

            Address upstreamA = properties["inColorA"].input;

            if (upstreamA == null)
            {
                return;
            }
            Address upstreamB = properties["inColorB"].input;

            if (upstreamB == null)
            {
                return;
            }

            state = upstreamA.node.getData(upstreamA.port);
            if (state == null)
            {
                return;
            }
            DataBlob stateB = upstreamB.node.getData(upstreamB.port);

            if (stateB == null)
            {
                return;
            }

            state = state.clone();

            if (state.type != DataBlob.Type.Image || state.bmp == null)
            {
                state = null;
                return;
            }
            if (stateB.type != DataBlob.Type.Image || stateB.bmp == null)
            {
                stateB = null;
                return;
            }

            //check resolutions match
            if (state.imageWidth != stateB.imageWidth || state.imageHeight != stateB.imageHeight)
            {
                return;
            }

            state.bmp = state.bmp.Clone(new Rectangle(0, 0, state.bmp.Width, state.bmp.Height), state.bmp.PixelFormat);
            merge(stateB.bmp);
        }
示例#13
0
        protected override void clean() {
            base.clean();
            state = null;

            Address upstreamDiff = properties["inChannels"].input;
            if (upstreamDiff == null) {
                return;
            }
            Address upstreamPast = properties["inChannelsPast"].input;
            if (upstreamPast == null) {
                return;
            }
            Address upstreamVectors = properties["inVectors"].input;
            if (upstreamVectors == null) {
                return;
            }


            DataBlob stateDiff = upstreamDiff.node.getData(upstreamDiff.port);
            if (stateDiff == null) {
                return;
            }
            DataBlob statePast = upstreamPast.node.getData(upstreamPast.port);
            if (statePast == null) {
                return;
            }

            stateVectors = upstreamVectors.node.getData(upstreamVectors.port);
            if (stateVectors == null) {
                return;
            }


            if (stateDiff.type != DataBlob.Type.Channels || stateDiff.channels == null) 
                return;
            if (statePast.type != DataBlob.Type.Channels || statePast.channels == null) 
                return;
            if (stateVectors.type != DataBlob.Type.Vectors || stateVectors.channels == null)
                return;

            state = stateDiff.clone();
            byte[][] newChannels = new byte[state.channels.Length][];
            newChannels[0] = new byte[state.channels[0].Length];
            newChannels[1] = new byte[state.channels[1].Length];
            newChannels[2] = new byte[state.channels[2].Length];
            state.channels = newChannels;
            state.bmp = null;

            reassemble(statePast.channels, stateDiff.channels, stateVectors.channels);
        }
示例#14
0
        /// <summary>
        /// Encrypts the specified data.
        /// </summary>
        /// <param name="plainTextBytes">A byte array containing data to protect.</param>
        /// <returns>A byte array representing the encrypted data.</returns>
        public byte[] Encrypt(byte[] plainTextBytes)
        {
            var description = string.Empty;

            var plainTextBlob  = new DataBlob(plainTextBytes);
            var cipherTextBlob = new DataBlob(null);
            var entropyBlob    = new DataBlob(Key.Bytes);

            try
            {
                var flags = CryptProtect.UiForbidden;

                if (KeyType == DataProtectionKeyType.MachineKey)
                {
                    flags |= CryptProtect.LocalMachine;
                }

                CryptProtectData(
                    ref plainTextBlob,
                    description,
                    ref entropyBlob,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    flags,
                    ref cipherTextBlob);

                var cipherTextBytes = new byte[cipherTextBlob.DataLength];

                Marshal.Copy(cipherTextBlob.DataBuffer, cipherTextBytes, 0, cipherTextBlob.DataLength);

                return(cipherTextBytes);
            }
            finally
            {
                if (plainTextBlob.DataBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(plainTextBlob.DataBuffer);
                }

                if (cipherTextBlob.DataBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(cipherTextBlob.DataBuffer);
                }

                if (entropyBlob.DataBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(entropyBlob.DataBuffer);
                }
            }
        }
示例#15
0
 private static void InitBlob(byte[] data, ref DataBlob blob)
 {
     if (data == null)
     {
         data = new byte[0];
     }
     blob.pbData = Marshal.AllocHGlobal(data.Length);
     if (blob.pbData == IntPtr.Zero)
     {
         throw new Exception("Unable to allocate data buffer for BLOB structure.");
     }
     blob.cbData = data.Length;
     Marshal.Copy(data, 0, blob.pbData, data.Length);
 }
示例#16
0
        protected override void clean() {
            base.clean();
            //load image from path, if it exists
            state = new DataBlob();

            try {
                state.bmp = new Bitmap(filepath);
                state.bmp = state.bmp.Clone(new Rectangle(0, 0, state.bmp.Width, state.bmp.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                state.imageWidth = state.bmp.Width;
                state.imageHeight = state.bmp.Height;
            } catch (Exception) {
                state = null;
            }
        }
示例#17
0
        public static async Task <DataReference> TransferBinaryData(IDataApiClient dataApiClient, Stream data, string id = null)
        {
            if (id == null)
            {
                id = IdGenerator.FromGuid(); // We cannot be sure that the stream is reversible and hence cannot use it for calculating an ID
            }
            var dataType = nameof(DataBlob);
            var dataBlob = new DataBlob(id, new byte[0]);

            id = await dataApiClient.CreateSubmission(dataBlob, x => x.Data, id);

            await dataApiClient.TransferSubmissionData(dataType, id, data);

            return(new DataReference(dataType, id));
        }
示例#18
0
        protected override void clean()
        {
            base.clean();
            //load image from path, if it exists
            state = new DataBlob();

            try {
                state.bmp         = new Bitmap(filepath);
                state.bmp         = state.bmp.Clone(new Rectangle(0, 0, state.bmp.Width, state.bmp.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                state.imageWidth  = state.bmp.Width;
                state.imageHeight = state.bmp.Height;
            } catch (Exception) {
                state = null;
            }
        }
示例#19
0
        public byte[] Encrypt(byte[] plainTextBytes)
        {
            if (description == null)
            {
                description = "";
            }

            DataBlob plainTextBlob  = new DataBlob(plainTextBytes);
            DataBlob cipherTextBlob = new DataBlob( );
            DataBlob entropyBlob    = new DataBlob(entropy);

            try {
                CryptProtectFlags flags = CryptProtectFlags.UIForbidden;

                if (keyType == DataProtectionKeyType.MachineKey)
                {
                    flags |= CryptProtectFlags.LocalMachine;
                }

                if (!CryptProtectData(ref plainTextBlob, description, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, flags, ref cipherTextBlob))
                {
                    throw new COMException("CryptProtectData failed." + Marshal.GetLastWin32Error( ));
                }

                byte[] cipherTextBytes = new byte[cipherTextBlob.cbData];

                Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData);

                return(cipherTextBytes);
            } catch (Exception ex) {
                throw new Exception("DPAPI was unable to encrypt data. " + ex.Message);
            } finally {
                if (plainTextBlob.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(plainTextBlob.pbData);
                }

                if (cipherTextBlob.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(cipherTextBlob.pbData);
                }

                if (entropyBlob.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(entropyBlob.pbData);
                }
            }
        }
示例#20
0
        public static int getCbCrStride(DataBlob data)
        {
            Size unpadded = getCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);

            if (data.channels[1].Length == unpadded.Width * unpadded.Height)
            {
                return(unpadded.Width);
            }
            Size padded = getPaddedCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);

            if (data.channels[1].Length == padded.Width * padded.Height)
            {
                return(padded.Width);
            }
            return(-1);
        }
示例#21
0
        private bool validateInput()
        {
            Address upC1 = properties["inChannels"].input;

            if (upC1 == null)
            {
                return(false);
            }
            Address upC2 = properties["inChannels2"].input;

            if (upC2 == null)
            {
                return(false);
            }
            Address upV2 = properties["inVectors2"].input;

            if (upV2 == null)
            {
                return(false);
            }

            inC1 = upC1.node.getData(upC1.port);
            inC2 = upC2.node.getData(upC2.port);
            inV2 = upV2.node.getData(upV2.port);

            if (inC1 == null || inC1.type != DataBlob.Type.Channels || inC1.channels == null)
            {
                return(false);
            }
            if (inC2 == null || inC2.type != DataBlob.Type.Channels || inC2.channels == null)
            {
                return(false);
            }
            if (inV2 == null || inV2.type != DataBlob.Type.Vectors || inV2.channels == null)
            {
                return(false);
            }

            if (inC1.channels[0].Length != inC2.channels[0].Length ||
                inC1.channels[1].Length != inC2.channels[1].Length ||
                inC1.channels[2].Length != inC2.channels[2].Length)
            {
                return(false);
            }

            return(true);
        }
示例#22
0
        private void setupBlobs(DataBlob metadata)
        {
            C1      = new DataBlob();
            C2      = new DataBlob();
            V2      = new DataBlob();
            C1.type = C2.type = DataBlob.Type.Channels;
            V2.type = DataBlob.Type.Vectors;

            //import metadata onto channels
            C1.imageWidth      = C2.imageWidth = metadata.imageWidth;
            C1.imageHeight     = C2.imageHeight = metadata.imageHeight;
            C1.channelWidth    = C2.channelWidth = metadata.channelWidth;
            C1.channelHeight   = C2.channelHeight = metadata.channelHeight;
            C1.quantizeQuality = C2.quantizeQuality = metadata.quantizeQuality;
            C1.samplingMode    = C2.samplingMode = metadata.samplingMode;

            Chunker c = new Chunker(8, metadata.channelWidth, metadata.channelHeight, metadata.channelWidth, 1);

            V2.imageWidth      = metadata.imageWidth;
            V2.imageHeight     = metadata.imageHeight;
            V2.channelWidth    = c.getChunksWide();
            V2.channelHeight   = c.getChunksHigh();
            V2.quantizeQuality = metadata.quantizeQuality;
            V2.samplingMode    = metadata.samplingMode;

            //Allocate space for incoming data
            C1.channels = new byte[3][];
            C2.channels = new byte[3][];
            V2.channels = new byte[3][];

            int  cMajor    = C1.channelWidth * C1.channelHeight;
            Size sizeMinor = Subsample.getPaddedCbCrSize(new Size(C1.channelWidth, C1.channelHeight), C1.samplingMode);
            int  cMinor    = sizeMinor.Width * sizeMinor.Height;

            C1.channels[0] = new byte[cMajor];
            C2.channels[0] = new byte[cMajor];
            C1.channels[1] = new byte[cMinor];
            C2.channels[1] = new byte[cMinor];
            C1.channels[2] = new byte[cMinor];
            C2.channels[2] = new byte[cMinor];
            cMajor         = V2.channelWidth * V2.channelHeight;
            sizeMinor      = Subsample.getCbCrSize(new Size(V2.channelWidth, V2.channelHeight), V2.samplingMode);
            cMinor         = sizeMinor.Width * sizeMinor.Height;
            V2.channels[0] = new byte[cMajor];
            V2.channels[1] = new byte[cMinor];
            V2.channels[2] = new byte[cMinor];
        }
示例#23
0
 public static Size getCbCrSize(Size ySize, DataBlob.Samples mode) {
     switch (mode) {
         case DataBlob.Samples.s444:
             break;
         case DataBlob.Samples.s422:
             ySize.Width = (ySize.Width + 1) / 2;
             break;
         case DataBlob.Samples.s420:
             ySize.Width = (ySize.Width + 1) / 2;
             ySize.Height = (ySize.Height + 1) / 2;
             break;
         case DataBlob.Samples.s411:
             ySize.Width = (ySize.Width + 3) / 4;
             break;
     }
     return ySize;
 }
示例#24
0
        public static Size deduceCbCrSize(DataBlob data)
        {
            Size size = getCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);

            if (data.channels[1].Length == size.Width * size.Height)
            {
                return(size);
            }
            size = getPaddedCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);
            if (data.channels[1].Length == size.Width * size.Height)
            {
                return(size);
            }
            size.Width  = 0;
            size.Height = 0;
            return(size);
        }
示例#25
0
        //------------------------------- helpers --------------------------
        void HandleBlobData(DataBlob packet)
        {
            //int sizeOfBlobs = accumulator.GetSizeOfAllBlobs();
            if (accumulator.Add(packet as DataBlob) == true)
            {
                //int sizeOfBlobs = accumulator.GetSizeOfAllBlobs();
                int    numBlobs = accumulator.BlobCount;
                byte[] bytes    = accumulator.ConvertDatablobsIntoRawData();

                int len = bytes.Length;
                OnImageReceived?.Invoke(bytes, bytes.Length);

                accumulator.Clear();
                Console.Write("Blobs received in acc {0}\n", numBlobs);
                Console.Write("Bytes received in blob {0}\n", len);
            }
            return;
        }
示例#26
0
            public bool Add(DataBlob blob)
            {
                Debug.Assert(accumulator.Count < blob.totalRawDataPacketCount);
                if (accumulator.Count > 1)
                {
                    //Debug.Assert(blob.packetIndex != accumulator[accumulator.Count - 1].packetIndex);
                    if (blob.packetIndex == accumulator[accumulator.Count - 1].packetIndex)
                    {
                        return(false);
                    }
                }
                accumulator.Add(blob);
                if (accumulator.Count == blob.totalRawDataPacketCount)
                {
                    return(true);
                }

                return(false);
            }
示例#27
0
        /// <summary>
        /// Decrypts the specified data.
        /// </summary>
        /// <param name="cipherTextBytes">A byte array containing the encrypted data.</param>
        /// <returns>A byte array containing the decrypted data.</returns>
        public byte[] Decrypt(byte[] cipherTextBytes)
        {
            var plainTextBlob  = default(DataBlob);
            var cipherTextBlob = new DataBlob(cipherTextBytes);
            var entropyBlob    = new DataBlob(Key.Bytes);

            var description = string.Empty;

            try
            {
                CryptUnprotectData(
                    ref cipherTextBlob,
                    ref description,
                    ref entropyBlob,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    CryptProtect.UiForbidden,
                    ref plainTextBlob);

                var plainTextBytes = new byte[plainTextBlob.DataLength];

                Marshal.Copy(plainTextBlob.DataBuffer, plainTextBytes, 0, plainTextBlob.DataLength);
                return(plainTextBytes);
            }
            finally
            {
                if (plainTextBlob.DataBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(plainTextBlob.DataBuffer);
                }

                if (cipherTextBlob.DataBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(cipherTextBlob.DataBuffer);
                }

                if (entropyBlob.DataBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(entropyBlob.DataBuffer);
                }
            }
        }
示例#28
0
        public static async Task <DataReference> TransferBinaryData(IDataApiClient dataApiClient, byte[] data, string id = null)
        {
            if (id == null)
            {
                id = IdGenerator.Sha1HashFromByteArray(data);
            }
            var dataType = nameof(DataBlob);

            if (await dataApiClient.ExistsAsync <DataBlob>(id))
            {
                return(new DataReference(dataType, id));
            }
            var dataBlob = new DataBlob(id, new byte[0]);

            id = await dataApiClient.CreateSubmission(dataBlob, x => x.Data, id);

            await dataApiClient.TransferSubmissionData(dataType, id, data);

            return(new DataReference(dataType, id));
        }
示例#29
0
        //------------------------------- helpers --------------------------
        void HandleBlobData(DataBlob packet)
        {
            //int sizeOfBlobs = accumulator.GetSizeOfAllBlobs();
            if (accumulator.Add(packet as DataBlob) == true)
            {
                //int sizeOfBlobs = accumulator.GetSizeOfAllBlobs();
                int    numBlobs = accumulator.BlobCount;
                byte[] bytes    = accumulator.ConvertDatablobsIntoRawData();

                int len = bytes.Length;
                OnImageReceived?.Invoke(bytes, bytes.Length);

                accumulator.Clear();
                Console.Write("Blobs received in acc {0}\n", numBlobs);
                Console.Write("Bytes received in blob {0}\n", len);
                var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
                Console.WriteLine("request roundtrip total time {0} ms", Timestamp - startTimeMilliseconds);
            }
            return;
        }
示例#30
0
        public static async Task <DataReference> TransferFile(IDataApiClient dataApiClient, string filePath, string id = null)
        {
            if (id == null)
            {
                id = IdGenerator.Sha1HashFromFile(filePath);
            }
            var dataType = nameof(DataBlob);

            if (await dataApiClient.ExistsAsync <DataBlob>(id))
            {
                return(new DataReference(dataType, id));
            }
            var dataBlob = new DataBlob(id, new byte[0], Path.GetFileName(filePath));

            id = await dataApiClient.CreateSubmission(dataBlob, x => x.Data, id);

            using (var fileStream = File.OpenRead(filePath))
                await dataApiClient.TransferSubmissionData(dataType, id, fileStream);
            return(new DataReference(dataType, id));
        }
示例#31
0
        private async Task <GenericDataContainer> FixMissingMetadata(string dataType, string id, byte[] binaryData)
        {
            // Assumption: Metadata doesn't exist

            var      blob = binaryDataStorage.GetBlob(dataType, id);
            DateTime createdTimeUtc;
            DateTime submissionTimeUtc;

            if (await blob.ExistsAsync())
            {
                createdTimeUtc    = blob.CreatedTimestampUtc;
                submissionTimeUtc = blob.LastModifiedTimestampUtc;
            }
            else
            {
                var utcNow = DateTime.UtcNow;
                createdTimeUtc    = utcNow;
                submissionTimeUtc = utcNow;
            }
            IId obj;

            switch (dataType)
            {
            case nameof(DataBlob):
                obj = new DataBlob(id, new byte[0]);
                break;

            case nameof(Image):
                var imageFormat    = ImageFormatDetector.Detect(binaryData);
                var imageExtension = imageFormat != ImageFormatDetector.ImageFormat.Unknown ? imageFormat.GetFileExtension() : ".bin";
                obj = new Image(id, new byte[0], imageExtension);
                break;

            default:
                throw new NotSupportedException($"Cannot fix missing metadata for ID '{id}' of data type '{dataType}'");
            }
            var container = new GenericDataContainer("unknown", createdTimeUtc, "unknown", submissionTimeUtc, ApiVersion.Current, obj);
            await metadataStorage.StoreAsync(dataType, container, false);

            return(container);
        }
示例#32
0
        public byte[] Decrypt(byte[] cipherTextBytes)
        {
            DataBlob plainTextBlob  = new DataBlob( );
            DataBlob cipherTextBlob = new DataBlob(cipherTextBytes);
            DataBlob entropyBlob    = new DataBlob(entropy);

            description = "";

            try {
                CryptProtectFlags flags = CryptProtectFlags.UIForbidden;

                if (!CryptUnprotectData(ref cipherTextBlob, ref description, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, flags, ref plainTextBlob))
                {
                    throw new COMException("CryptUnprotectData failed. ", Marshal.GetLastWin32Error( ));
                }

                byte[] plainTextBytes = new byte[plainTextBlob.cbData];

                Marshal.Copy(plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData);
                return(plainTextBytes);
            } catch (Exception ex) {
                throw new Exception("DPAPI was unable to decrypt data. " + ex.Message);
            } finally {
                if (plainTextBlob.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(plainTextBlob.pbData);
                }

                if (cipherTextBlob.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(cipherTextBlob.pbData);
                }

                if (entropyBlob.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(entropyBlob.pbData);
                }
            }
        }
示例#33
0
        public async Task CanUploadLargeDataBlobs()
        {
            var data = new byte[35 * 1024 * 1024];

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = 0x42;
            }
            var dataBlob = new DataBlob(IdGenerator.FromGuid(), data);

            if (await analystDataApiClient.ExistsAsync <DataBlob>(dataBlob.Id))
            {
                await adminDataApiClient.DeleteAsync <DataBlob>(dataBlob.Id);
            }

            string actualId = null;

            AssertStatusCode(
                () => actualId = analystDataApiClient.ReplaceAsync(dataBlob, dataBlob.Id).Result,
                HttpStatusCode.OK);
            analystDataApiClient.DeleteAsync <DataBlob>(actualId).Wait();
        }
示例#34
0
        private void DeserializeDataBlob()
        {
            Stream stream = null;

            try
            {
                if (Directory.Exists(GetFilepath()) && File.Exists(GetFilepath() + DataCacheFilename))
                {
                    stream = File.Open(GetFilepath() + DataCacheFilename, FileMode.Open);
                    BinaryFormatter bformatter = new BinaryFormatter();
                    bformatter.Binder = new VersionDeserializationBinder();
                    _dataBlob         = bformatter.Deserialize(stream) as DataBlob;
                    stream.Close();
                }
                else
                {
                    _dataBlob = new DataBlob();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("DataCache: Error deserializing data blob: " + e.Message);
                if (File.Exists(GetFilepath() + DataCacheFilename))
                {
                    File.Delete(GetFilepath() + DataCacheFilename);
                }

                _dataBlob = new DataBlob();
            }
            finally
            {
                if (null != stream)
                {
                    stream.Close();
                }
            }
        }
示例#35
0
        private void open(object sender, EventArgs e)
        {
            soil();
            clean();
            Stream stream = null;

            try {
                stream = new FileStream(inPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                using (BinaryReader reader = new BinaryReader(stream, Encoding.Default)) {
                    DataBlob metadata = readHeader(reader);
                    setupBlobs(metadata);
                    readChannels(reader, C1);
                    readChannels(reader, V2);
                    readChannels(reader, C2);
                }
            } catch (FileNotFoundException) {
                //silently fail.
            } finally {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
示例#36
0
        /// <summary>
        /// Initializes a BLOB structure from a byte array.
        /// </summary>
        /// <param name="data">
        /// Original data in a byte array format.
        /// </param>
        /// <param name="blob">
        /// Returned blob structure.
        /// </param>
        private static void InitBlob(byte[] data, ref DataBlob blob)
        {
            // Use empty array for null parameter.
            if (data == null)
            {
                data = new byte[0];
            }

            // Allocate memory for the BLOB data.
            blob.pbData = Marshal.AllocHGlobal(data.Length);

            // Make sure that memory allocation was successful.
            if (blob.pbData == IntPtr.Zero)
            {
                throw new Exception(
                          "Unable to allocate data buffer for BLOB structure.");
            }

            // Specify number of bytes in the BLOB.
            blob.cbData = data.Length;

            // Copy data from original source to the BLOB structure.
            Marshal.Copy(data, 0, blob.pbData, data.Length);
        }
示例#37
0
 public void setOutSamples(DataBlob.Samples samples) {
     outSamples = samples;
     properties["outSamples"].nValue = (int)samples;
     setExtra(options[(int)samples] + " to " + options[(int)outSamples]);
     soil();
 }
示例#38
0
 private static extern bool CryptUnprotectData(
     ref DataBlob pDataIn,
     String szDataDescr,
     ref DataBlob pOptionalEntropy,
     IntPtr pvReserved,
     ref CryptprotectPromptstruct
         pPromptStruct,
     int dwFlags,
     ref DataBlob pDataOut);
示例#39
0
 public byte[] Decrypt(
     byte[] cipherText,
     byte[] optionalEntropy,
     string dataDescription)
 {
     var plainTextBlob = new DataBlob();
     var cipherBlob = new DataBlob();
     var prompt = new
         CryptprotectPromptstruct();
     InitPromptstruct(ref prompt);
     try
     {
         try
         {
             int cipherTextSize = cipherText.Length;
             cipherBlob.pbData = Marshal.AllocHGlobal(cipherTextSize);
             if (IntPtr.Zero == cipherBlob.pbData)
             {
                 throw new Exception("Unable to allocate cipherText buffer.");
             }
             cipherBlob.cbData = cipherTextSize;
             Marshal.Copy
                 (
                     cipherText,
                     0,
                     cipherBlob.pbData,
                     cipherBlob.cbData);
         }
         catch (Exception ex)
         {
             throw new Exception
                 (
                 "Exception marshalling data. " +
                 ex.Message);
         }
         var entropyBlob = new DataBlob();
         int dwFlags;
         if (Store.UseMachineStore == _store)
         {
             //Using the machine store, should be providing entropy.
             dwFlags =
                 CryptprotectLocalMachine | CryptprotectUiForbidden;
             //Check to see if the entropy is null
             if (null == optionalEntropy)
             {
                 //Allocate something
                 optionalEntropy = new byte[0];
             }
             try
             {
                 int bytesSize = optionalEntropy.Length;
                 entropyBlob.pbData = Marshal.AllocHGlobal(bytesSize);
                 if (IntPtr.Zero == entropyBlob.pbData)
                 {
                     throw new Exception("Unable to allocate entropy buffer.");
                 }
                 entropyBlob.cbData = bytesSize;
                 Marshal.Copy
                     (
                         optionalEntropy,
                         0,
                         entropyBlob.pbData,
                         bytesSize);
             }
             catch (Exception ex)
             {
                 throw new Exception
                     (
                     "Exception entropy marshalling data. " +
                     ex.Message);
             }
         }
         else
         {
             //Using the user store
             dwFlags = CryptprotectUiForbidden;
         }
         bool retVal = dataDescription != null && CryptUnprotectData
                                                      (
                                                          ref cipherBlob,
                                                          dataDescription,
                                                          ref
                                                      entropyBlob,
                                                          IntPtr.Zero,
                                                          ref prompt,
                                                          dwFlags,
                                                          ref plainTextBlob);
         if (false == retVal)
         {
             throw new Exception
                 (
                 "Decryption failed. " +
                 GetErrorMessage(Marshal.GetLastWin32Error()));
         }
         //Free the blob and entropy.
         if (IntPtr.Zero != cipherBlob.pbData)
         {
             Marshal.FreeHGlobal(cipherBlob.pbData);
         }
         if (IntPtr.Zero != entropyBlob.pbData)
         {
             Marshal.FreeHGlobal(entropyBlob.pbData);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(@"Exception decrypting. " + ex.Message);
     }
     var plainText = new byte[plainTextBlob.cbData];
     Marshal.Copy
         (
             plainTextBlob.pbData,
             plainText,
             0,
             plainTextBlob.cbData);
     Marshal.FreeHGlobal(plainTextBlob.pbData);
     return plainText;
 }
示例#40
0
 private DataBlob readHeader(BinaryReader reader) {
     DataBlob metadata = new DataBlob();
     metadata.imageWidth = reader.ReadUInt16();
     metadata.imageHeight = reader.ReadUInt16();
     metadata.channelWidth = reader.ReadUInt16();
     metadata.channelHeight = reader.ReadUInt16();
     metadata.quantizeQuality = reader.ReadByte();
     metadata.samplingMode = (DataBlob.Samples)reader.ReadByte();
     return metadata;
 }
示例#41
0
        private void setupBlobs(DataBlob metadata) {
            C1 = new DataBlob();
            C2 = new DataBlob();
            C3 = new DataBlob();
            V2 = new DataBlob();
            V3 = new DataBlob();
            C1.type = C2.type = C3.type = DataBlob.Type.Channels;
            V2.type = V3.type = DataBlob.Type.Vectors;

            //import metadata onto channels
            C1.imageWidth = C2.imageWidth = C3.imageWidth = metadata.imageWidth;
            C1.imageHeight = C2.imageHeight = C3.imageHeight = metadata.imageHeight;
            C1.channelWidth = C2.channelWidth = C3.channelWidth = metadata.channelWidth;
            C1.channelHeight = C2.channelHeight = C3.channelHeight = metadata.channelHeight;
            C1.quantizeQuality = C2.quantizeQuality = C3.quantizeQuality = metadata.quantizeQuality;
            C1.samplingMode = C2.samplingMode = C3.samplingMode = metadata.samplingMode;

            Chunker c = new Chunker(8, metadata.channelWidth, metadata.channelHeight, metadata.channelWidth, 1);
            V2.imageWidth = V3.imageWidth = metadata.imageWidth;
            V2.imageHeight = V3.imageHeight = metadata.imageHeight;
            V2.channelWidth = V3.channelWidth = c.getChunksWide();
            V2.channelHeight = V3.channelHeight = c.getChunksHigh();
            V2.quantizeQuality = V3.quantizeQuality = metadata.quantizeQuality;
            V2.samplingMode = V3.samplingMode = metadata.samplingMode;

            //Allocate space for incoming data
            C1.channels = new byte[3][];
            C2.channels = new byte[3][];
            C3.channels = new byte[3][];
            V2.channels = new byte[3][];
            V3.channels = new byte[3][];

            int cMajor = C1.channelWidth * C1.channelHeight;
            Size sizeMinor = Subsample.getPaddedCbCrSize(new Size(C1.channelWidth, C1.channelHeight), C1.samplingMode);
            int cMinor = sizeMinor.Width * sizeMinor.Height;
            C1.channels[0] = new byte[cMajor];
            C2.channels[0] = new byte[cMajor];
            C3.channels[0] = new byte[cMajor];
            C1.channels[1] = new byte[cMinor];
            C2.channels[1] = new byte[cMinor];
            C3.channels[1] = new byte[cMinor];
            C1.channels[2] = new byte[cMinor];
            C2.channels[2] = new byte[cMinor];
            C3.channels[2] = new byte[cMinor];
            cMajor = V2.channelWidth * V2.channelHeight;
            sizeMinor = Subsample.getCbCrSize(new Size(V2.channelWidth, V2.channelHeight), V2.samplingMode);
            cMinor = sizeMinor.Width * sizeMinor.Height;
            V2.channels[0] = new byte[cMajor];
            V3.channels[0] = new byte[cMajor];
            V2.channels[1] = new byte[cMinor];
            V3.channels[1] = new byte[cMinor];
            V2.channels[2] = new byte[cMinor];
            V3.channels[2] = new byte[cMinor];
        }
示例#42
0
 protected static void writeChannels(BinaryWriter writer, DataBlob ch) {
     Chunker c = new Chunker(8, ch.channelWidth, ch.channelHeight, ch.channelWidth, 1);
     writeChannel(writer, ch.channels[0], c);
     Size s = Subsample.deduceCbCrSize(ch);
     c = new Chunker(8, s.Width, s.Height, s.Width, 1);
     writeChannel(writer, ch.channels[1], c);
     writeChannel(writer, ch.channels[2], c);
 }
示例#43
0
		/// <summary>
		/// Returns the byte representation of the serialized store.
		/// </summary>
		/// <param name="type">One of the <see cref="CertificateStoreType"/> values.</param>
		/// <returns>An array of bytes that represents the encoded store.</returns>
		/// <exception cref="CertificateException">An error occurs while saving the store to the memory buffer.</exception>
		private byte[] GetCerBuffer(CertificateStoreType type) {
			DataBlob data = new DataBlob();
			try {
				data.cbData = 0;
				data.pbData = IntPtr.Zero;
				if (SspiProvider.CertSaveStore(this.Handle, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, (int)type, SecurityConstants.CERT_STORE_SAVE_TO_MEMORY, ref data, 0) == 0)
					throw new CertificateException("Unable to get the certificate data.");
				data.pbData = Marshal.AllocHGlobal(data.cbData);
				if (SspiProvider.CertSaveStore(this.Handle, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, (int)type, SecurityConstants.CERT_STORE_SAVE_TO_MEMORY, ref data, 0) == 0)
					throw new CertificateException("Unable to get the certificate data.");
				byte[] ret = new byte[data.cbData];
				Marshal.Copy(data.pbData, ret, 0, data.cbData);
				return ret;
			} finally {
				if (data.pbData != IntPtr.Zero)
					Marshal.FreeHGlobal(data.pbData);
			}
		}
示例#44
0
文件: Node.cs 项目: JoePelz/NodeShop
 protected virtual void clean() {
     isDirty = false;
     state = null;
 }
示例#45
0
        protected override void clean()
        {
            base.clean();

            state  = null;
            vState = null;

            Address upstreamNow = properties["inChannelsNow"].input;

            if (upstreamNow == null)
            {
                return;
            }
            Address upstreamPast = properties["inChannelsPast"].input;

            if (upstreamPast == null)
            {
                return;
            }

            DataBlob stateNow = upstreamNow.node.getData(upstreamNow.port);

            if (stateNow == null)
            {
                return;
            }
            DataBlob statePast = upstreamPast.node.getData(upstreamPast.port);

            if (statePast == null)
            {
                return;
            }

            if (stateNow.type != DataBlob.Type.Channels || stateNow.channels == null)
            {
                return;
            }
            if (statePast.type != DataBlob.Type.Channels || statePast.channels == null)
            {
                return;
            }

            //check resolutions match
            if (stateNow.channels[0].Length != statePast.channels[0].Length ||
                stateNow.channels[1].Length != statePast.channels[1].Length ||
                stateNow.channels[2].Length != statePast.channels[2].Length)
            {
                return;
            }

            state  = stateNow.clone();
            vState = stateNow.clone();

            //create copy of channels for local use.
            byte[][] diffChannels = new byte[state.channels.Length][];
            diffChannels[0] = new byte[state.channels[0].Length];
            diffChannels[1] = new byte[state.channels[1].Length];
            diffChannels[2] = new byte[state.channels[2].Length];
            byte[][] vectors = new byte[3][];
            state.channels  = diffChannels;
            vState.channels = vectors;
            state.bmp       = null;
            vState.bmp      = null;
            state.type      = DataBlob.Type.Channels;
            vState.type     = DataBlob.Type.Vectors;

            calcMoVec(statePast.channels, stateNow.channels);
        }
示例#46
0
        private bool validateInput() {
            Address upC1 = properties["inChannels"].input;
            if (upC1 == null) return false;
            Address upC2 = properties["inChannels2"].input;
            if (upC2 == null) return false;
            Address upV2 = properties["inVectors2"].input;
            if (upV2 == null) return false;

            inC1 = upC1.node.getData(upC1.port);
            inC2 = upC2.node.getData(upC2.port);
            inV2 = upV2.node.getData(upV2.port);

            if (inC1 == null || inC1.type != DataBlob.Type.Channels || inC1.channels == null)
                return false;
            if (inC2 == null || inC2.type != DataBlob.Type.Channels || inC2.channels == null)
                return false;
            if (inV2 == null || inV2.type != DataBlob.Type.Vectors || inV2.channels == null)
                return false;

            if (inC1.channels[0].Length != inC2.channels[0].Length ||
                inC1.channels[1].Length != inC2.channels[1].Length || 
                inC1.channels[2].Length != inC2.channels[2].Length) {
                return false;
            }

            return true;
        }
示例#47
0
 private static extern bool CryptUnprotectData( ref DataBlob pCipherText, ref string pszDescription, ref DataBlob pEntropy, IntPtr pReserved, IntPtr pPrompt, CryptProtectFlags dwFlags, ref DataBlob pPlainText );
示例#48
0
 private void readChannels(BinaryReader reader, DataBlob ch) {
     Chunker c = new Chunker(8, ch.channelWidth, ch.channelHeight, ch.channelWidth, 1);
     readChannel(reader, ch.channels[0], c);
     Size s = Subsample.deduceCbCrSize(ch);
     c = new Chunker(8, s.Width, s.Height, s.Width, 1);
     readChannel(reader, ch.channels[1], c);
     readChannel(reader, ch.channels[2], c);
 }
示例#49
0
		/// <summary>
		/// Finds a certificate with a matching subject name.
		/// </summary>
		/// <param name="name">The X500 string to search for.</param>
		/// <param name="previous">The previous certificate.</param>
		/// <returns>A <see cref="Certificate"/> with a matching subject name -or- a null reference (<b>Nothing</b> in Visual Basic) if no matching certificate could be found in the store.</returns>
		/// <exception cref="ArgumentNullException"><paramref name="name"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
		/// <exception cref="ArgumentException"><paramref name="name"/> is invalid.</exception>
		/// <exception cref="CertificateException">An error occurs while encoding the specified string.</exception>
		public Certificate FindCertificateBySubjectName(string name, Certificate previous) {
			if (name == null)
				throw new ArgumentNullException();
			if (name.Length == 0)
				throw new ArgumentException();
			IntPtr prev, cert = IntPtr.Zero;
			if (previous == null)
				prev = IntPtr.Zero;
			else
				prev = SspiProvider.CertDuplicateCertificateContext(previous.Handle);
			DataBlob data = new DataBlob();
			if (SspiProvider.CertStrToName(SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, name, SecurityConstants.CERT_X500_NAME_STR, IntPtr.Zero, IntPtr.Zero, ref data.cbData, IntPtr.Zero) == 0)
				throw new CertificateException("Could not encode the specified string. [is the string a valid X500 string?]");
			data.pbData = Marshal.AllocHGlobal(data.cbData);
			try {
				if (SspiProvider.CertStrToName(SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, name, SecurityConstants.CERT_X500_NAME_STR, IntPtr.Zero, data.pbData, ref data.cbData, IntPtr.Zero) == 0)
					throw new CertificateException("Could not encode the specified string.");
				cert = SspiProvider.CertFindDataBlobCertificateInStore(this.Handle, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, 0, SecurityConstants.CERT_FIND_SUBJECT_NAME, ref data, prev);
			} finally {
				Marshal.FreeHGlobal(data.pbData);
			}
			if (cert == IntPtr.Zero)
				return null;
			else
				return new Certificate(cert);
		}
示例#50
0
 protected static void writeHeader(BinaryWriter writer, DataBlob info) {
     writer.Write((short)info.imageWidth);
     writer.Write((short)info.imageHeight);
     writer.Write((short)info.channelWidth);
     writer.Write((short)info.channelHeight);
     writer.Write((byte)info.quantizeQuality);
     writer.Write((byte)info.samplingMode);
 }
示例#51
0
        public byte[] Encrypt( byte[] plainTextBytes )
        {
            if ( description == null )
                description = "";

            DataBlob plainTextBlob = new DataBlob ( plainTextBytes );
            DataBlob cipherTextBlob = new DataBlob ( );
            DataBlob entropyBlob = new DataBlob ( entropy );

            try {
                CryptProtectFlags flags = CryptProtectFlags.UIForbidden;

                if ( keyType == DataProtectionKeyType.MachineKey )
                    flags |= CryptProtectFlags.LocalMachine;

                if ( !CryptProtectData ( ref plainTextBlob, description, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, flags, ref cipherTextBlob ) )
                    throw new COMException ( "CryptProtectData failed." + Marshal.GetLastWin32Error ( ) );

                byte[] cipherTextBytes = new byte[ cipherTextBlob.cbData ];

                Marshal.Copy ( cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData );

                return cipherTextBytes;
            } catch ( Exception ex ) {
                throw new Exception ( "DPAPI was unable to encrypt data. " + ex.Message );
            } finally {
                if ( plainTextBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( plainTextBlob.pbData );

                if ( cipherTextBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( cipherTextBlob.pbData );

                if ( entropyBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( entropyBlob.pbData );
            }
        }
示例#52
0
		/// <summary>
		/// Returns the byte representation of the PFX encoded store.
		/// </summary>
		/// <param name="password">The password to use when encrypting the private keys.</param>
		/// <param name="exportPrivateKeys"><b>true</b> if the private keys should be exported [if possible], <b>false</b> otherwise.</param>
		/// <returns>An array of bytes that represents the PFX encoded store.</returns>
		/// <exception cref="ArgumentNullException"><paramref name="password"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
		private byte[] GetPfxBuffer(string password, bool exportPrivateKeys) {
			if (password == null)
				throw new ArgumentNullException();
			DataBlob data = new DataBlob();
			try {
				data.pbData = IntPtr.Zero;
				data.cbData = 0;
				if (SspiProvider.PFXExportCertStoreEx(Handle, ref data, password, IntPtr.Zero, exportPrivateKeys ? SecurityConstants.EXPORT_PRIVATE_KEYS : 0) == 0)
					throw new CertificateException("Could not export the certificate store.");
				data.pbData = Marshal.AllocHGlobal(data.cbData);
				if (SspiProvider.PFXExportCertStoreEx(Handle, ref data, password, IntPtr.Zero, exportPrivateKeys ? SecurityConstants.EXPORT_PRIVATE_KEYS : 0) == 0)
					throw new CertificateException("Could not export the certificate store.");
				byte[] buffer = new byte[data.cbData];
				Marshal.Copy(data.pbData, buffer, 0, buffer.Length);
				return buffer;
			} finally {
				if (data.pbData != IntPtr.Zero)
					Marshal.FreeHGlobal(data.pbData);
			}
		}
示例#53
0
		/// <summary>
		/// Creates a new certificate store from a PFX/P12 encoded file.
		/// </summary>
		/// <param name="file">The contents of a PFX file.</param>
		/// <param name="password">The password used to encrypt the private key.</param>
		/// <param name="exportable"><b>true</b> if the private keys associated with the certificates should be marked as exportable, <b>false</b> otherwise.</param>
		/// <param name="location">One of the <see cref="KeysetLocation"/> values.</param>
		/// <returns>A <see cref="CertificateStore"/> instance.</returns>
		/// <exception cref="ArgumentNullException"><paramref name="file"/> or <paramref name="password"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
		/// <exception cref="ArgumentException"><paramref name="password"/> is invalid.</exception>
		/// <exception cref="CertificateException">An error occurs while loading the PFX file.</exception>
		// Thanks go out to Chris Hudel for the implementation of this method.
		public static CertificateStore CreateFromPfxFile(byte[] file, string password, bool exportable, KeysetLocation location) {
			if (password == null || file == null)
				throw new ArgumentNullException("The arguments cannot be null references.");
			CertificateStore cs;
			DataBlob pPFX = new DataBlob();
			// Crypt_data_blob contains two elements,
			// cbData = the size of the blob
			// pbData = a byte array of [cbData] size containing contents of the .p12 file
			pPFX.cbData = file.Length;
			// We need to marshal the byte array Bytes into a pointer so that it can be placed
			// in the structure (class) for the WinAPI call
			IntPtr buffer = Marshal.AllocHGlobal(file.Length);
			Marshal.Copy(file, 0, buffer, file.Length);
			pPFX.pbData = buffer;
			// IF this really is a valid PFX file, then do some work on it 
			try {
				if (SspiProvider.PFXIsPFXBlob(ref pPFX) != 0) {
					if (SspiProvider.PFXVerifyPassword(ref pPFX, password, 0) != 0) {
						int flags = (int)location;
						if (exportable)
							flags |= SecurityConstants.CRYPT_EXPORTABLE;
						IntPtr m_Handle = SspiProvider.PFXImportCertStore(ref pPFX, password, flags);
						if (m_Handle.Equals(IntPtr.Zero)) {
							throw new CertificateException("Unable to import the PFX file! [error code = " + Marshal.GetLastWin32Error() + "]");
						}
						cs = new CertificateStore(m_Handle);
					} else {
						throw new ArgumentException("The specified password is invalid.");
					}
				} else {
					throw new CertificateException("The specified file is not a PFX file.");
				}
			} finally {
				// Free the pointer
				Marshal.FreeHGlobal(buffer);
			}
			return cs;
		}
示例#54
0
 public static int getCbCrStride(DataBlob data) {
     Size unpadded = getCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);
     if (data.channels[1].Length == unpadded.Width * unpadded.Height) {
         return unpadded.Width;
     }
     Size padded = getPaddedCbCrSize(new Size(data.channelWidth, data.channelHeight), data.samplingMode);
     if (data.channels[1].Length == padded.Width * padded.Height) {
         return padded.Width;
     }
     return -1;
 }
示例#55
0
 /// <summary>
 /// Gets the string representation of the data blob.
 /// </summary>
 private string ToDataBlobString()
 {
     return(Kind + "(" + ToByteArrayString(DataBlob.ToArray()) + ")");
 }
示例#56
0
		/// <summary>
		/// Opens a serialized certificate store or a certificate store with signed PKCS7 messages.
		/// </summary>
		/// <param name="buffer">The bytes of the store to open.</param>
		/// <param name="type">One of the <see cref="CertificateStoreType"/> values.</param>
		/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
		/// <exception cref="CertificateException">An error occurs while opening the store.</exception>
		public CertificateStore(byte[] buffer, CertificateStoreType type) {
			if (buffer == null)
				throw new ArgumentNullException();
			DataBlob data = new DataBlob();
			data.cbData = buffer.Length;
			data.pbData = Marshal.AllocHGlobal(data.cbData);
			Marshal.Copy(buffer, 0, data.pbData, buffer.Length);
			IntPtr provider;
			if (type == CertificateStoreType.Pkcs7Message)
				provider = new IntPtr(SecurityConstants.CERT_STORE_PROV_PKCS7);
			else
				provider = new IntPtr(SecurityConstants.CERT_STORE_PROV_SERIALIZED);
			m_Handle = SspiProvider.CertOpenStoreData(provider, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, IntPtr.Zero, 0, ref data);
			Marshal.FreeHGlobal(data.pbData);
			if (m_Handle == IntPtr.Zero)
				throw new CertificateException("An error occurs while opening the store.");
		}
示例#57
0
        private void open(object sender, EventArgs e)
        {
            soil();
            clean();
            state          = new DataBlob();
            state.type     = DataBlob.Type.Channels;
            state.channels = new byte[3][];
            using (Stream stream = new FileStream(inPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                using (BinaryReader reader = new BinaryReader(stream, Encoding.Default)) {
                    state.imageWidth      = reader.ReadUInt16();
                    state.imageHeight     = reader.ReadUInt16();
                    state.channelWidth    = reader.ReadUInt16();
                    state.channelHeight   = reader.ReadUInt16();
                    state.quantizeQuality = reader.ReadByte();
                    state.samplingMode    = (DataBlob.Samples)reader.ReadByte();

                    state.channels[0] = new byte[state.channelWidth * state.channelHeight];

                    byte[] data = new byte[64];
                    byte   count, val;

                    //======================
                    //===== Y Channel ======
                    //======================
                    Chunker c       = new Chunker(8, state.channelWidth, state.channelHeight, state.channelWidth, 1);
                    var     indexer = Chunker.zigZag8Index();
                    for (int iChunk = 0; iChunk < c.getNumChunks(); iChunk++)
                    {
                        for (int iPixel = 0; iPixel < 64;)
                        {
                            val = reader.ReadByte();
                            if (val != rleToken)
                            {
                                data[iPixel++] = val;
                            }
                            else
                            {
                                count = reader.ReadByte();
                                val   = reader.ReadByte();
                                while (count > 0)
                                {
                                    data[iPixel++] = val;
                                    count--;
                                }
                            }
                        }
                        c.setZigZag8Block(state.channels[0], data, iChunk);
                    }

                    //===========================
                    //===== Cr, Cb Channels =====
                    //===========================
                    Size len = Subsample.getPaddedCbCrSize(new Size(state.channelWidth, state.channelHeight), state.samplingMode);
                    state.channels[1] = new byte[len.Width * len.Height];
                    state.channels[2] = new byte[state.channels[1].Length];
                    c = new Chunker(8, len.Width, len.Height, len.Width, 1);

                    indexer = Chunker.zigZag8Index();
                    for (int channel = 1; channel < state.channels.Length; channel++)
                    {
                        for (int iChunk = 0; iChunk < c.getNumChunks(); iChunk++)
                        {
                            for (int iPixel = 0; iPixel < 64;)
                            {
                                val = reader.ReadByte();
                                if (val != rleToken)
                                {
                                    data[iPixel++] = val;
                                }
                                else
                                {
                                    count = reader.ReadByte();
                                    val   = reader.ReadByte();
                                    while (count > 0)
                                    {
                                        data[iPixel++] = val;
                                        count--;
                                    }
                                }
                            }
                            c.setZigZag8Block(state.channels[channel], data, iChunk);
                        }
                    }
                }
            } //close file
        }
示例#58
0
		/// <summary>
		/// Finds a certificate with a matching hash.
		/// </summary>
		/// <param name="hash">The hash to search for.</param>
		/// <param name="hashType">One of the HashType values.</param>
		/// <returns>The <see cref="Certificate"/> with the matching hash -or- a null reference (<b>Nothing</b> in Visual Basic) if no certificate with that hash could be found in the store.</returns>
		/// <exception cref="ArgumentNullException"><paramref name="hash"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
		public Certificate FindCertificateByHash(byte[] hash, HashType hashType) {
			if (hash == null)
				throw new ArgumentNullException();
			int findType;
			if (hashType == HashType.SHA1)
				findType = SecurityConstants.CERT_FIND_SHA1_HASH;
			else if (hashType == HashType.MD5)
				findType = SecurityConstants.CERT_FIND_MD5_HASH;
			else
				findType = SecurityConstants.CERT_FIND_HASH;
			DataBlob data = new DataBlob();
			data.cbData = hash.Length;
			data.pbData = Marshal.AllocHGlobal(hash.Length);
			Marshal.Copy(hash, 0, data.pbData, hash.Length);
			IntPtr cert = SspiProvider.CertFindDataBlobCertificateInStore(this.Handle, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, 0, findType, ref data, IntPtr.Zero);
			Marshal.FreeHGlobal(data.pbData);
			if (cert == IntPtr.Zero)
				return null;
			else
				return new Certificate(cert);
		}
示例#59
0
		/// <summary>
		/// Finds a certificate with a matching key identifier.
		/// </summary>
		/// <param name="keyID">The key identifier to search for.</param>
		/// <returns>The <see cref="Certificate"/> with the matching key identifier -or- a null reference (<b>Nothing</b> in Visual Basic) if no matching certificate could be found in the store.</returns>
		/// <exception cref="ArgumentNullException"><paramref name="keyID"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
		/// <exception cref="ArgumentException"><paramref name="keyID"/> is invalid.</exception>
		public Certificate FindCertificateByKeyIdentifier(byte[] keyID) {
			if (keyID == null)
				throw new ArgumentNullException();
			if (keyID.Length == 0)
				throw new ArgumentException();
			DataBlob data = new DataBlob();
			data.cbData = keyID.Length;
			data.pbData = Marshal.AllocHGlobal(keyID.Length);
			Marshal.Copy(keyID, 0, data.pbData, keyID.Length);
			IntPtr cert = SspiProvider.CertFindDataBlobCertificateInStore(this.Handle, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, 0, SecurityConstants.CERT_FIND_KEY_IDENTIFIER, ref data, IntPtr.Zero);
			Marshal.FreeHGlobal(data.pbData);
			if (cert == IntPtr.Zero)
				return null;
			else
				return new Certificate(cert);
		}
示例#60
0
 public static extern bool CryptProtectData(ref DataBlob dataIn, string description, ref DataBlob optionalEntropy, IntPtr reserved, IntPtr promptStruct, uint flags, out DataBlob dataOut);