//
            // Summary:
            //  Special function for transforming the last block or partial block in the stream.  The
            //  return value is an array containting the remaining transformed bytes.
            //  We return a new array here because the amount of information we send back at the end could
            //  be larger than a single block once padding is accounted for.
            //
            // Parameters:
            //  inputBuffer  - The input for which to compute the transform.
            //  inputOffset  - The offset into the byte array from which to begin using data.
            //  inputCount   - The number of bytes in the byte array to use as data.
            //
            // Returns:
            //  The computed transform.
            //
            public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
            {
                IDT.DebugAssert(null != inputBuffer && 0 != inputBuffer.Length, "null input buffer");
                IDT.DebugAssert(0 != inputCount, "0 input count");
                GlobalAllocSafeHandle pOutData = null;
                int cbOutData = 0;

                byte[] outData;

                using (HGlobalSafeHandle pInData = HGlobalSafeHandle.Construct(inputCount))
                {
                    Marshal.Copy(inputBuffer, inputOffset, pInData.DangerousGetHandle(), inputCount);

                    int status = CardSpaceSelector.GetShim().m_csShimTransformFinalBlock(m_transCryptoHandle.InternalHandle,
                                                                                         inputCount,
                                                                                         pInData,
                                                                                         out cbOutData,
                                                                                         out pOutData);

                    if (0 != status)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw IDT.ThrowHelperError(new Win32Exception(status));
                    }
                    pOutData.Length = cbOutData;
                    outData         = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
                    using (pOutData)
                    {
                        Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
                    }
                }

                return(outData);
            }
