/// <summary> /// Helper for RSACryptoServiceProvider.VerifyData/VerifyHash apis. /// </summary> public static bool VerifySign(SafeProvHandle hProv, SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, byte[] signature) { switch (calgKey) { case CALG_RSA_SIGN: signature = signature.CloneByteArray(); Array.Reverse(signature); break; case CALG_DSS_SIGN: throw new PlatformNotSupportedException(); default: throw new InvalidOperationException(); } using (SafeHashHandle hHash = hProv.CreateHashHandle(hash, calgHash)) { bool verified = Interop.CryptVerifySignature(hHash, signature, signature.Length, hKey, null, CryptSignAndVerifyHashFlags.None); return verified; } }
/// <summary> /// Helper for RSACryptoServiceProvider.SignData/SignHash apis. /// </summary> public static byte[] SignValue(SafeProvHandle hProv, SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash) { using (SafeHashHandle hHash = hProv.CreateHashHandle(hash, calgHash)) { int cbSignature = 0; if (!Interop.CryptSignHash(hHash, (KeySpec)keyNumber, null, CryptSignAndVerifyHashFlags.None, null, ref cbSignature)) { int hr = Marshal.GetHRForLastWin32Error(); throw hr.ToCryptographicException(); } byte[] signature = new byte[cbSignature]; if (!Interop.CryptSignHash(hHash, (KeySpec)keyNumber, null, CryptSignAndVerifyHashFlags.None, signature, ref cbSignature)) { int hr = Marshal.GetHRForLastWin32Error(); throw hr.ToCryptographicException(); } switch (calgKey) { case CALG_RSA_SIGN: Array.Reverse(signature); break; case CALG_DSS_SIGN: throw new PlatformNotSupportedException(); default: throw new InvalidOperationException(); } return signature; } }