/// <summary>
        ///A test for CryptDecodeObjectEx
        ///</summary>

        public void CryptDecodeObjectExTest()
        {
            Encodings dwCertEncodingType = new Encodings();                        // TODO: Initialize to an appropriate value
            int       lpszStructType     = 0;                                      // TODO: Initialize to an appropriate value

            byte[] pbEncoded = null;                                               // TODO: Initialize to an appropriate value
            int    cbEncoded = 0;                                                  // TODO: Initialize to an appropriate value
            int    dwFlags   = 0;                                                  // TODO: Initialize to an appropriate value
            IntPtr blah      = new IntPtr();                                       // TODO: Initialize to an appropriate value
            CERT_PUBLIC_KEY_INFO pDecodePara         = new CERT_PUBLIC_KEY_INFO(); // TODO: Initialize to an appropriate value
            CERT_PUBLIC_KEY_INFO pDecodeParaExpected = new CERT_PUBLIC_KEY_INFO(); // TODO: Initialize to an appropriate value
            int  pcbStructInfo         = 0;                                        // TODO: Initialize to an appropriate value
            int  pcbStructInfoExpected = 0;                                        // TODO: Initialize to an appropriate value
            bool expected = false;                                                 // TODO: Initialize to an appropriate value


            var certInput = Resources.crud;
            var input     = from a in certInput.Split(' ')
                            select Byte.Parse(a, System.Globalization.NumberStyles.HexNumber);

            bool actual;

            actual = PfxStoreLoader.CryptDecodeObjectEx((Encodings.PKCS_7_ASN_ENCODING | Encodings.X509_ASN_ENCODING), PfxStoreLoader.X509_PUBLIC_KEY_INFO,
                                                        input.ToArray(), input.Count(), PfxStoreLoader.CRYPT_DECODE_ALLOC_FLAG, IntPtr.Zero, ref pDecodePara, ref pcbStructInfo);
            Assert.AreEqual(pDecodeParaExpected, pDecodePara);
            Assert.AreEqual(pcbStructInfoExpected, pcbStructInfo);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemple #2
0
 public static extern Boolean CryptEncodeObject(
     Int32 dwCertEncodingType,
     Int32 lpszStructType,
     ref CERT_PUBLIC_KEY_INFO pvStructInfo,
     Byte[] pbEncoded,
     ref Int32 pcbEncoded
     );
Exemple #3
0
        private static byte[] GetPublicKeyOfContainer(string container)
        {
            var  info    = new CERT_PUBLIC_KEY_INFO();
            var  pInfo   = IntPtr.Zero;
            var  hProv   = IntPtr.Zero;
            uint pcbInfo = 0;

            try
            {
                var i = 0;
                CryptAcquireContext(ref hProv, container, null, CRYPT_PROV_TYPE, 0);
                CryptExportPublicKeyInfo(hProv, AT_KEYEXCHANGE, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, IntPtr.Zero, ref pcbInfo);
                pInfo = Marshal.AllocHGlobal((int)pcbInfo);
                Marshal.StructureToPtr(info, pInfo, false);
                CryptExportPublicKeyInfo(hProv, AT_KEYEXCHANGE, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pInfo, ref pcbInfo);
                info = (CERT_PUBLIC_KEY_INFO)Marshal.PtrToStructure(pInfo, typeof(CERT_PUBLIC_KEY_INFO));
                var bytes = new byte[66];
                Marshal.Copy(info.PublicKey.pbData, bytes, 0, bytes.Length);
                return(bytes);
            }
            finally
            {
                if (hProv != IntPtr.Zero)
                {
                    CryptReleaseContext(hProv, 0);
                }
                Marshal.FreeHGlobal(pInfo);
            }
        }
        internal static byte[] GetRSAFromDER(byte[] DERData)
        {
            byte[] pvStructInfo = null;
            byte[] array        = null;
            uint   cbStructInfo = 0u;
            IntPtr zero         = IntPtr.Zero;

            if (CryptDecodeObject((CRYPT_ENCODING_FLAGS)65537u, new IntPtr(8), DERData, (uint)DERData.Length, CRYPT_DECODE_FLAGS.NONE, pvStructInfo, ref cbStructInfo))
            {
                pvStructInfo = new byte[cbStructInfo];
                if (CryptDecodeObject((CRYPT_ENCODING_FLAGS)65537u, new IntPtr(8), DERData, (uint)DERData.Length, CRYPT_DECODE_FLAGS.NONE, pvStructInfo, ref cbStructInfo))
                {
                    GCHandle gCHandle = GCHandle.Alloc(pvStructInfo, GCHandleType.Pinned);
                    try
                    {
                        CERT_PUBLIC_KEY_INFO cERT_PUBLIC_KEY_INFO = (CERT_PUBLIC_KEY_INFO)Marshal.PtrToStructure(gCHandle.AddrOfPinnedObject(), typeof(CERT_PUBLIC_KEY_INFO));
                        array = new byte[cERT_PUBLIC_KEY_INFO.PublicKey.cbData];
                        Marshal.Copy(cERT_PUBLIC_KEY_INFO.PublicKey.pbData, array, 0, array.Length);
                    }
                    finally
                    {
                        gCHandle.Free();
                    }
                    return(array);
                }
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
        /// <summary>
        ///A test for CryptDecodeObjectEx
        ///</summary>
        public void CryptDecodeObjectExTest()
        {
            Encodings dwCertEncodingType = new Encodings(); // TODO: Initialize to an appropriate value
            int lpszStructType = 0; // TODO: Initialize to an appropriate value
            byte[] pbEncoded = null; // TODO: Initialize to an appropriate value
            int cbEncoded = 0; // TODO: Initialize to an appropriate value
            int dwFlags = 0; // TODO: Initialize to an appropriate value
            IntPtr blah = new IntPtr(); // TODO: Initialize to an appropriate value
            CERT_PUBLIC_KEY_INFO pDecodePara = new CERT_PUBLIC_KEY_INFO(); // TODO: Initialize to an appropriate value
            CERT_PUBLIC_KEY_INFO pDecodeParaExpected = new CERT_PUBLIC_KEY_INFO(); // TODO: Initialize to an appropriate value
            int pcbStructInfo = 0; // TODO: Initialize to an appropriate value
            int pcbStructInfoExpected = 0; // TODO: Initialize to an appropriate value
            bool expected = false; // TODO: Initialize to an appropriate value

            var certInput = Resources.crud;
            var input = from a in certInput.Split(' ')
                        select Byte.Parse(a, System.Globalization.NumberStyles.HexNumber);
            bool actual;
            actual = PfxStoreLoader.CryptDecodeObjectEx((Encodings.PKCS_7_ASN_ENCODING | Encodings.X509_ASN_ENCODING), PfxStoreLoader.X509_PUBLIC_KEY_INFO,
                input.ToArray(), input.Count(), PfxStoreLoader.CRYPT_DECODE_ALLOC_FLAG, IntPtr.Zero, ref pDecodePara, ref pcbStructInfo);
            Assert.AreEqual(pDecodeParaExpected, pDecodePara);
            Assert.AreEqual(pcbStructInfoExpected, pcbStructInfo);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemple #6
0
 public static extern bool CryptEncodeObject(
     int dwCertEncodingType,
     int lpszStructType,
     ref CERT_PUBLIC_KEY_INFO pvStructInfo,
     byte[] pbEncoded,
     ref int pcbEncoded
     );
Exemple #7
0
 internal static partial bool CryptHashPublicKeyInfo(
     IntPtr hCryptProv,
     int algId,
     int dwFlags,
     CertEncodingType dwCertEncodingType,
     ref CERT_PUBLIC_KEY_INFO pInfo,
     byte[] pbComputedHash,
     ref int pcbComputedHash);
Exemple #8
0
 bool CryptHashPublicKeyInfo(
     [In]      IntPtr hCryptProv, // HCRYPTPROV
     [In]      uint Algid,        // ALG_ID
     [In]      uint dwFlags,
     [In]      uint dwCertEncodingType,
     [In]      ref CERT_PUBLIC_KEY_INFO pInfo,
     [Out]     byte[] pbComputedHash,
     [In, Out] ref uint pcbComputedHash);
Exemple #9
0
 public static extern bool CryptHashPublicKeyInfo(
     SafeCryptProviderHandle hCryptProv,
     CALG Algid,
     uint dwFlags,
     CertEncoding dwCertEncodingType,
     CERT_PUBLIC_KEY_INFO pInfo,
     byte[] pbComputedHash,
     out uint pcbComputedHash
     );
Exemple #10
0
        public static SubjectIdentifierOrKey ToSubjectIdentifierOrKey(this CERT_PUBLIC_KEY_INFO publicKeyInfo)
        {
            int    keyLength = Interop.Crypt32.CertGetPublicKeyLength(MsgEncodingType.All, ref publicKeyInfo);
            string oidValue  = publicKeyInfo.Algorithm.pszObjId.ToStringAnsi();
            AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(Oid.FromOidValue(oidValue, OidGroup.PublicKeyAlgorithm), keyLength);

            byte[]        keyValue = publicKeyInfo.PublicKey.ToByteArray();
            PublicKeyInfo pki      = new PublicKeyInfo(algorithmId, keyValue);

            return(new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.PublicKeyInfo, pki));
        }
Exemple #11
0
 internal static bool CryptHashPublicKeyInfoWrapper(
     [In]      IntPtr hCryptProv, // HCRYPTPROV
     [In]      uint Algid,        // ALG_ID
     [In]      uint dwFlags,
     [In]      uint dwCertEncodingType,
     [In]      ref CERT_PUBLIC_KEY_INFO pInfo,
     [Out]     byte[] pbComputedHash,
     [In, Out] ref uint pcbComputedHash)
 {
     BinaryParsers.PlatformSpecificHelpers.ThrowIfNotOnWindows();
     return(CryptHashPublicKeyInfo(hCryptProv, Algid, dwFlags, dwCertEncodingType, ref pInfo, pbComputedHash, ref pcbComputedHash));
 }
        public bool VerifySignature(Certificate cert, byte[] signature, byte[] hash)
        {
            int provider = 0;
            int hashptr  = 0;
            int pubKey   = 0;

            try {
                if (SspiProvider.CryptAcquireContext(ref provider, IntPtr.Zero, null, SecurityConstants.PROV_RSA_FULL, 0) == 0)
                {
                    if (Marshal.GetLastWin32Error() == SecurityConstants.NTE_BAD_KEYSET)
                    {
                        SspiProvider.CryptAcquireContext(ref provider, IntPtr.Zero, null, SecurityConstants.PROV_RSA_FULL, SecurityConstants.CRYPT_NEWKEYSET);
                    }
                }
                if (provider == 0)
                {
                    throw new CryptographicException("Unable to acquire a cryptographic context.");
                }
                if (SspiProvider.CryptCreateHash(provider, SecurityConstants.CALG_SSL3_SHAMD5, 0, 0, out hashptr) == 0)
                {
                    throw new CryptographicException("Unable to create the SHA-MD5 hash.");
                }
                if (SspiProvider.CryptSetHashParam(hashptr, SecurityConstants.HP_HASHVAL, hash, 0) == 0)
                {
                    throw new CryptographicException("Unable to set the value of the SHA-MD5 hash.");
                }
                CertificateInfo      ci  = cert.GetCertificateInfo();
                CERT_PUBLIC_KEY_INFO pki = new CERT_PUBLIC_KEY_INFO(ci);
                if (SspiProvider.CryptImportPublicKeyInfo(provider, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, ref pki, out pubKey) == 0)
                {
                    throw new CryptographicException("Unable to get a handle to the public key of the specified certificate.");
                }
                byte[] sign_rev = new byte[signature.Length];
                Array.Copy(signature, 0, sign_rev, 0, signature.Length);
                Array.Reverse(sign_rev);
                return(SspiProvider.CryptVerifySignature(hashptr, sign_rev, sign_rev.Length, pubKey, IntPtr.Zero, 0) != 0);
            } finally {
                if (pubKey != 0)
                {
                    SspiProvider.CryptDestroyKey(pubKey);
                }
                if (hashptr != 0)
                {
                    SspiProvider.CryptDestroyHash(hashptr);
                }
                if (provider != 0)
                {
                    SspiProvider.CryptReleaseContext(provider, 0);
                }
            }
        }
Exemple #13
0
        private unsafe static CtPublicKey FromWin32Structure(CERT_PUBLIC_KEY_INFO spki)
        {
            CtPublicKeyType type;
            var             parameters = new byte[spki.Algorithm.Parameters.cbData];

            if (spki.Algorithm.Parameters.cbData > 0)
            {
                Marshal.Copy(spki.Algorithm.Parameters.pbData, parameters, 0, parameters.Length);
            }
            switch (spki.Algorithm.pszObjId)
            {
            case KnownOids.X509Algorithms.RSA:
                if (parameters.Length == 0 || IsAsnNull(parameters))
                {
                    type = CtPublicKeyType.RSA_PKCS15;
                }
                else
                {
                    goto default;
                }
                break;

            case KnownOids.X509Algorithms.Ecc:
                var curve = OidParser.ReadFromBytes(parameters);
                if (curve?.Value == KnownOids.EccCurves.EcdsaP256)
                {
                    type = CtPublicKeyType.ECDSA_P256;
                }
                else
                {
                    goto default;
                }
                break;

            default:
                return(null);
            }
            if (spki.PublicKey.cbData == 0)
            {
                return(null);
            }
            var publicKey = new byte[spki.PublicKey.cbData];

            Marshal.Copy(new IntPtr(spki.PublicKey.pbData), publicKey, 0, publicKey.Length);
            return(new CtPublicKey
            {
                KeyType = type,
                Key = publicKey
            });
        }
        public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
        {
            unsafe
            {
                fixed(byte *pszOidValue = key.Oid.ValueAsAscii())
                {
                    byte[] encodedParameters = key.EncodedParameters.RawData;
                    fixed(byte *pEncodedParameters = encodedParameters)
                    {
                        byte[] encodedKeyValue = key.EncodedKeyValue.RawData;
                        fixed(byte *pEncodedKeyValue = encodedKeyValue)
                        {
                            CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO()
                            {
                                Algorithm = new CRYPT_ALGORITHM_IDENTIFIER()
                                {
                                    pszObjId   = new IntPtr(pszOidValue),
                                    Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters),
                                },

                                PublicKey = new CRYPT_BIT_BLOB()
                                {
                                    cbData      = encodedKeyValue.Length,
                                    pbData      = pEncodedKeyValue,
                                    cUnusedBits = 0,
                                },
                            };

                            int cb = 20;

                            byte[] buffer = new byte[cb];
                            if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb))
                            {
                                throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
                            }
                            ;
                            if (cb < buffer.Length)
                            {
                                byte[] newBuffer = new byte[cb];
                                Array.Copy(buffer, 0, newBuffer, 0, cb);
                                buffer = newBuffer;
                            }
                            return(buffer);
                        }
                    }
                }
            }
        }