예제 #2
0
파일: PDFSigner.cs 프로젝트: tixsys/esteid
        private byte[] ComputeHash(EstEIDReader estEidReader, byte[] data)
        {
            uint       rc, digest_length = 0;
            const uint hash_length = Digest.SHA1_LENGTH;

            Digest hash = new Digest(estEidReader);

            rc = hash.InitDigest(Digest.HashAlgorithm.SHA1);
            if (rc != EstEIDReader.ESTEID_OK)
            {
                throw new Exception(Resources.CARD_HASH_INIT);
            }

            rc = hash.UpdateDigest(data, (uint)data.Length);
            if (rc != EstEIDReader.ESTEID_OK)
            {
                throw new Exception(Resources.CARD_HASH_UPDATE);
            }

            HGlobalSafeHandle raw       = new HGlobalSafeHandle((int)hash_length);
            IntPtr            hashBytes = raw;

            if (hashBytes == IntPtr.Zero)
            {
                throw new OutOfMemoryException(Resources.OUT_OF_MEMORY);
            }

            rc = hash.FinalizeDigest(ref hashBytes, ref digest_length);
            if (rc != EstEIDReader.ESTEID_OK)
            {
                throw new Exception(Resources.CARD_HASH_FINALIZE);
            }

            return(raw.ToByteArray());
        }
        public bool VerifyHash(byte[] hash, string hashAlgOid, byte[] sig)
        {
            InfoCardTrace.ThrowInvalidArgumentConditional((hash == null) || (0 == hash.Length), "hash");
            InfoCardTrace.ThrowInvalidArgumentConditional(string.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
            InfoCardTrace.ThrowInvalidArgumentConditional((sig == null) || (0 == sig.Length), "sig");
            bool verified = false;

            using (HGlobalSafeHandle handle = HGlobalSafeHandle.Construct(hash.Length))
            {
                using (HGlobalSafeHandle handle2 = HGlobalSafeHandle.Construct(hashAlgOid))
                {
                    Marshal.Copy(hash, 0, handle.DangerousGetHandle(), hash.Length);
                    int status = 0;
                    using (HGlobalSafeHandle handle3 = HGlobalSafeHandle.Construct(sig.Length))
                    {
                        Marshal.Copy(sig, 0, handle3.DangerousGetHandle(), sig.Length);
                        status = CardSpaceSelector.GetShim().m_csShimVerifyHash(this.m_cryptoHandle.InternalHandle, hash.Length, handle, handle2, sig.Length, handle3, out verified);
                    }
                    if (status != 0)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw InfoCardTrace.ThrowHelperError(new Win32Exception(status));
                    }
                }
            }
            return(verified);
        }
        public byte[] SignHash(byte[] hash, string hashAlgOid)
        {
            InfoCardTrace.ThrowInvalidArgumentConditional((hash == null) || (0 == hash.Length), "hash");
            InfoCardTrace.ThrowInvalidArgumentConditional(string.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
            int pcbSig = 0;
            GlobalAllocSafeHandle pSig = null;

            using (HGlobalSafeHandle handle2 = HGlobalSafeHandle.Construct(hash.Length))
            {
                using (HGlobalSafeHandle handle3 = HGlobalSafeHandle.Construct(hashAlgOid))
                {
                    Marshal.Copy(hash, 0, handle2.DangerousGetHandle(), hash.Length);
                    RuntimeHelpers.PrepareConstrainedRegions();
                    int status = CardSpaceSelector.GetShim().m_csShimSignHash(this.m_cryptoHandle.InternalHandle, hash.Length, handle2, handle3, out pcbSig, out pSig);
                    if (status != 0)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw InfoCardTrace.ThrowHelperError(new Win32Exception(status));
                    }
                    pSig.Length = pcbSig;
                    byte[] destination = DiagnosticUtility.Utility.AllocateByteArray(pSig.Length);
                    using (pSig)
                    {
                        Marshal.Copy(pSig.DangerousGetHandle(), destination, 0, pSig.Length);
                    }
                    return(destination);
                }
            }
        }
 protected override void HashCore(byte[] array, int ibStart, int cbSize)
 {
     if (this.m_cachedBlock != null)
     {
         using (HGlobalSafeHandle handle = null)
         {
             if (this.m_cachedBlock.Length != 0)
             {
                 handle = HGlobalSafeHandle.Construct(this.m_cachedBlock.Length);
                 Marshal.Copy(this.m_cachedBlock, 0, handle.DangerousGetHandle(), this.m_cachedBlock.Length);
             }
             int status = CardSpaceSelector.GetShim().m_csShimHashCore(this.m_cryptoHandle.InternalHandle, this.m_cachedBlock.Length, (handle != null) ? handle : HGlobalSafeHandle.Construct());
             if (status != 0)
             {
                 ExceptionHelper.ThrowIfCardSpaceException(status);
                 throw InfoCardTrace.ThrowHelperError(new Win32Exception(status));
             }
         }
     }
     if (this.m_cachedBlock != null)
     {
         Array.Clear(this.m_cachedBlock, 0, this.m_cachedBlock.Length);
     }
     this.m_cachedBlock = DiagnosticUtility.Utility.AllocateByteArray(cbSize);
     Array.Copy(array, ibStart, this.m_cachedBlock, 0, cbSize);
 }
        public byte[] Decrypt(byte[] inData, bool fAOEP)
        {
            GlobalAllocSafeHandle pOutData = null;

            byte[] buffer;
            int    pcbOutData = 0;

            InfoCardTrace.ThrowInvalidArgumentConditional(null == inData, "indata");
            using (HGlobalSafeHandle handle2 = HGlobalSafeHandle.Construct(inData.Length))
            {
                Marshal.Copy(inData, 0, handle2.DangerousGetHandle(), inData.Length);
                int status = CardSpaceSelector.GetShim().m_csShimDecrypt(this.m_cryptoHandle.InternalHandle, fAOEP, inData.Length, handle2, out pcbOutData, out pOutData);
                if (status != 0)
                {
                    ExceptionHelper.ThrowIfCardSpaceException(status);
                    throw InfoCardTrace.ThrowHelperError(new Win32Exception(status));
                }
                pOutData.Length = pcbOutData;
                buffer          = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
                using (pOutData)
                {
                    Marshal.Copy(pOutData.DangerousGetHandle(), buffer, 0, pOutData.Length);
                }
            }
            return(buffer);
        }
 public override byte[] GenerateDerivedKey(string algorithmUri, byte[] label, byte[] nonce, int derivedKeyLength, int offset)
 {
     if (!this.IsSupportedAlgorithm(algorithmUri))
     {
         throw InfoCardTrace.ThrowHelperError(new NotSupportedException(Microsoft.InfoCards.SR.GetString("ClientUnsupportedCryptoAlgorithm", new object[] { algorithmUri })));
     }
     byte[] destination = null;
     using (HGlobalSafeHandle handle = HGlobalSafeHandle.Construct(label.Length))
     {
         using (HGlobalSafeHandle handle2 = HGlobalSafeHandle.Construct(nonce.Length))
         {
             GlobalAllocSafeHandle pDerivedKey = null;
             int cbDerivedKey = 0;
             Marshal.Copy(label, 0, handle.DangerousGetHandle(), label.Length);
             Marshal.Copy(nonce, 0, handle2.DangerousGetHandle(), nonce.Length);
             int error = CardSpaceSelector.GetShim().m_csShimGenerateDerivedKey(this.m_cryptoHandle.InternalHandle, label.Length, handle, nonce.Length, handle2, derivedKeyLength, offset, algorithmUri, out cbDerivedKey, out pDerivedKey);
             if (error != 0)
             {
                 throw InfoCardTrace.ThrowHelperError(new Win32Exception(error));
             }
             pDerivedKey.Length = cbDerivedKey;
             destination        = new byte[pDerivedKey.Length];
             using (pDerivedKey)
             {
                 Marshal.Copy(pDerivedKey.DangerousGetHandle(), destination, 0, pDerivedKey.Length);
             }
             return(destination);
         }
     }
 }
        public byte[] Decrypt(byte[] inData, bool fAOEP)
        {
            GlobalAllocSafeHandle pOutData = null;
            int cbOutData = 0;

            byte[] outData;
            IDT.ThrowInvalidArgumentConditional(null == inData, "indata");
            using (HGlobalSafeHandle pInData = HGlobalSafeHandle.Construct(inData.Length))
            {
                Marshal.Copy(inData, 0, pInData.DangerousGetHandle(), inData.Length);
                int status = CardSpaceSelector.GetShim().m_csShimDecrypt(m_cryptoHandle.InternalHandle,
                                                                         fAOEP,
                                                                         inData.Length,
                                                                         pInData,
                                                                         out cbOutData,
                                                                         out pOutData);

                if (0 != status)
                {
                    ExceptionHelper.ThrowIfCardSpaceException(status);
                    throw IDT.ThrowHelperError(new Win32Exception(status));
                }
                pOutData.Length = cbOutData;
                outData         = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
                using (pOutData)
                {
                    Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
                }
            }

            return(outData);
        }
        public bool VerifyHash(byte[] hash, string hashAlgOid, byte[] sig)
        {
            IDT.ThrowInvalidArgumentConditional(null == hash || 0 == hash.Length, "hash");
            IDT.ThrowInvalidArgumentConditional(String.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
            IDT.ThrowInvalidArgumentConditional(null == sig || 0 == sig.Length, "sig");
            bool verified = false;

            using (HGlobalSafeHandle pHash = HGlobalSafeHandle.Construct(hash.Length))
            {
                using (HGlobalSafeHandle pHashAlgOid = HGlobalSafeHandle.Construct(hashAlgOid))
                {
                    Marshal.Copy(hash, 0, pHash.DangerousGetHandle(), hash.Length);
                    int status = 0;
                    using (HGlobalSafeHandle pSig = HGlobalSafeHandle.Construct(sig.Length))
                    {
                        Marshal.Copy(sig, 0, pSig.DangerousGetHandle(), sig.Length);

                        status = CardSpaceSelector.GetShim().m_csShimVerifyHash(m_cryptoHandle.InternalHandle,
                                                                                hash.Length,
                                                                                pHash,
                                                                                pHashAlgOid,
                                                                                sig.Length,
                                                                                pSig,
                                                                                out verified);
                    }
                    if (0 != status)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw IDT.ThrowHelperError(new Win32Exception(status));
                    }
                }
            }

            return(verified);
        }
            public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
            {
                GlobalAllocSafeHandle pOutData = null;

                byte[] buffer;
                int    cbOutData = 0;

                using (HGlobalSafeHandle handle2 = HGlobalSafeHandle.Construct(inputCount))
                {
                    Marshal.Copy(inputBuffer, inputOffset, handle2.DangerousGetHandle(), inputCount);
                    int status = CardSpaceSelector.GetShim().m_csShimTransformFinalBlock(this.m_transCryptoHandle.InternalHandle, inputCount, handle2, out cbOutData, out pOutData);
                    if (status != 0)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw InfoCardTrace.ThrowHelperError(new Win32Exception(status));
                    }
                    pOutData.Length = cbOutData;
                    buffer          = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
                    using (pOutData)
                    {
                        Marshal.Copy(pOutData.DangerousGetHandle(), buffer, 0, pOutData.Length);
                    }
                }
                return(buffer);
            }
        public SafeHandle DoMarshal()
        {
            if (null == m_nativeChain)
            {
                int elementSize = InternalPolicyElement.Size;
                int chainLength = m_chain.Length;


                m_nativeChain = HGlobalSafeHandle.Construct(chainLength * elementSize);

                IntPtr pos = m_nativeChain.DangerousGetHandle();

                foreach (InternalPolicyElement element in m_chain)
                {
                    element.DoMarshal(pos);
                    unsafe
                    {
                        //
                        // All this just to do pos += elementSize
                        //
                        pos = new IntPtr((long)(((ulong)pos.ToPointer()) + (ulong)elementSize));
                    }
                }
            }

            return(m_nativeChain);
        }
