当前位置: 首页>>代码示例>>C#>>正文


C# Cryptography.CngKey类代码示例

本文整理汇总了C#中System.Security.Cryptography.CngKey的典型用法代码示例。如果您正苦于以下问题:C# CngKey类的具体用法?C# CngKey怎么用?C# CngKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


CngKey类属于System.Security.Cryptography命名空间,在下文中一共展示了CngKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DecryptData

        /// <summary>
        /// Decrypts a ProcessedPacket.
        /// </summary>
        /// <param name="InitializationVector">Initialization vec to be used by AES.</param>
        /// <param name="PrivateKey">Private key to be used.</param>
        /// <param name="PubKeyBlob">Public key blob to be used.</param>
        /// <param name="StreamToDecrypt">The stream to decrypt.</param>
        /// <returns>A decrypted stream.</returns>
        public static byte[] DecryptData(byte[] InitializationVector, CngKey PrivateKey, byte[] PubKeyBlob,
            byte[] DataToDecrypt)
        {
            using (var Algorithm = new ECDiffieHellmanCng(PrivateKey))
            {
                using (CngKey PubKey = CngKey.Import(PubKeyBlob,
                      CngKeyBlobFormat.EccPublicBlob))
                {
                    byte[] SymmetricKey = Algorithm.DeriveKeyMaterial(PubKey);
                    Console.WriteLine("DecryptedStream: Created symmetric key with " +
                        "public key information: {0}", Convert.ToBase64String(SymmetricKey));

                    AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
                    AES.Key = SymmetricKey;
                    AES.IV = InitializationVector;
                    int NBytes = AES.BlockSize >> 3; //No idea...

                    using (ICryptoTransform Decryptor = AES.CreateDecryptor())
                    {
                        using (MemoryStream DecryptedStream = new MemoryStream())
                        {
                            var cs = new CryptoStream(DecryptedStream, Decryptor, CryptoStreamMode.Write);
                            cs.Write(DataToDecrypt, NBytes, DataToDecrypt.Length - NBytes);
                            cs.FlushFinalBlock();

                            return DecryptedStream.ToArray();
                        }
                    }
                }
            }
        }
开发者ID:ddfczm,项目名称:Project-Dollhouse,代码行数:39,代码来源:Cryptography.cs

示例2: CreateSelfSignedCertificate

        private static X509Certificate2 CreateSelfSignedCertificate(CngKey key, X500DistinguishedName subjectName)
        {
            using (SafeCertContextHandle selfSignedCertHandle = CreateSelfSignedCertificate(key,
                                                                                            true,
                                                                                            subjectName.RawData,
                                                                                            X509CertificateCreationOptions.None, // NONE
                                                                                            RsaSha1Oid,
                                                                                            DateTime.UtcNow,
                                                                                            DateTime.UtcNow.AddYears(1)))
            {
                X509Certificate2 certificate = null;
                bool addedRef = false;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    selfSignedCertHandle.DangerousAddRef(ref addedRef);
                    certificate = new X509Certificate2(selfSignedCertHandle.DangerousGetHandle());
                }
                finally
                {
                    if (addedRef)
                    {
                        selfSignedCertHandle.DangerousRelease();
                    }
                }

                key.Dispose();

                return certificate;
            }
        }
开发者ID:bstearns,项目名称:VipSwapper,代码行数:31,代码来源:CertHelper.cs

示例3: CreateKeys

 public static void CreateKeys()
 {
     // 根据算法创建密钥对
     aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP256);
     // 导出密钥对中的公钥
     alicePubKeyBlob = aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob);
 }
开发者ID:xxy1991,项目名称:cozy,代码行数:7,代码来源:B2Encryption.cs