Exemple #15
0
        public static unsafe byte[] BuildHashForPublicKeyBinary <THashAlgorithm>(X509Certificate2 certificate) where THashAlgorithm : HashAlgorithm, new()
        {
            var        PUBLIC_KEY_INFO_TYPE    = new IntPtr(8);
            const uint CRYPT_ENCODE_ALLOC_FLAG = 0x8000u;
            var        handle = LocalBufferSafeHandle.Zero;

            try
            {
                var publicKey = certificate.GetPublicKey();
                fixed(byte *publicKeyParametersPtr = certificate.PublicKey.EncodedParameters.RawData, publicKeyPtr = publicKey)
                {
                    var publicKeyInfo = new CERT_PUBLIC_KEY_INFO();

                    publicKeyInfo.Algorithm                   = new CRYPT_ALGORITHM_IDENTIFIER();
                    publicKeyInfo.PublicKey                   = new CRYPT_BIT_BLOB();
                    publicKeyInfo.Algorithm.pszObjId          = certificate.PublicKey.EncodedKeyValue.Oid.Value;
                    publicKeyInfo.Algorithm.Parameters        = new CRYPT_OBJID_BLOB();
                    publicKeyInfo.PublicKey.cbData            = (uint)publicKey.Length;
                    publicKeyInfo.PublicKey.cUnusedBits       = 0;
                    publicKeyInfo.PublicKey.pbData            = publicKeyPtr;
                    publicKeyInfo.Algorithm.Parameters.cbData = (uint)certificate.PublicKey.EncodedParameters.RawData.Length;
                    publicKeyInfo.Algorithm.Parameters.pbData = publicKeyParametersPtr;
                    uint size = 0;

                    if (Crypto32.CryptEncodeObjectEx(EncodingType.X509_ASN_ENCODING, PUBLIC_KEY_INFO_TYPE, ref publicKeyInfo, CRYPT_ENCODE_ALLOC_FLAG, IntPtr.Zero, out handle, ref size))
                    {
                        var encoded = new byte[size];
                        Marshal.Copy(handle.DangerousGetHandle(), encoded, 0, encoded.Length);
                        using (var algorithm = new THashAlgorithm())
                        {
                            return(algorithm.ComputeHash(encoded));
                        }
                    }
                }
            }
            finally
            {
                handle.Dispose();
            }
            return(null);
        }