예제 #12
0
 public void Dispose()
 {
     if (this.pointerValue != null)
     {
         this.pointerValue.Close();
         this.pointerValue = null;
     }
 }
예제 #13
0
 public void Dispose()
 {
     if (pointerValue != null)
     {
         pointerValue.Close();
         pointerValue = null;
     }
 }
예제 #14
0
        //
        // Summary:
        //  Implements the HashFinal method of the KeyedHashAlgorithm class by calling the InfoCard native client.
        //
        protected override byte[] HashFinal()
        {
            byte[] outData   = null;
            int    cbOutData = 0;

            IDT.DebugAssert(null != m_cachedBlock, "null cached block");

            HGlobalSafeHandle     pInData  = null;
            GlobalAllocSafeHandle pOutData = null;

            try
            {
                if (null != m_cachedBlock)
                {
                    if (0 != m_cachedBlock.Length)
                    {
                        pInData = HGlobalSafeHandle.Construct(m_cachedBlock.Length);
                        Marshal.Copy(m_cachedBlock, 0, pInData.DangerousGetHandle(), m_cachedBlock.Length);
                    }

                    int status = CardSpaceSelector.GetShim().m_csShimHashFinal(m_cryptoHandle.InternalHandle,
                                                                               m_cachedBlock.Length,
                                                                               null != pInData ? pInData : HGlobalSafeHandle.Construct(),
                                                                               out cbOutData,
                                                                               out pOutData);
                    if (0 != status)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw IDT.ThrowHelperError(new Win32Exception(status));
                    }
                    pOutData.Length = cbOutData;
                    outData         = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
                    using (pOutData)
                    {
                        Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
                    }
                }
            }
            finally
            {
                if (null != pInData)
                {
                    pInData.Dispose();
                }
                Array.Clear(m_cachedBlock, 0, m_cachedBlock.Length);
                m_cachedBlock = null;
            }

            return(outData);
        }