示例4: Import

        internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format, CngProvider provider)
        {
            if (keyBlob == null)
                throw new ArgumentNullException(nameof(keyBlob));
            if (format == null)
                throw new ArgumentNullException(nameof(format));
            if (provider == null)
                throw new ArgumentNullException(nameof(provider));

            SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider();
            SafeNCryptKeyHandle keyHandle = null;
            ErrorCode errorCode;
            
            if (curveName == null)
            {
                errorCode = Interop.NCrypt.NCryptImportKey(providerHandle, IntPtr.Zero, format.Format, IntPtr.Zero, out keyHandle, keyBlob, keyBlob.Length, 0);
                if (errorCode != ErrorCode.ERROR_SUCCESS)
                {
                    throw errorCode.ToCryptographicException();
                }
            }
            else
            {
#if !NETNATIVE
                keyHandle = ECCng.ImportKeyBlob(format.Format, keyBlob, curveName, providerHandle);
#endif //!NETNATIVE
            }

            CngKey key = new CngKey(providerHandle, keyHandle);

            // We can't tell directly if an OpaqueTransport blob imported as an ephemeral key or not
            key.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob;

            return key;
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:35,代码来源:CngKey.Import.cs

示例5: CreateKeys

 private static void CreateKeys()
 {
     aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
     alicePubKeyBlod = aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob);
     bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
     bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.GenericPublicBlob);
 }
开发者ID:xxy1991,项目名称:cozy,代码行数:7,代码来源:ExchangeAndTransfer.cs

示例6: DeriveKey

        public static byte[] DeriveKey(CngKey externalPubKey, CngKey privateKey, int keyBitLength, byte[] algorithmId, byte[] partyVInfo, byte[] partyUInfo, byte[] suppPubInfo)
        {
            using (var cng = new ECDiffieHellmanCng(privateKey))
            {
                using (SafeNCryptSecretHandle hSecretAgreement = cng.DeriveSecretAgreementHandle(externalPubKey))
                {
                    using (var algIdBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_ALGORITHMID, algorithmId))
                    using (var pviBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_PARTYVINFO, partyVInfo))
                    using (var pvuBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_PARTYUINFO, partyUInfo))
                    using (var spiBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_SUPPPUBINFO, suppPubInfo))
                    {
                        using (var parameters = new NCrypt.NCryptBufferDesc(algIdBuffer, pviBuffer, pvuBuffer, spiBuffer))
                        {
                            uint derivedSecretByteSize;
                            uint status = NCrypt.NCryptDeriveKey(hSecretAgreement, "SP800_56A_CONCAT", parameters, null, 0, out derivedSecretByteSize, 0);

                            if (status != BCrypt.ERROR_SUCCESS)
                                throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", status));

                            var secretKey = new byte[derivedSecretByteSize];

                            status = NCrypt.NCryptDeriveKey(hSecretAgreement, "SP800_56A_CONCAT", parameters, secretKey, derivedSecretByteSize, out derivedSecretByteSize, 0);

                            if (status != BCrypt.ERROR_SUCCESS)
                                throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", status));

                            return Arrays.LeftmostBits(secretKey, keyBitLength);
                        }
                    }
                }
            }            

        }
开发者ID:coryflucas,项目名称:jose-jwt,代码行数:33,代码来源:ConcatKDF.cs

示例7: CngCryptographicKey

        /// <summary>
        /// Initializes a new instance of the <see cref="CngCryptographicKey"/> class.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="eccPrivateKeyBlob">The ECC Private key blob from which this key was imported, if applicable.</param>
        internal CngCryptographicKey(CngKey key, byte[] eccPrivateKeyBlob)
        {
            Requires.NotNull(key, "key");

            this.key = key;
            this.eccPrivateKeyBlob = eccPrivateKeyBlob.CloneArray();
        }
开发者ID:martijn00,项目名称:PCLCrypto,代码行数:12,代码来源:CngCryptographicKey.cs

示例8: Verify

 public static bool Verify(byte[] securedInput, byte[] signature, CngKey key, CngAlgorithm hash, int saltSize)
 {
     using (HashAlgorithm algo = HashAlgorithm(hash))
     {
         return VerifyHash(algo.ComputeHash(securedInput),signature, key, hash.Algorithm, saltSize);
     }
 }
开发者ID:XinicsInc,项目名称:jose-jwt,代码行数:7,代码来源:RsaPss.cs

示例9: IsSignatureValid

 private bool IsSignatureValid(byte[] hash, byte[] signature, CngKey key)
 {
     using (var signingAlg = new RSACng(key))
     {
         return signingAlg.VerifyHash(hash, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pss);
     }
 }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:7,代码来源:Program.cs