Exemple #16
0
 public static extern int CryptVerifyCertificateSignature(
     IntPtr hCryptProv,
     Int32 dwCertEncodingType,
     IntPtr pbEncoded,
     Int32 cbEncoded,
     ref CERT_PUBLIC_KEY_INFO pPublicKey);
		public bool VerifySignature(Certificate cert, byte[] signature, byte[] hash) {
			int provider = 0;
			int hashptr = 0;
			int pubKey = 0;
			try {
				if (SspiProvider.CryptAcquireContext(ref provider, IntPtr.Zero, null, SecurityConstants.PROV_RSA_FULL, 0) == 0) {
					if (Marshal.GetLastWin32Error() == SecurityConstants.NTE_BAD_KEYSET)
						SspiProvider.CryptAcquireContext(ref provider, IntPtr.Zero, null, SecurityConstants.PROV_RSA_FULL, SecurityConstants.CRYPT_NEWKEYSET);
				}
				if (provider == 0)
					throw new CryptographicException("Unable to acquire a cryptographic context.");
				if (SspiProvider.CryptCreateHash(provider, SecurityConstants.CALG_SSL3_SHAMD5, 0, 0, out hashptr) == 0)
					throw new CryptographicException("Unable to create the SHA-MD5 hash.");
				if (SspiProvider.CryptSetHashParam(hashptr, SecurityConstants.HP_HASHVAL, hash, 0) == 0)
					throw new CryptographicException("Unable to set the value of the SHA-MD5 hash.");
				CertificateInfo ci = cert.GetCertificateInfo();
				CERT_PUBLIC_KEY_INFO pki = new CERT_PUBLIC_KEY_INFO(ci);
				if (SspiProvider.CryptImportPublicKeyInfo(provider, SecurityConstants.X509_ASN_ENCODING | SecurityConstants.PKCS_7_ASN_ENCODING, ref pki, out pubKey) == 0)
					throw new CryptographicException("Unable to get a handle to the public key of the specified certificate.");
				byte[] sign_rev = new byte[signature.Length];
				Array.Copy(signature, 0, sign_rev, 0, signature.Length);
				Array.Reverse(sign_rev);
				return SspiProvider.CryptVerifySignature(hashptr, sign_rev, sign_rev.Length, pubKey, IntPtr.Zero, 0) != 0;
			} finally {
				if (pubKey != 0)
					SspiProvider.CryptDestroyKey(pubKey);
				if (hashptr != 0)
					SspiProvider.CryptDestroyHash(hashptr);
				if (provider != 0)
					SspiProvider.CryptReleaseContext(provider, 0);
			}
		}
