static Boolean deleteCngKey(SafeNCryptKeyHandle phKey) { var hresult = NCrypt.NCryptDeleteKey(phKey, 0); phKey.Dispose(); return(hresult == 0); }
private static byte[] SignHash(byte[] hash, CngKey key, string algorithm, int saltSize) { var paddingIndo = new BCrypt.BCRYPT_PSS_PADDING_INFO(algorithm, saltSize); uint size; uint status; status = NCrypt.NCryptSignHash(key.Handle, ref paddingIndo, hash, hash.Length, null, 0, out size, BCrypt.BCRYPT_PAD_PSS); if (status != BCrypt.ERROR_SUCCESS) { throw new CryptographicException(string.Format("NCrypt.NCryptSignHash() (signature size) failed with status code:{0}", status)); } byte[] signature = new byte[size]; status = NCrypt.NCryptSignHash(key.Handle, ref paddingIndo, hash, hash.Length, signature, signature.Length, out size, BCrypt.BCRYPT_PAD_PSS); if (status != BCrypt.ERROR_SUCCESS) { throw new CryptographicException(string.Format("NCrypt.NCryptSignHash() failed with status code:{0}", status)); } return(signature); }
// signing with CNG keys Byte[] signHashEcDsaCng(Byte[] hash) { Int32 hresult = NCrypt.NCryptSignHash( phPrivKey, IntPtr.Zero, hash, hash.Length, null, 0, out Int32 pcbResult, 0); if (hresult != 0) { throw new CryptographicException(hresult); } Byte[] pbSignature = new Byte[pcbResult]; hresult = NCrypt.NCryptSignHash( phPrivKey, IntPtr.Zero, hash, hash.Length, pbSignature, pbSignature.Length, out pcbResult, 0); if (hresult != 0) { throw new CryptographicException(hresult); } return(pbSignature); }
Boolean verifyHashEcDsa(Byte[] hash, Byte[] signature) { Int32 hresult = NCrypt.NCryptVerifySignature(phPubKey, IntPtr.Zero, hash, hash.Length, signature, signature.Length, 0); return(hresult == 0); }
void getCngHandleFromLegacy(SafeHandle phCryptProvOrNCryptKey) { // attempt to translate legacy HCRYPTPROV handle to CNG key handle Int32 hresult = NCrypt.NCryptTranslateHandle( IntPtr.Zero, out SafeNCryptKeyHandle cngKey, phCryptProvOrNCryptKey, IntPtr.Zero, (UInt32)X509KeySpecFlags.AT_NONE, 0); // release legacy HCRYPTPROV handle AdvAPI.CryptReleaseContext(phCryptProvOrNCryptKey.DangerousGetHandle(), 0); if (hresult == 0) { // if key is successfully translated, assign new CNG key handle to phPrivKey phPrivKey = cngKey; isCng = true; } else { // if key translation failed, then switch to legacy RSA/DSACryptoServiceProvider isCng = false; legacyKey = SignerCertificate.PrivateKey; } }
static CspCNGCollection m_enumcngprovs() { UInt32 pImplCount = 0; IntPtr ppImplList = IntPtr.Zero; StringBuilder SB = new StringBuilder(); Hashtable interfaces = get_interfaces(); CspCNGCollection csps = new CspCNGCollection(); Int32 retn = NCrypt.NCryptEnumStorageProviders(ref pImplCount, ref ppImplList, 0); if (retn != 0) { throw new Win32Exception(unchecked ((Int32)retn)); } IntPtr pvInput = ppImplList; for (Int32 index = 0; index < pImplCount; index++) { nCrypt2.NCryptProviderName Name = (nCrypt2.NCryptProviderName)Marshal.PtrToStructure(ppImplList, typeof(nCrypt2.NCryptProviderName)); ppImplList = (IntPtr)((UInt64)ppImplList + (UInt32)Marshal.SizeOf(typeof(nCrypt2.NCryptProviderName))); SB.Append(Name.pszName + ","); } String[] names = SB.ToString().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); NCrypt.NCryptFreeBuffer(pvInput); foreach (String pszProviderName in names) { ALG_ID_CNGCollection algs = new ALG_ID_CNGCollection(); retn = NCrypt.NCryptOpenStorageProvider(out SafeNCryptProviderHandle phProvider, pszProviderName, 0); if (retn == 0) { Int32 pdwAlgCount = 0; IntPtr ppAlgList = IntPtr.Zero; retn = NCrypt.NCryptEnumAlgorithms(phProvider, 0, ref pdwAlgCount, ref ppAlgList, 0); if (retn != 0) { throw new Win32Exception(unchecked ((Int32)retn)); } pvInput = ppAlgList; for (Int32 index = 0; index < pdwAlgCount; index++) { nCrypt2.NCryptAlgorithmName AlgId = (nCrypt2.NCryptAlgorithmName)Marshal.PtrToStructure(ppAlgList, typeof(nCrypt2.NCryptAlgorithmName)); algs.Add(get_cngalgparams(AlgId, interfaces)); ppAlgList = (IntPtr)((UInt64)ppAlgList + (UInt32)Marshal.SizeOf(typeof(nCrypt2.NCryptAlgorithmName))); } NCrypt.NCryptFreeBuffer(pvInput); } csps.Add(new CspCNG(pszProviderName, String.Empty, algs)); } return(csps); }
private static bool VerifyHash(byte[] hash, byte[] signature, CngKey key, string algorithm, int saltSize) { BCrypt.BCRYPT_PSS_PADDING_INFO bCRYPTPSSPADDINGINFO = new BCrypt.BCRYPT_PSS_PADDING_INFO(algorithm, saltSize); uint num = NCrypt.NCryptVerifySignature(key.Handle, ref bCRYPTPSSPADDINGINFO, hash, (int)hash.Length, signature, (int)signature.Length, 8); if (num == -2146893818) { return(false); } if (num != 0) { throw new CryptographicException(string.Format("NCrypt.NCryptSignHash() (signature size) failed with status code:{0}", num)); } return(true); }
protected override bool ReleaseHandle() { if (!_callerFree) { return(true); } if (IsNCryptKey) { return(NCrypt.NCryptFreeObject(handle) == SECURITY_STATUS.ERROR_SUCCESS); } else { return(AdvApi32.CryptReleaseContext(handle, 0u)); } }
internal override NCryptKeyOrCryptProviderSafeHandle OpenExisting(string keyName, out KeySpec keySpec) { keySpec = KeySpec.NONE; NCryptKeyOrCryptProviderSafeHandle keyHandle; var result = NCrypt.NCryptOpenKey(_storageProvider.Handle, out keyHandle, keyName, KeySpec.NONE, 0u); if (result == SECURITY_STATUS.ERROR_SUCCESS) { return(keyHandle); } if (result == SECURITY_STATUS.NTE_BAD_KEYSET) { return(null); } throw new InvalidOperationException("Failed to open key."); }
private static bool VerifyHash(byte[] hash, byte[] signature, CngKey key, string algorithm, int saltSize) { var paddingIndo = new BCrypt.BCRYPT_PSS_PADDING_INFO(algorithm, saltSize); uint status = NCrypt.NCryptVerifySignature(key.Handle, ref paddingIndo, hash, hash.Length, signature, signature.Length, BCrypt.BCRYPT_PAD_PSS); if (status == NCrypt.NTE_BAD_SIGNATURE) //honestly it always failing with NTE_INVALID_PARAMETER, but let's stick to public API { return(false); } if (status != BCrypt.ERROR_SUCCESS) { throw new CryptographicException(string.Format("NCrypt.NCryptSignHash() (signature size) failed with status code:{0}", status)); } return(true); }
private static byte[] SignHash(byte[] hash, CngKey key, string algorithm, int saltSize) { BCrypt.BCRYPT_PSS_PADDING_INFO bcrypt_PSS_PADDING_INFO = new BCrypt.BCRYPT_PSS_PADDING_INFO(algorithm, saltSize); uint num2; uint num = NCrypt.NCryptSignHash(key.Handle, ref bcrypt_PSS_PADDING_INFO, hash, hash.Length, null, 0, out num2, 8u); if (num != 0u) { throw new CryptographicException(string.Format("NCrypt.NCryptSignHash() (signature size) failed with status code:{0}", num)); } byte[] array = new byte[num2]; num = NCrypt.NCryptSignHash(key.Handle, ref bcrypt_PSS_PADDING_INFO, hash, hash.Length, array, array.Length, out num2, 8u); if (num != 0u) { throw new CryptographicException(string.Format("NCrypt.NCryptSignHash() failed with status code:{0}", num)); } return(array); }
/// <summary> /// Computes the hash value of the specified byte array using the specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="certificate">An <see cref="X509Certificate2"/> object of the signer certificate.</param> /// <param name="message">Message to be signed.</param> /// <param name="hashAlgorithm">The name of the hash algorithm to use in the signature. For example, 'SHA256'</param> /// <returns>The signature for the specified data.</returns> public static Byte[] SignMessage(X509Certificate2 certificate, Byte[] message, Oid hashAlgorithm) { SafeNCryptKeyHandle phCryptProv = new SafeNCryptKeyHandle(); UInt32 pdwKeySpec = 0; Boolean pfCallerFreeProv = false; if (!Crypt32.CryptAcquireCertificatePrivateKey(certificate.Handle, Wincrypt.CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG, IntPtr.Zero, out phCryptProv, out pdwKeySpec, out pfCallerFreeProv)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } // true -> CNG, false -> legacy if (pdwKeySpec == UInt32.MaxValue) { Byte[] hashBytes = calculateHash(message, hashAlgorithm.FriendlyName, false); try { Int32 hresult = NCrypt.NCryptSignHash(phCryptProv, IntPtr.Zero, hashBytes, hashBytes.Length, null, 0, out Int32 pcbResult, 0); if (hresult != 0) { throw new CryptographicException(hresult); } Byte[] pbSignature = new Byte[pcbResult]; hresult = NCrypt.NCryptSignHash(phCryptProv, IntPtr.Zero, hashBytes, hashBytes.Length, pbSignature, pbSignature.Length, out pcbResult, 0); if (hresult != 0) { throw new CryptographicException(hresult); } return(pbSignature); } finally { if (pfCallerFreeProv) { NCrypt.NCryptFreeObject(phCryptProv.DangerousGetHandle()); } } } if (pfCallerFreeProv) { AdvAPI.CryptReleaseContext(phCryptProv.DangerousGetHandle(), 0); } calculateHash(message, hashAlgorithm.FriendlyName, false); RSACryptoServiceProvider key = (RSACryptoServiceProvider)certificate.PrivateKey; return(key.SignData(message, hashAlgorithm.Value)); }
public static byte[] Decrypt(byte[] cipherText, CngKey key, CngAlgorithm hash) { uint num; BCrypt.BCRYPT_OAEP_PADDING_INFO bCRYPTOAEPPADDINGINFO = new BCrypt.BCRYPT_OAEP_PADDING_INFO(hash.Algorithm); uint num1 = NCrypt.NCryptDecrypt(key.Handle, cipherText, (int)cipherText.Length, ref bCRYPTOAEPPADDINGINFO, null, 0, out num, 4); if (num1 != 0) { throw new CryptographicException(string.Format("NCrypt.Decrypt() (plaintext buffer size) failed with status code:{0}", num1)); } byte[] numArray = new byte[num]; num1 = NCrypt.NCryptDecrypt(key.Handle, cipherText, (int)cipherText.Length, ref bCRYPTOAEPPADDINGINFO, numArray, num, out num, 4); if (num1 != 0) { throw new CryptographicException(string.Format("NCrypt.Decrypt() failed with status code:{0}", num1)); } return(numArray); }
void acquirePublicKey(PublicKey publicKey) { // do not load public key again if it is already loaded if (checkPublicKeyIsLoaded()) { return; } switch (publicKey.Oid.Value) { case AlgorithmOids.ECC: keyType = KeyType.EcDsa; break; case AlgorithmOids.RSA: keyType = KeyType.Rsa; break; case AlgorithmOids.DSA: keyType = KeyType.Dsa; break; default: throw new NotSupportedException("Public key algorithm is not supported"); } // regardless of public key algorithm and provider, load public keys to CNG provider for unification // and wider signature formats and padding support. Int32 hresult = NCrypt.NCryptOpenStorageProvider(out SafeNCryptProviderHandle phProvider, MSFT_KSP_NAME, 0); if (hresult != 0) { throw new CryptographicException(hresult); } Byte[] blob = publicKey.GetCryptBlob(); hresult = NCrypt.NCryptImportKey(phProvider, IntPtr.Zero, "PUBLICBLOB", IntPtr.Zero, out phPubKey, blob, blob.Length, 0); if (hresult != 0) { throw new CryptographicException(hresult); } }
public static byte[] DeriveKey(CngKey externalPubKey, CngKey privateKey, int keyBitLength, byte[] algorithmId, byte[] partyVInfo, byte[] partyUInfo, byte[] suppPubInfo) { uint num; byte[] numArray; using (ECDiffieHellmanCng eCDiffieHellmanCng = new ECDiffieHellmanCng(privateKey)) { using (SafeNCryptSecretHandle safeNCryptSecretHandle = eCDiffieHellmanCng.DeriveSecretAgreementHandle(externalPubKey)) { using (NCrypt.NCryptBuffer nCryptBuffer = new NCrypt.NCryptBuffer(8, algorithmId)) { using (NCrypt.NCryptBuffer nCryptBuffer1 = new NCrypt.NCryptBuffer(10, partyVInfo)) { using (NCrypt.NCryptBuffer nCryptBuffer2 = new NCrypt.NCryptBuffer(9, partyUInfo)) { using (NCrypt.NCryptBuffer nCryptBuffer3 = new NCrypt.NCryptBuffer(11, suppPubInfo)) { using (NCrypt.NCryptBufferDesc nCryptBufferDesc = new NCrypt.NCryptBufferDesc(new NCrypt.NCryptBuffer[] { nCryptBuffer, nCryptBuffer1, nCryptBuffer2, nCryptBuffer3 })) { uint num1 = NCrypt.NCryptDeriveKey(safeNCryptSecretHandle, "SP800_56A_CONCAT", nCryptBufferDesc, null, 0, out num, 0); if (num1 != 0) { throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", num1)); } byte[] numArray1 = new byte[num]; num1 = NCrypt.NCryptDeriveKey(safeNCryptSecretHandle, "SP800_56A_CONCAT", nCryptBufferDesc, numArray1, num, out num, 0); if (num1 != 0) { throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", num1)); } numArray = Arrays.LeftmostBits(numArray1, keyBitLength); } } } } } } } return(numArray); }
public static byte[] DeriveKey(CngKey externalPubKey, CngKey privateKey, int keyBitLength, byte[] algorithmId, byte[] partyVInfo, byte[] partyUInfo, byte[] suppPubInfo) { #if NET40 || NET461 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)); } } } } #elif NETSTANDARD1_4 throw new NotImplementedException("not yet"); #endif }
void acquirePrivateKeyFromKeyBuilder() { Int32 hresult = NCrypt.NCryptOpenStorageProvider(out SafeNCryptProviderHandle phProv, _keyInfo.ProviderName, 0); if (hresult != 0) { openLegacyPrivateKey(); return; } UInt32 dwFlags = 0; if (_keyInfo.MachineContext) { dwFlags = nCrypt2.NCRYPT_MACHINE_KEY_FLAG; } hresult = NCrypt.NCryptOpenKey(phProv, out phPrivKey, _keyInfo.KeyContainerName, (UInt32)_keyInfo.KeySpec, dwFlags); if (hresult != 0) { throw new CryptographicException(hresult); } isCng = true; }
public static void test() { string password = @"my password"; string secretpassword = @"my secret"; string salt = "my salt!"; // create secret key byte[] commonKey = NCrypt.CreateSeckey(secretpassword, System.Text.Encoding.UTF8.GetBytes(salt)); Console.WriteLine("commonKey : " + System.Convert.ToBase64String(commonKey)); // Encrypt byte[] vector = NCrypt.IV; string cipherText = NCrypt.Encrypt(commonKey, vector, password); Console.WriteLine("cipherText : " + cipherText); // Decrypt string planeText = NCrypt.Decrypt(commonKey, vector, cipherText); Console.WriteLine("planeText : " + planeText); }
public static byte[] Decrypt(byte[] cipherText, CngKey key, CngAlgorithm hash) { var paddingInfo = new BCrypt.BCRYPT_OAEP_PADDING_INFO(hash.Algorithm); uint plainTextByteSize; uint status = NCrypt.NCryptDecrypt(key.Handle, cipherText, cipherText.Length, ref paddingInfo, null, 0, out plainTextByteSize, BCrypt.BCRYPT_PAD_OAEP); if (status != BCrypt.ERROR_SUCCESS) { throw new CryptographicException(string.Format("NCrypt.Decrypt() (plaintext buffer size) failed with status code:{0}", status)); } var plainText = new byte[plainTextByteSize]; status = NCrypt.NCryptDecrypt(key.Handle, cipherText, cipherText.Length, ref paddingInfo, plainText, plainTextByteSize, out plainTextByteSize, BCrypt.BCRYPT_PAD_OAEP); if (status != BCrypt.ERROR_SUCCESS) { throw new CryptographicException(string.Format("NCrypt.Decrypt() failed with status code:{0}", status)); } return(plainText); }
internal override NCryptKeyOrCryptProviderSafeHandle CreateKey(string keyName, int keySize, Algorithm algorithm, bool overwrite, KeyUsage keyUsage, out KeySpec keySpec) { NCryptKeyOrCryptProviderSafeHandle keyHandle; var flags = overwrite ? NCryptCreatePersistedKeyFlags.NCRYPT_OVERWRITE_KEY_FLAG : NCryptCreatePersistedKeyFlags.NONE; var result = NCrypt.NCryptCreatePersistedKey(_storageProvider.Handle, out keyHandle, algorithm.Name, keyName, KeySpec.NONE, flags); if (result != SECURITY_STATUS.ERROR_SUCCESS) { throw new InvalidOperationException("Failed to generate a key."); } if (algorithm == Algorithm.RSA) { NCryptPropertyWriter.WriteUInt32(keyHandle, CngProperties.NCRYPT_LENGTH_PROPERTY, (uint)keySize); } NCryptPropertyWriter.WriteEnum(keyHandle, CngProperties.NCRYPT_EXPORT_POLICY_PROPERTY, CngExportPolicy.NCRYPT_ALLOW_EXPORT_FLAG); var finalizeResult = NCrypt.NCryptFinalizeKey(keyHandle, 0u); if (finalizeResult != SECURITY_STATUS.ERROR_SUCCESS) { throw new InvalidOperationException("Failed to finalize key."); } keySpec = KeySpec.NONE; return(keyHandle); }
public string GetSecurityDescriptorFromSecret(ProtectedSecret data) { if (data.Mode != 3) { throw new ArgumentException("The protected data was of the incorrect format"); } byte[] rawProtectedData = Convert.FromBase64String(data.Data); using SafeHGlobalHandle f = new SafeHGlobalHandle(rawProtectedData); var result = NCrypt.NCryptUnprotectSecret(out NCrypt.SafeNCRYPT_DESCRIPTOR_HANDLE dh, NCrypt.UnprotectSecretFlags.NCRYPT_SILENT_FLAG | NCrypt.UnprotectSecretFlags.NCRYPT_UNPROTECT_NO_DECRYPT, f.DangerousGetHandle(), f.Size, IntPtr.Zero, IntPtr.Zero, out IntPtr unprotectedData, out uint unprotectedDataSize); result.ThrowIfFailed(); IntPtr ruleStringHandle = IntPtr.Zero; try { result = NCrypt.NCryptGetProtectionDescriptorInfo( dh, IntPtr.Zero, NCrypt.ProtectionDescriptorInfoType.NCRYPT_PROTECTION_INFO_TYPE_DESCRIPTOR_STRING, out ruleStringHandle); result.ThrowIfFailed(); return(Marshal.PtrToStringUni(ruleStringHandle)); } finally { if (ruleStringHandle != IntPtr.Zero) { Marshal.FreeHGlobal(ruleStringHandle); } } }
public ProtectedSecret ProtectSecret(string secret, CommonSecurityDescriptor securityDescriptor) { this.licenseManager.ThrowOnMissingFeature(LicensedFeatures.DpapiNgSecretEncryption); var result = NCrypt.NCryptCreateProtectionDescriptor($"SDDL={securityDescriptor.GetSddlForm(AccessControlSections.All)}", 0, out NCrypt.SafeNCRYPT_DESCRIPTOR_HANDLE handle); result.ThrowIfFailed(); using (handle) { using SafeHGlobalHandle f = new SafeHGlobalHandle(Encoding.Unicode.GetBytes(secret)); result = NCrypt.NCryptProtectSecret(handle, NCrypt.ProtectFlags.NCRYPT_SILENT_FLAG, f.DangerousGetHandle(), f.Size, IntPtr.Zero, IntPtr.Zero, out IntPtr protectedData, out uint protectedDataSize); result.ThrowIfFailed(); using SafeHGlobalHandle d = new SafeHGlobalHandle(protectedData, protectedDataSize, true); return(new ProtectedSecret { Data = Convert.ToBase64String(d.GetBytes(0, (int)protectedDataSize)), Mode = 3 }); } }
protected override bool ReleaseHandle() { return(NCrypt.NCryptFreeObject(handle) == SECURITY_STATUS.ERROR_SUCCESS); }