예제 #15
0
        // ISymmetricCrypto

        public override byte[] GenerateDerivedKey(string algorithmUri,
                                                  byte[] label,
                                                  byte[] nonce,
                                                  int derivedKeyLength,
                                                  int offset)
        {
            IDT.DebugAssert(!String.IsNullOrEmpty(algorithmUri), "null alg uri");
            IDT.DebugAssert(null != label && 0 != label.Length, "null label");
            IDT.DebugAssert(null != nonce && 0 != nonce.Length, "null nonce");

            if (!IsSupportedAlgorithm(algorithmUri))
            {
                throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
            }
            byte[] derivedKey = null;
            using (HGlobalSafeHandle pLabel = HGlobalSafeHandle.Construct(label.Length))
            {
                using (HGlobalSafeHandle pNonce = HGlobalSafeHandle.Construct(nonce.Length))
                {
                    GlobalAllocSafeHandle pDerivedKey = null;
                    int cbDerivedKey = 0;

                    Marshal.Copy(label, 0, pLabel.DangerousGetHandle(), label.Length);
                    Marshal.Copy(nonce, 0, pNonce.DangerousGetHandle(), nonce.Length);

                    int status = CardSpaceSelector.GetShim().m_csShimGenerateDerivedKey(m_cryptoHandle.InternalHandle,
                                                                                        label.Length,
                                                                                        pLabel,
                                                                                        nonce.Length,
                                                                                        pNonce,
                                                                                        derivedKeyLength,
                                                                                        offset,
                                                                                        algorithmUri,
                                                                                        out cbDerivedKey,
                                                                                        out pDerivedKey);

                    if (0 != status)
                    {
                        throw IDT.ThrowHelperError(new Win32Exception(status));
                    }
                    pDerivedKey.Length = cbDerivedKey;
                    derivedKey         = new byte[pDerivedKey.Length];
                    using (pDerivedKey)
                    {
                        Marshal.Copy(pDerivedKey.DangerousGetHandle(), derivedKey, 0, pDerivedKey.Length);
                    }
                }
            }
            return(derivedKey);
        }
 public SafeHandle DoMarshal()
 {
     if (this.m_nativeChain == null)
     {
         int size   = InternalPolicyElement.Size;
         int length = this.m_chain.Length;
         this.m_nativeChain = HGlobalSafeHandle.Construct((int)(length * size));
         IntPtr handle = this.m_nativeChain.DangerousGetHandle();
         foreach (InternalPolicyElement element in this.m_chain)
         {
             element.DoMarshal(handle);
             handle = new IntPtr(((long)((ulong)handle.ToPointer())) + size);
         }
     }
     return(this.m_nativeChain);
 }