Exemple #18
0
 public static extern int CryptVerifyCertificateSignature(
   IntPtr hCryptProv,
   Int32 dwCertEncodingType,
   IntPtr pbEncoded,
   Int32 cbEncoded,
   ref CERT_PUBLIC_KEY_INFO pPublicKey);
Exemple #19
0
 internal static extern int CertGetPublicKeyLength(MsgEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pPublicKey);
Exemple #20
0
 public static extern bool CryptHashPublicKeyInfo(IntPtr hCryptProv, int algId, int dwFlags, CertEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pInfo, [Out] byte[] pbComputedHash, [In, Out] ref int pcbComputedHash);
Exemple #21
0
 internal static extern bool CryptEncodeObject(
     UInt32 dwCertEncodingType,
     IntPtr lpszStructType,
     ref CERT_PUBLIC_KEY_INFO pvStructInfo,
     byte[] pbEncoded,
     ref UInt32 pcbEncoded);
Exemple #22
0
 internal static extern bool CryptEncodeObject(
     UInt32 dwCertEncodingType,
     IntPtr lpszStructType,
     ref CERT_PUBLIC_KEY_INFO pvStructInfo,
     byte[] pbEncoded,
     ref UInt32 pcbEncoded);
Exemple #23
0
 public static extern bool CryptHashPublicKeyInfo(
     SafeCryptProviderHandle hCryptProv,
     CALG Algid,
     uint dwFlags,
     CertEncoding dwCertEncodingType,
     CERT_PUBLIC_KEY_INFO pInfo,
     byte[] pbComputedHash,
     out uint pcbComputedHash
 );
 internal static partial int CertGetPublicKeyLength(MsgEncodingType dwCertEncodingType, ref CERT_PUBLIC_KEY_INFO pPublicKey);
 internal PublicKeyInfo(IntPtr buffer)
 {
     _publicKey = (CERT_PUBLIC_KEY_INFO)Marshal.PtrToStructure(buffer, typeof(CERT_PUBLIC_KEY_INFO));
     _buffer    = buffer;
 }