本文整理汇总了C#中System.Security.Cryptography.RSACryptoServiceProvider.VerifyHash方法的典型用法代码示例。如果您正苦于以下问题:C# RSACryptoServiceProvider.VerifyHash方法的具体用法?C# RSACryptoServiceProvider.VerifyHash怎么用?C# RSACryptoServiceProvider.VerifyHash使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.RSACryptoServiceProvider
的用法示例。
在下文中一共展示了RSACryptoServiceProvider.VerifyHash方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MainAsync
static async Task MainAsync(string[] args)
{
var keyClient = new KeyVaultClient((authority, resource, scope) =>
{
var adCredential = new ClientCredential(applicationId, applicationSecret);
var authenticationContext = new AuthenticationContext(authority, null);
return authenticationContext.AcquireToken(resource, adCredential).AccessToken;
});
// Get the key details
var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784";
var key = await keyClient.GetKeyAsync(keyIdentifier);
var publicKey = Convert.ToBase64String(key.Key.N);
using (var rsa = new RSACryptoServiceProvider())
{
var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
rsa.ImportParameters(p);
var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
// Encrypt and Decrypt
var encryptedText = rsa.Encrypt(byteData, true);
var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText);
var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);
// Sign and Verify
var hasher = new SHA256CryptoServiceProvider();
var digest = hasher.ComputeHash(byteData);
var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
}
}
示例2: VerifyHash
// Hash and sign the data
public bool VerifyHash(RSAParameters sendersPublicKey, byte[] signatureToVerify, byte[] encryptedData)
{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider();
SHA1Managed hash = new SHA1Managed();
byte[] hashedData;
rsaCSP.ImportParameters(sendersPublicKey);
hashedData = hash.ComputeHash(encryptedData);
return rsaCSP.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signatureToVerify);
}
示例3: MatchesSignature
private bool MatchesSignature(byte[] key)
{
var signatureData = Convert.FromBase64String(Signature);
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportCspBlob(key);
var bodyData = Encoding.Unicode.GetBytes(Body);
using (var hasher = new SHA1Managed())
{
var hash = hasher.ComputeHash(bodyData);
return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signatureData);
}
}
}
示例4: VerifyHash
private static bool VerifyHash(Byte[] hash, string publicKey, string sig)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.PersistKeyInCsp = false;
try
{
provider.FromXmlString(publicKey);
}
catch (Exception)
{
throw new FeedReaderException("Could not read public key. It needs to have an xml format, as required by RSACryptoServiceProvider");
}
if (!provider.PublicOnly)
{
throw new FeedReaderException("The given public key contains both private and public parts. Please dont publish your private keys publicly.");
}
return provider.VerifyHash(hash, "sha512", Convert.FromBase64String(sig));
}
示例5: AllowUpdateIfIDontRequireChecksum
public void AllowUpdateIfIDontRequireChecksum()
{
const string NauUpdateFeed =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Feed RSASignature=""SIGNATURE"">
<Title>My application</Title>
<Link>http://myapp.com/</Link>
<Tasks>
<FileUpdateTask sha256-checksum=""invalidhashButWeCanNotKnowThatNow"" localPath=""test.dll"" updateTo=""remoteFile.dll"" hotswap=""true"">
<Description>update details</Description>
</FileUpdateTask>
<RegistryTask keyName=""asdf"" keyValue=""zsdfgafsdg"" valueKind=""String"">
</RegistryTask>
</Tasks>
</Feed>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(NauUpdateFeed);
// Support for different feed versions
XmlNode root = doc.SelectSingleNode(@"/Feed[version=""1.0""] | /Feed") ?? doc;
SHA512Managed sha = new SHA512Managed();
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(root.InnerXml));
RSACryptoServiceProvider provider = new RSACryptoServiceProvider(1024);
provider.PersistKeyInCsp = false;
var pubKey = provider.ToXmlString(false);
var sigBytes = provider.SignHash(hash, "sha512");
var sig = Convert.ToBase64String(sigBytes);
var update = NauUpdateFeed.Replace("SIGNATURE", sig);
bool isVerified = provider.VerifyHash(hash, "sha512", Convert.FromBase64String(sig));
Assert.IsTrue(isVerified);
var reader = new NAppUpdate.Framework.FeedReaders.NauXmlFeedReaderSigned();
reader.PublicKeys = new string[] { pubKey };
IList<IUpdateTask> updates = reader.Read(update);
Assert.IsTrue(updates != null && updates.Count == 2);
}
示例6: GetKeys
private static async Task<string> GetKeys(KeyVaultClient keyVaultClient)
{
var keyIdentifier = "keyIdentifier";
var textToEncrypt = "This is a test message";
var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
var hasher = new SHA256CryptoServiceProvider();
var digest = hasher.ComputeHash(byteData);
var signedResult = await keyVaultClient.SignAsync(
keyIdentifier, JsonWebKeySignatureAlgorithm.RS256, digest);
var isVerified = await keyVaultClient.VerifyAsync(keyIdentifier, "RS256", digest, signedResult.Result);
var keyResult = await keyVaultClient.GetKeyAsync(keyIdentifier);
var jsonWebKey = keyResult.Key.ToString();
var key = JsonConvert.DeserializeObject<JsonWebKey>(jsonWebKey);
var rsa = new RSACryptoServiceProvider();
var p = new RSAParameters() { Modulus = key.N, Exponent = key.E };
rsa.ImportParameters(p);
isVerified = rsa.VerifyHash(digest, "Sha256", signedResult.Result);
return null;
}
示例7: VerifyRSA
public static bool VerifyRSA(byte[] rsaModulus, byte[] exponent, byte[] data, byte[] sign)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters rsaPar = rsa.ExportParameters(false);
rsaPar.Modulus = rsaModulus;
rsaPar.Exponent = exponent;
rsa.ImportParameters(rsaPar);
bool resp;
resp = rsa.VerifyHash(data, "SHA256", sign);
//resp = rsa.VerifyData(data, "SHA256", sign);
return resp;
}
示例8: VerifyHash
/// <summary>
/// Verifies a signed hash against the unsigned version
/// </summary>
/// <param name="hash"> The unsigned hash (should be 64bit string) </param>
/// <param name="signedHash"> The signed hash (should be 64bit string) </param>
/// <param name="key"> The key to use in decryption </param>
/// <param name="hashIdentifer">The id of the hash algorithm used (default SHA1)</param>
/// <returns> True if it is verified, false otherwise </returns>
public static bool VerifyHash(string hash, string signedHash, string key, string hashIdentifer = "SHA1")
{
if (string.IsNullOrEmpty(hash))
throw new ArgumentNullException("input");
if (string.IsNullOrEmpty(signedHash))
throw new ArgumentNullException("signedHash");
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(key);
var inputArray = Convert.FromBase64String(signedHash);
var hashArray = Convert.FromBase64String(hash);
var result = rsa.VerifyHash(hashArray, CryptoConfig.MapNameToOID(hashIdentifer), inputArray);
rsa.Clear();
return result;
}
}
示例9: verifyotp
public bool verifyotp()
{
if (skipotp)
return true;
// check if is a fmuv2 and bootloader >= 4 else fail;
// 9 = fmuv2
// 5 = px4 1.x
if (board_type == 9) // &&up.bl_rev >= 4
{
try
{
// get the device sn
byte[] sn = __get_sn();
string line = "";
line="SN: ";
for (int s = 0; s < sn.Length; s += 1)
{
line += sn[s].ToString("X2");
}
print(line);
// 20 bytes - sha1
Array.Resize(ref sn, 20);
if (ByteArrayCompare(sn, new byte[] { 0x00, 0x23, 0x00, 0x30, 0x35, 0x32, 0x47, 0x18, 0x36, 0x34, 0x30, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }))
{
print("Libre bootloader");
libre = true;
}
object obj = new otp();
byte[] test = __read_otp();
ByteArrayToStructure(test, ref obj);
otp otp = (otp)obj;
print("id: " + otp.id_type.ToString("X"));
print("vid: " + otp.vid.ToString("X"));
print("pid: " + otp.pid.ToString("X"));
if (otp.h1 == 'P' &&
otp.h2 == 'X' &&
otp.h3 == '4' &&
otp.h4 == '\0')
{
// no vendor checks yet
byte[] sig = otp.signature;
line = "";
for (int s = 0; s < 512; s += 1)
{
line += test[s].ToString("X2");
if (s % 16 == 15)
{
print(line);
line = "";
}
}
/*
byte[] PEMbuffer = Convert.FromBase64String(@"");
*/
// RSACryptoServiceProvider rsa = DecodeRsaPrivateKey(PEMbuffer);
// RSAParameters rsapublic = rsa.ExportParameters(false);
foreach (var cert in certs)
{
byte[] pubpem = Convert.FromBase64String(cert.Value);
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(pubpem);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
bool valid = rsa.VerifyHash(sn, CryptoConfig.MapNameToOID("SHA1"), otp.signature);
if (valid)
{
print("Valid Key");
return true;
}
}
print("Invalid Key");
throw new InvalidKeyException("Invalid Board");
}
else
{
print("Failed Header Check");
throw new FormatException("Failed Header Check");
}
//.........这里部分代码省略.........
示例10: VerifyHashNullSignature
public void VerifyHashNullSignature ()
{
byte[] hash = new byte [20];
rsa = new RSACryptoServiceProvider (minKeySize);
rsa.VerifyHash (hash, "1.3.14.3.2.26", null);
}
示例11: VerifyHashInvalidHashLength
public void VerifyHashInvalidHashLength ()
{
byte[] hash = new byte [19];
byte[] sign = new byte [(minKeySize << 3)];
rsa = new RSACryptoServiceProvider (minKeySize);
rsa.VerifyHash (hash, "1.3.14.3.2.26", sign);
// note: invalid signature length doesn't throw an exception (but returns false)
}
示例12: SignHashNullOID
public void SignHashNullOID ()
{
byte [] hash = new byte [20];
rsa = new RSACryptoServiceProvider (minKeySize);
byte[] signature = rsa.SignHash (hash, null);
Assert ("Null OID == SHA1", rsa.VerifyHash (hash, "1.3.14.3.2.26", signature));
Assert ("Null OID", rsa.VerifyHash (hash, null, signature));
}
示例13: VerifyHash
/// <summary>
/// Verifies that a digital signature is valid by determining the hash value
/// in the signature using the provided public key and comparing it to the provided hash value.
/// </summary>
/// <param name="hash">hash to test</param>
/// <param name="signedHash">already signed hash (in base64 form)</param>
/// <param name="publicKey">signature (in base64 form)</param>
/// <returns>true if the signature is valid; otherwise, false.</returns>
public bool VerifyHash(string hash, string signedHash, string publicKey)
{
using (var RSA = new RSACryptoServiceProvider())
{
var encoder = new UTF8Encoding();
var toVerify = encoder.GetBytes(hash);
var signed = Convert.FromBase64String(signedHash);
try
{
RSA.ImportCspBlob(Convert.FromBase64String(publicKey));
return RSA.VerifyHash(toVerify, CryptoConfig.MapNameToOID("SHA256"), signed);
}
catch (CryptographicException e)
{
Debug.Fail(e.Message);
return false;
}
finally
{
RSA.PersistKeyInCsp = false;
}
}
}
示例14: VerifyHash
/// <summary>
/// Verifies a signed hash against the unsigned version
/// </summary>
/// <param name="Hash">The unsigned hash (should be 64bit string)</param>
/// <param name="SignedHash">The signed hash (should be 64bit string)</param>
/// <param name="Key">The key to use in decryption</param>
/// <returns>True if it is verified, false otherwise</returns>
public override bool VerifyHash(string Hash, string SignedHash, string Key)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Key), "Key");
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Hash), "Hash");
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(SignedHash), "SignedHash");
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(Key);
byte[] InputArray = SignedHash.FromBase64();
byte[] HashArray = Hash.FromBase64();
bool Result = RSA.VerifyHash(HashArray, CryptoConfig.MapNameToOID("SHA1"), InputArray);
RSA.Clear();
return Result;
}
}
示例15: RunBasicScenario
static bool RunBasicScenario(Session session)
{
try
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(session))
{
Log.Comment("Importing RSA public key");
rsa.ImportParameters(RsaSignatureTestData.GetKeyParameters());
Log.Comment("RSA key size: " + rsa.KeySize);
Log.Comment("Verifying SHA-1 signature");
bool verified = rsa.VerifyHash(RsaSignatureTestData.GetHashValue(), MechanismType.SHA_1, RsaSignatureTestData.GetSignatureValue());
Log.Comment("Complete verifying SHA-1 signature");
if (!verified)
{
Log.Comment("Signature failed to verify - fail.");
return false;
}
#if DEFINED_BASE64TRANSFORM
byte[] signature = RsaSignatureTestData.GetSignatureValue();
string before = Convert.ToBase64String(signature);
byte[] after = ConvertToByteArray(before);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, new FromBase64Transform(), CryptoStreamMode.Write);
cs.Write(after, 0, after.Length);
cs.Close();
if (!Compare(ms.ToArray(), signature))
{
Log.Comment("Base64 Transform failed.");
return false;
}
#endif
}
}
catch (Exception e)
{
Log.Comment("Fail - got an exception");
Log.Exception("",e);
return false;
}
return true;
}