예제 #17
0
        //
        // Summary:
        //  Implements the HashCore method of the KeyedHashAlgorithm class by calling the InfoCard native client.
        //
        // Parameters:
        //  array   - the bytes to hash.
        //  ibStart - the index in the array from which to begin hashing.
        //  cbSize  - the number of bytes after the starting index to hash.
        //
        protected override void HashCore(byte[] array, int ibStart, int cbSize)
        {
            //
            // will cache one block and call TransformBlock on the previous block.
            //
            if (null != m_cachedBlock)
            {
                HGlobalSafeHandle pInData = null;
                try
                {
                    if (0 != m_cachedBlock.Length)
                    {
                        pInData = HGlobalSafeHandle.Construct(m_cachedBlock.Length);
                        Marshal.Copy(m_cachedBlock, 0, pInData.DangerousGetHandle(), m_cachedBlock.Length);
                    }

                    int status = CardSpaceSelector.GetShim().m_csShimHashCore(m_cryptoHandle.InternalHandle,
                                                                              m_cachedBlock.Length,
                                                                              null != pInData ? pInData : HGlobalSafeHandle.Construct());

                    if (0 != status)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw IDT.ThrowHelperError(new Win32Exception(status));
                    }
                }
                finally
                {
                    if (null != pInData)
                    {
                        pInData.Dispose();
                    }
                }
            }

            //
            // Cache the current block.
            //
            if (null != m_cachedBlock)
            {
                Array.Clear(m_cachedBlock, 0, m_cachedBlock.Length);
            }
            m_cachedBlock = DiagnosticUtility.Utility.AllocateByteArray(cbSize);
            Array.Copy(array, ibStart, m_cachedBlock, 0, cbSize);

            return;
        }
