private static void TestSignVerifyDataRoundTrip(byte[] message, HashAlgorithmName hashAlgorithm, RSASignaturePadding paddingMode, int expectedSignatureLength) { using (RSA rsa = new RSACng()) { byte[] signature = rsa.SignData(message, hashAlgorithm, paddingMode); // RSACng.SignHash() is intentionally non-deterministic so we can verify that we got back a signature of the right length // but nothing about the contents. Assert.Equal(expectedSignatureLength, signature.Length); bool verified = rsa.VerifyData(message, signature, hashAlgorithm, paddingMode); Assert.True(verified); } }
/// <summary> /// Generates signature based on RSA PKCS#v1.5 scheme using a specified CNG Key. /// </summary> /// <param name="dataToSign">Text to sign.</param> /// <param name="rsaCngProvider">RSA CNG Provider.</param> /// <returns>Signature</returns> private byte[] RSASignHashedData(byte[] dataToSign, RSACng rsaCngProvider) { Debug.Assert((dataToSign != null) && (dataToSign.Length != 0)); Debug.Assert(rsaCngProvider != null); return rsaCngProvider.SignData(dataToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); }
private static void TestSignAndVerifyDataFromStream(int messageSize) { RSASignaturePadding padding = RSASignaturePadding.Pkcs1; byte[] message = new byte[messageSize]; byte b = 5; for (int i = 0; i < message.Length; i++) { message[i] = b; b = (byte)((b << 4) | (i & 0xf)); } byte[] hash = SHA1.Create().ComputeHash(message); Stream stream = new MemoryStream(message); using (RSA rsa = new RSACng()) { byte[] signature = rsa.SignData(stream, HashAlgorithmName.SHA1, padding); // Since the unique codepath being tested here is HashData(Stream...), the interesting test is to see if HashData(Stream...) // computed the right hash. The easiest way to test that is to compute the hash ourselves and call VerifyHash. bool verified = rsa.VerifyHash(hash, signature, HashAlgorithmName.SHA1, padding); Assert.True(verified); stream = new MemoryStream(message); verified = rsa.VerifyData(stream, signature, HashAlgorithmName.SHA1, padding); Assert.True(verified); } }