示例10: ECDsaCng

        public ECDsaCng(CngKey key) {
            Contract.Ensures(LegalKeySizesValue != null);
            Contract.Ensures(m_key != null && m_key.AlgorithmGroup == CngAlgorithmGroup.ECDsa);

            if (key == null) {
                throw new ArgumentNullException("key");
            }
            if (key.AlgorithmGroup != CngAlgorithmGroup.ECDsa) {
                throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDsaRequiresECDsaKey), "key");
            }

            if (!NCryptNative.NCryptSupported) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
            }

            LegalKeySizesValue = s_legalKeySizes;

            // Make a copy of the key so that we continue to work if it gets disposed before this algorithm
            //
            // This requires an assert for UnmanagedCode since we'll need to access the raw handles of the key
            // and the handle constructor of CngKey.  The assert is safe since ECDsaCng will never expose the
            // key handles to calling code (without first demanding UnmanagedCode via the Handle property of
            // CngKey).
            //
            // We also need to dispose of the key handle since CngKey.Handle returns a duplicate
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
            using (SafeNCryptKeyHandle keyHandle = key.Handle) {
                Key = CngKey.Open(keyHandle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None);
            }
            CodeAccessPermission.RevertAssert();

            KeySize = m_key.KeySize;
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:33,代码来源:ECDsaCng.cs

示例11: Create

        public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters)
        {
            if (algorithm == null)
                throw new ArgumentNullException("algorithm");

            if (creationParameters == null)
                creationParameters = new CngKeyCreationParameters();

            SafeNCryptProviderHandle providerHandle = creationParameters.Provider.OpenStorageProvider();
            SafeNCryptKeyHandle keyHandle;
            ErrorCode errorCode = Interop.NCrypt.NCryptCreatePersistedKey(providerHandle, out keyHandle, algorithm.Algorithm, keyName, 0, creationParameters.KeyCreationOptions);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            InitializeKeyProperties(keyHandle, creationParameters);

            errorCode = Interop.NCrypt.NCryptFinalizeKey(keyHandle, 0);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            CngKey key = new CngKey(providerHandle, keyHandle);

            // No name translates to an ephemeral key
            if (keyName == null)
            {
                key.IsEphemeral = true;
            }

            return key;
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:30,代码来源:CngKey.Create.cs

示例12: Write

        public override void Write(CngKey key, Stream stream)
        {
            int keySize;
            byte[] x;
            byte[] y;

            var keyBlob = key.Export(CngKeyBlobFormat.EccPublicBlob);

            unsafe
            {
                fixed(byte* pKeyBlob = keyBlob)
                {
                    var pBcryptBlob = (BCRYPT_ECCKEY_BLOB*) pKeyBlob;
                    var offset = Marshal.SizeOf(typeof (BCRYPT_ECCKEY_BLOB));

                    keySize = pBcryptBlob->KeySizeBytes;
                    x = new byte[keySize];
                    y = new byte[keySize];

                    Buffer.BlockCopy(keyBlob, offset, x, 0, keySize);
                    offset += keySize;
                    Buffer.BlockCopy(keyBlob, offset, y, 0, keySize);
                }
            }

            WriteInternal(keySize, x, y, stream);
        }
开发者ID:holytshirt,项目名称:Jwt4Net,代码行数:27,代码来源:CngKeyWriter.cs

示例13: CreateKey

 public static void CreateKey()
 {
     aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
     bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
     alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob);
     bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob);
 }
开发者ID:niujiale,项目名称:SecurityTransportation,代码行数:7,代码来源:Program.cs

示例14: ECDiffieHellmanCngPublicKey

 internal ECDiffieHellmanCngPublicKey(CngKey key) : base(key.Export(CngKeyBlobFormat.EccPublicBlob))
 {
     this.m_format = CngKeyBlobFormat.EccPublicBlob;
     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
     this.m_key = CngKey.Open(key.Handle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None);
     CodeAccessPermission.RevertAssert();
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:ECDiffieHellmanCngPublicKey.cs

示例15: DeriveKeyMaterial

    public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey)
    {
      Contract.Ensures(Contract.Result<byte[]>() != null);
      Contract.Ensures(this.Key.Handle != null);

      return default(byte[]);
    }
开发者ID:asvishnyakov,项目名称:CodeContracts,代码行数:7,代码来源:System.Security.Cryptography.ECDiffieHellmanCng.cs


注:本文中的System.Security.Cryptography.CngKey类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。