예제 #18
0
            /// <summary>
            /// Retrieves the value associated with the specified name. If the name is not found, returns the default value that you provide.
            /// </summary>
            /// <param name="name">The name of the value to retrieve.</param>
            /// <param name="defaultValue">The value to return if name does not exist.</param>
            /// <returns>The value associated with name, with any embedded environment variables left unexpanded, or defaultValue if name is not found.</returns>
            public object GetValue(string name, object defaultValue)
            {
                EnsureNotDisposed();
                int cbData = 0;
                int ret    = sess.CeRegQueryValueEx(hKey, name, IntPtr.Zero, out _, IntPtr.Zero, ref cbData);

                if (ret != ERROR_SUCCESS)
                {
                    throw new RapiException(ret);
                }
                HGlobalSafeHandle data = new HGlobalSafeHandle(cbData);

                ret = sess.CeRegQueryValueEx(hKey, name, IntPtr.Zero, out int lpType, data, ref cbData);
                if (ret != 0)
                {
                    throw new RapiException(ret);
                }
                if (data == IntPtr.Zero)
                {
                    return(defaultValue);
                }
                byte[] buffer = new byte[cbData];
                Marshal.Copy(data, buffer, 0, cbData);
                switch (lpType)
                {
                case (int)RegistryValueKind.ExpandString:
                case (int)RegistryValueKind.String:
                    return(Encoding.Unicode.GetString(buffer));

                case (int)RegistryValueKind.DWord:
                    return(BitConverter.ToInt32(buffer, 0));

                case (int)RegistryValueKind.QWord:
                    return(BitConverter.ToInt64(buffer, 0));

                case (int)RegistryValueKind.Binary:
                    return(buffer);

                case (int)RegistryValueKind.MultiString:
                    return(Encoding.Unicode.GetString(buffer).TrimEnd('\0').Split('\0'));

                default:
                    return(defaultValue);
                }
            }
예제 #19
0
파일: PDFSigner.cs 프로젝트: tixsys/esteid
        private byte[] ComputeHash(EstEIDReader estEidReader, PdfSignatureAppearance sap)
        {
            Digest     hash          = new Digest(estEidReader);
            const uint hash_length   = Digest.SHA1_LENGTH;
            uint       digest_length = 0;
            uint       rc;

            rc = hash.InitDigest(Digest.HashAlgorithm.SHA1);
            if (rc != EstEIDReader.ESTEID_OK)
            {
                throw new Exception(Resources.CARD_HASH_INIT);
            }

            Stream       s    = sap.RangeStream;
            MemoryStream ss   = new MemoryStream();
            int          read = 0;

            byte[] buff = new byte[8192];
            while ((read = s.Read(buff, 0, 8192)) > 0)
            {
                ss.Write(buff, 0, read);
                rc = hash.UpdateDigest(buff, (uint)read);
                if (rc != EstEIDReader.ESTEID_OK)
                {
                    throw new Exception(Resources.CARD_HASH_UPDATE);
                }
            }

            HGlobalSafeHandle raw       = new HGlobalSafeHandle((int)hash_length);
            IntPtr            hashBytes = raw;

            if (hashBytes == IntPtr.Zero)
            {
                throw new OutOfMemoryException(Resources.OUT_OF_MEMORY);
            }

            rc = hash.FinalizeDigest(ref hashBytes, ref digest_length);
            if (rc != EstEIDReader.ESTEID_OK)
            {
                throw new Exception(Resources.CARD_HASH_FINALIZE);
            }

            return(raw.ToByteArray());
        }
예제 #20
0
            /// <summary>
            /// Sets the value of a name/value pair in the registry key, using the specified registry data type.
            /// </summary>
            /// <param name="name">The name of the value to store.</param>
            /// <param name="value">The data to be stored.</param>
            /// <param name="valueKind">The registry data type to use when storing the data.</param>
            public void SetValue(string name, object value, RegistryValueKind valueKind)
            {
                EnsureNotDisposed();
                HGlobalSafeHandle data;
                int cbData;

                switch (valueKind)
                {
                case RegistryValueKind.Binary:
                    cbData = ((byte[])value).Length;
                    data   = new HGlobalSafeHandle((byte[])value);
                    break;

                case RegistryValueKind.DWord:
                    cbData = sizeof(int);
                    data   = new HGlobalSafeHandle(BitConverter.GetBytes(Convert.ToInt32(value)));
                    break;

                case RegistryValueKind.String:
                case RegistryValueKind.ExpandString:
                case RegistryValueKind.MultiString:
                    string str   = (valueKind == RegistryValueKind.MultiString ? string.Join("\0", (string[])value) : value.ToString()) + '\0';
                    byte[] bytes = Encoding.Unicode.GetBytes(str);
                    cbData = bytes.Length;
                    data   = new HGlobalSafeHandle(bytes);
                    break;

                case RegistryValueKind.QWord:
                    cbData = sizeof(long);
                    data   = new HGlobalSafeHandle(BitConverter.GetBytes(Convert.ToInt64(value)));
                    break;

                case RegistryValueKind.Unknown:
                default:
                    throw new InvalidOperationException();
                }
                int ret = sess.CeRegSetValueEx(hKey, name, 0, (int)valueKind, data, cbData);

                if (ret != ERROR_SUCCESS)
                {
                    throw new RapiException(ret);
                }
            }
            public CryptoTransform(InfoCardSymmetricAlgorithm symAlgo, Direction cryptoDirection)
            {
                InternalRefCountedHandle nativeTransformHandle = null;

                byte[] iV = symAlgo.IV;
                using (HGlobalSafeHandle handle2 = HGlobalSafeHandle.Construct(iV.Length))
                {
                    Marshal.Copy(iV, 0, handle2.DangerousGetHandle(), iV.Length);
                    int status = CardSpaceSelector.GetShim().m_csShimGetCryptoTransform(symAlgo.m_cryptoHandle.InternalHandle, (int)symAlgo.Mode, (int)symAlgo.Padding, symAlgo.FeedbackSize, (int)cryptoDirection, iV.Length, handle2, out nativeTransformHandle);
                    if (status != 0)
                    {
                        InfoCardTrace.CloseInvalidOutSafeHandle(nativeTransformHandle);
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw InfoCardTrace.ThrowHelperError(new Win32Exception(status));
                    }
                    this.m_transCryptoHandle = (TransformCryptoHandle)CryptoHandle.Create(nativeTransformHandle);
                    this.m_param             = (RpcTransformCryptoParameters)this.m_transCryptoHandle.Parameters;
                }
            }
        protected override byte[] HashFinal()
        {
            byte[]                destination = null;
            int                   cbOutData   = 0;
            HGlobalSafeHandle     handle      = null;
            GlobalAllocSafeHandle pOutData    = null;

            try
            {
                if (this.m_cachedBlock == null)
                {
                    return(destination);
                }
                if (this.m_cachedBlock.Length != 0)
                {
                    handle = HGlobalSafeHandle.Construct(this.m_cachedBlock.Length);
                    Marshal.Copy(this.m_cachedBlock, 0, handle.DangerousGetHandle(), this.m_cachedBlock.Length);
                }
                int status = CardSpaceSelector.GetShim().m_csShimHashFinal(this.m_cryptoHandle.InternalHandle, this.m_cachedBlock.Length, (handle != null) ? handle : HGlobalSafeHandle.Construct(), out cbOutData, out pOutData);
                if (status != 0)
                {
                    ExceptionHelper.ThrowIfCardSpaceException(status);
                    throw InfoCardTrace.ThrowHelperError(new Win32Exception(status));
                }
                pOutData.Length = cbOutData;
                destination     = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
                using (pOutData)
                {
                    Marshal.Copy(pOutData.DangerousGetHandle(), destination, 0, pOutData.Length);
                }
            }
            finally
            {
                if (handle != null)
                {
                    handle.Dispose();
                }
                Array.Clear(this.m_cachedBlock, 0, this.m_cachedBlock.Length);
                this.m_cachedBlock = null;
            }
            return(destination);
        }
        public byte[] SignHash(byte[] hash, string hashAlgOid)
        {
            IDT.ThrowInvalidArgumentConditional(null == hash || 0 == hash.Length, "hash");
            IDT.ThrowInvalidArgumentConditional(String.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
            int cbSig = 0;
            GlobalAllocSafeHandle pSig = null;

            byte[] sig;
            using (HGlobalSafeHandle pHash = HGlobalSafeHandle.Construct(hash.Length))
            {
                using (HGlobalSafeHandle pHashAlgOid = HGlobalSafeHandle.Construct(hashAlgOid))
                {
                    Marshal.Copy(hash, 0, pHash.DangerousGetHandle(), hash.Length);

                    RuntimeHelpers.PrepareConstrainedRegions();
                    int status = CardSpaceSelector.GetShim().m_csShimSignHash(m_cryptoHandle.InternalHandle,
                                                                              hash.Length,
                                                                              pHash,
                                                                              pHashAlgOid,
                                                                              out cbSig,
                                                                              out pSig);

                    if (0 != status)
                    {
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw IDT.ThrowHelperError(new Win32Exception(status));
                    }
                    pSig.Length = cbSig;
                    sig         = DiagnosticUtility.Utility.AllocateByteArray(pSig.Length);
                    using (pSig)
                    {
                        Marshal.Copy(pSig.DangerousGetHandle(), sig, 0, pSig.Length);
                    }
                }
            }

            return(sig);
        }
            //
            // Parameters:
            //  symAlgo  - the algorithm being requested.
            //  cryptoDirection - determines whether the transform will encrypt or decrypt.
            //
            public CryptoTransform(InfoCardSymmetricAlgorithm symAlgo, Direction cryptoDirection)
            {
                InternalRefCountedHandle nativeHandle = null;

                byte[] iv = symAlgo.IV;
                using (HGlobalSafeHandle pIV = HGlobalSafeHandle.Construct(iv.Length))
                {
                    //
                    // Marshal the initialization vector.
                    //
                    Marshal.Copy(iv, 0, pIV.DangerousGetHandle(), iv.Length);

                    //
                    // Call native method to get a handle to a native transform.
                    //
                    int status = CardSpaceSelector.GetShim().m_csShimGetCryptoTransform(symAlgo.m_cryptoHandle.InternalHandle,
                                                                                        (int)symAlgo.Mode,
                                                                                        (int)symAlgo.Padding,
                                                                                        symAlgo.FeedbackSize,
                                                                                        (int)cryptoDirection,
                                                                                        iv.Length,
                                                                                        pIV,
                                                                                        out nativeHandle);

                    if (0 != status)
                    {
                        IDT.CloseInvalidOutSafeHandle(nativeHandle);
                        ExceptionHelper.ThrowIfCardSpaceException(status);
                        throw IDT.ThrowHelperError(new Win32Exception(status));
                    }

                    m_transCryptoHandle = (TransformCryptoHandle)CryptoHandle.Create(nativeHandle);

                    m_param = (RpcTransformCryptoParameters)m_transCryptoHandle.Parameters;
                }
            }
예제 #25
0
파일: PDFSigner.cs 프로젝트: tixsys/esteid
        private byte[] EstEIDCardSign(EstEIDReader estEidReader, PKCS11Signer signer, Byte[] digest)
        {
            uint       rc, slot;
            const uint rsa_length    = SIGNATURE_LENGTH;
            uint       digest_length = rsa_length;
            string     pin           = string.Empty;
            TokenInfo  token         = null;

            HGlobalSafeHandle raw      = new HGlobalSafeHandle((int)rsa_length);
            IntPtr            rsaBytes = raw;

            if (rsaBytes == IntPtr.Zero)
            {
                throw new OutOfMemoryException(Resources.OUT_OF_MEMORY);
            }

            token = signer.Token;
            slot  = signer.Slot;

            if (token.LoginRequired && token.PinIsSet)
            {
                if (!token.PinPadPresent)
                {
                    pin = ReadPin(token);

                    // redraw window: single-threaded UI
                    Application.DoEvents();

                    // user requested Cancel ?
                    if (pin == null)
                    {
                        throw new CancelException(Resources.ACTION_CANCELED);
                    }
                    // no pin supplied ?
                    else if (pin == string.Empty)
                    {
                        throw new Exception(Resources.NO_PIN_SUPPLIED);
                    }
                }
                else
                {
                    // we have a PINPAD present
                    pin = null;
                    statusHandler(string.Format(Resources.UI_ENTER_PIN_ONTHE_PINPAD, token.Label), false);
                }
            }

            rc = estEidReader.Sign(slot, pin, digest, (uint)digest.Length, ref rsaBytes, ref digest_length);
            // failure ?
            if (rc != EstEIDReader.ESTEID_OK)
            {
                // signing cancelled or timed out
                if (rc == PKCS11Error.CKR_FUNCTION_CANCELED)
                {
                    throw new CancelException(Resources.ACTION_CANCELED);
                }

                throw new PKCS11Exception(rc);
            }

            return(raw.ToByteArray());
        }
예제 #26
0
 public void FromString(string str)
 {
     variantType  = 31;
     pointerValue = new HGlobalSafeHandle(Marshal.StringToHGlobalUni(str));
 }