本文整理汇总了C#中System.Security.Cryptography.DSACryptoServiceProvider类的典型用法代码示例。如果您正苦于以下问题:C# DSACryptoServiceProvider类的具体用法?C# DSACryptoServiceProvider怎么用?C# DSACryptoServiceProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DSACryptoServiceProvider类属于System.Security.Cryptography命名空间,在下文中一共展示了DSACryptoServiceProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DSASignHash
/// <summary>
/// 数字签名处理.
/// </summary>
/// <param name="HashToSign"></param>
/// <param name="DSAKeyInfo"></param>
/// <param name="HashAlg"></param>
/// <returns></returns>
public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo, string HashAlg)
{
try
{
//Create a new instance of DSACryptoServiceProvider.
DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
//Import the key information.
DSA.ImportParameters(DSAKeyInfo);
//Create an DSASignatureFormatter object and pass it the
//DSACryptoServiceProvider to transfer the private key.
DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);
//Set the hash algorithm to the passed value.
DSAFormatter.SetHashAlgorithm(HashAlg);
//Create a signature for HashValue and return it.
return DSAFormatter.CreateSignature(HashToSign);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
示例2: ChangeNick
public bool ChangeNick(string oldnick, string newnick, byte[] newnickhashed)
{
bool result = false;
Chat instance = new Chat();
instance.Deserialiser();
User user = instance.SearchNick(oldnick);
if (user != null) //si l'utilisateur actuel existe
{
if (instance.SearchNick(newnick) == null) //si le nouveau login choisi est bon
{
ASCIIEncoding encoding = new ASCIIEncoding();
DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider();
mycrypto.ImportParameters(user.Publickey);
if (mycrypto.VerifyData(encoding.GetBytes(newnick), newnickhashed)) //verification de la provenance du message
{
instance.RemoveUser(user);
user.Login = newnick;
instance.AddUser(user);
instance.Serialiser();
result = true;
}
}
}
return result;
}
示例3: DoTest
public static void DoTest()
{
Console.WriteLine("使用 DSACryptoServiceProvider 类创建哈希值的数字签名,然后验证签名的例子!");
// 创建一个 DSA 算法的加密服务提供程序 (CSP) 实现的包装对象.
DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
// 需要被签名的数据.
byte[] HashValue = { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };
Console.WriteLine("初始 Hash 数据.");
ByteArrayOutput.Print(HashValue);
// 签名处理.
byte[] SignedHashValue = DSASignHash(HashValue, DSA.ExportParameters(true), "SHA1");
Console.WriteLine("使用私钥签名的数据.");
ByteArrayOutput.Print(SignedHashValue);
// 验证签名.
if (DSAVerifyHash(HashValue, SignedHashValue, DSA.ExportParameters(false), "SHA1"))
{
Console.WriteLine("使用公钥验证 签名是有效的!");
}
else
{
Console.WriteLine("使用公钥验证 签名无效.");
}
}
示例4: DSAVerifyHash
//-------------------------------------------------------------------
public static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue,
DSAParameters DSAKeyInfo, string HashAlg)
{
bool verified = false;
try
{
// Создаем новый экземпляр класса DSACryptoServiceProvider.
using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
{
// Импортируем ключи
DSA.ImportParameters(DSAKeyInfo);
//Создаем объект класса DSASignatureFormatter и передаем ему DSACryptoServiceProvider закрытый ключ
DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);
// Устанавливаем алгоритм шифрования
DSADeformatter.SetHashAlgorithm(HashAlg);
// Сверяем подписи и возвращаем результат
verified = DSADeformatter.VerifySignature(HashValue, SignedHashValue);
}
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
return verified;
}
示例5: verify
public bool verify(byte[] sig)
{
m_cs.Close();
DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
DSA.ImportParameters(m_DSAKeyInfo);
DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);
DSADeformatter.SetHashAlgorithm("SHA1");
long i = 0;
long j = 0;
byte[] tmp;
//This makes sure sig is always 40 bytes?
if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
{
long i1 = (sig[i++] << 24) & 0xff000000;
long i2 = (sig[i++] << 16) & 0x00ff0000;
long i3 = (sig[i++] << 8) & 0x0000ff00;
long i4 = (sig[i++]) & 0x000000ff;
j = i1 | i2 | i3 | i4;
i += j;
i1 = (sig[i++] << 24) & 0xff000000;
i2 = (sig[i++] << 16) & 0x00ff0000;
i3 = (sig[i++] << 8) & 0x0000ff00;
i4 = (sig[i++]) & 0x000000ff;
j = i1 | i2 | i3 | i4;
tmp = new byte[j];
Array.Copy(sig, i, tmp, 0, j);
sig = tmp;
}
return DSADeformatter.VerifySignature(m_sha1, sig);
}
示例6: DSASignHash
//-------------------------------------------------------------------------
// Шифруем закрытым ключем Хеш-таблицу
public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo,
string HashAlg)
{
byte[] sig = null;
try
{
// Создаем новыый экземпляр класса
using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
{
// Импортируем ключи, в данном случае закрытый ключ
DSA.ImportParameters(DSAKeyInfo);
// Создаем объект класса DSASignatureFormatter и передаем ему DSACryptoServiceProvider закрытый ключ
DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);
// Устанавливаем алгоритм шифрования
DSAFormatter.SetHashAlgorithm(HashAlg);
// Создаем подпись для хеш-таблицы и возвращаем ее значение
sig = DSAFormatter.CreateSignature(HashToSign);
}
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
return sig;
}
示例7: Sign
void Sign(String[] args)
{
if (args.Length != 1)
{
Usage();
return;
}
try
{
String productCode = args[0];
byte[] pcode = StringUtils.Str2Bytes(productCode);
for (int i = 0; i < 1; ++i)
{
DSAParameters dsap = CryptographyParams.DSAP;
dsap.X = X;
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(512);
dsa.ImportParameters(dsap);
String oid = CryptoConfig.MapNameToOID(LicensingStrings.SHA1);
byte[] acode = dsa.SignHash(pcode, oid);
String activationCode = StringUtils.Bytes2Str(acode);
System.Console.Out.WriteLine(activationCode);
}
}
catch (Exception e)
{
System.Console.Out.WriteLine("Error: {0}\n", e.Message);
}
}
示例8: DigitalSignatureAlgorithm_compare_parameters_generation_with_original_Pidgin_OffTheRecord_data
public void DigitalSignatureAlgorithm_compare_parameters_generation_with_original_Pidgin_OffTheRecord_data()
{
// Arrange
const string p =
"AEC0FBB4CEA96EF8BDD0E91D1BA2F6641B6535CBDA8D739CC2898FE7B472865AB60AD2B1BAA2368603C7439E63BC2F2F33D422E70173F70DB738DF5979EAEAF3CAC343CBF711960E16786703C80DF0734D8330DC955DA84B521DAB5C729202F1244D805E6BF2CC7A7142CAD74BE5FFFC14B9CCB6CABB7DB10A8F2DDB4E82383F";
const string q = "A2A2BC20E2D94C44C63608479C79068CE7914EF3";
const string g =
"69B9FC5A73F3F6EA3A86F8FA3A203F42DACDC3A1516002025E5765A9DCB975F348ACBBA2116230E19CE3FC5256546FD168A2940809BDA8655771967E9CD90AF44D2C20F97F448494213A775E23607F33C255A9A74E2A5FC7B4D50BAD024D7EFAC282E67332D51A5F69239011FE058D7E75E97A788FBD5B3BAD796B2C6D8C6C3E";
const string y =
"9931144F3059D92FCB2AAC03B130DAE43ED1EF30AA2F0E670C3974C3E80C7110D1A60210F92479D7F640C20E1F16E01B4A72FF8D45443B01EBE2D67DF49791CAC6191B159AC39446EB6A2EA597B6B678CC3157AECEAB12A804CF0772068A942EC819138EDD6005620FE746522FF408BBC8211ABD9D6016AA46EEC87F3F04CFA4";
const string x = "48BFDA215C31A9F0B226B3DB11F862450A0F30DA"; /* private key */
// Act
var param = new DSAParameters();
param.X = General.StringToByteArray(x);
param.P = General.StringToByteArray(p);
param.Q = General.StringToByteArray(q);
param.G = General.StringToByteArray(g);
param.Y = General.StringToByteArray(y);
var dsa = new DSACryptoServiceProvider(1024);
dsa.ImportParameters(param);
DSAParameters output = dsa.ExportParameters(true);
// Assert
param.X.SequenceEqual(output.X).Should().BeTrue();
param.P.SequenceEqual(output.P).Should().BeTrue();
param.Q.SequenceEqual(output.Q).Should().BeTrue();
param.G.SequenceEqual(output.G).Should().BeTrue();
param.Y.SequenceEqual(output.Y).Should().BeTrue();
}
示例9: GetSignature
/// <summary>
/// Gets the signature.
/// </summary>
/// <param name="key">The key data bytes.</param>
/// <returns></returns>
public override byte[] GetSignature(IEnumerable<byte> key)
{
var data = key.ToArray();
//using (var sha1 = new Renci.SshNet.Security.Cryptography.SHA1Hash())
using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
{
using (var cs = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, sha1, System.Security.Cryptography.CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
}
var dsaKeyInfo = new System.Security.Cryptography.DSAParameters();
dsaKeyInfo.X = this._privateKey.TrimLeadingZero().ToArray();
dsaKeyInfo.P = this._p.TrimLeadingZero().ToArray();
dsaKeyInfo.Q = this._q.TrimLeadingZero().ToArray();
dsaKeyInfo.G = this._g.TrimLeadingZero().ToArray();
using (var DSA = new System.Security.Cryptography.DSACryptoServiceProvider())
{
DSA.ImportParameters(dsaKeyInfo);
var DSAFormatter = new DSASignatureFormatter(DSA);
DSAFormatter.SetHashAlgorithm("SHA1");
var signature = DSAFormatter.CreateSignature(sha1);
return new SignatureKeyData
{
AlgorithmName = this.Name,
Signature = signature,
}.GetBytes().ToArray();
}
}
}
示例10: TestMethodSendPrivateMessage
public void TestMethodSendPrivateMessage()
{
ASCIIEncoding encoding = new ASCIIEncoding();
DSACryptoServiceProvider mycryptoC = new DSACryptoServiceProvider();
DSAParameters publickeyC = mycryptoC.ExportParameters(false);
DSACryptoServiceProvider mycryptoW = new DSACryptoServiceProvider();
DSAParameters publickeyW = mycryptoW.ExportParameters(false);
byte[] hashC = mycryptoC.SignData(encoding.GetBytes("Cuddy"));
byte[] hashW = mycryptoW.SignData(encoding.GetBytes("Wilson"));
ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();
a.Register("Cuddy", "iluvhouse", hashC, publickeyC.Counter, publickeyC.G, publickeyC.J, publickeyC.P, publickeyC.Q, publickeyC.Seed, publickeyC.X, publickeyC.Y);
a.Register("Wilson", "ihatehouse", hashW, publickeyW.Counter, publickeyW.G, publickeyW.J, publickeyW.P, publickeyW.Q, publickeyW.Seed, publickeyW.X, publickeyW.Y);
string message = "je suis jalouse de Cameron";
byte[] messagesigned = mycryptoC.SignData(encoding.GetBytes(message));
Assert.AreEqual(true,a.SendPrivateMessage("Cuddy", "Wilson", message, messagesigned));
Assert.AreEqual(false, a.SendPrivateMessage("Cuddy", "Foreman", message, messagesigned));
File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
}
示例11: TestMethodReceivePrivateMessage
public void TestMethodReceivePrivateMessage()
{
ASCIIEncoding encoding = new ASCIIEncoding();
DSACryptoServiceProvider mycryptoC = new DSACryptoServiceProvider();
DSAParameters publickeyC = mycryptoC.ExportParameters(false);
DSACryptoServiceProvider mycryptoW = new DSACryptoServiceProvider();
DSAParameters publickeyW = mycryptoW.ExportParameters(false);
byte[] hashC = mycryptoC.SignData(encoding.GetBytes("Cuddy"));
byte[] hashW = mycryptoW.SignData(encoding.GetBytes("Wilson"));
ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient();
a.Register("Cuddy", "iluvhouse", hashC, publickeyC.Counter, publickeyC.G, publickeyC.J, publickeyC.P, publickeyC.Q, publickeyC.Seed, publickeyC.X, publickeyC.Y);
a.Register("Wilson", "ihatehouse", hashW, publickeyW.Counter, publickeyW.G, publickeyW.J, publickeyW.P, publickeyW.Q, publickeyW.Seed, publickeyW.X, publickeyW.Y);
string message = "je suis jalouse de Cameron";
byte[] messagesigned = mycryptoC.SignData(encoding.GetBytes(message));
a.SendPrivateMessage("Cuddy", "Wilson", message, messagesigned);
UnitTest.ServiceReference1.Message[] b = a.ReceivePrivateMessage("Wilson", hashW);
Assert.AreEqual("Cuddy", b[0].Auteur); //j'avoue les test sont moisi... mais je voulais juste verifier si le retour par une classe implemente dans le webservice etait possible
Assert.AreEqual("je suis jalouse de Cameron", b[0].Text);
File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\Message_serialization.xml");
File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\DevServer\\10.0\\User_serialization.xml");
}
示例12: DSAVerifyHash
private static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters publickeyinfo, string HashAlg)
{
bool verified = false;
try
{
//Create a new instance of DSACryptoServiceProvider
using(DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
{
//Import the key information
dsa.ImportParameters(publickeyinfo);
// Create an DSASignatureDeformatter object and pass it the DSACryptoServiceProvider to transfer the private key.
//DSASignatureDeformatter dsaDeformatter = new DSASignatureDeformatter(dsa);
//Set the hash algorithm to the passed value.
//dsaDeformatter.SetHashAlgorithm(HashAlg);
//Verify signature and return the result
//Verify hashed files //Verify hashed data
verified = dsa.VerifyData(HashValue, SignedHashValue); //dsaDeformatter.VerifySignature(HashValue, SignedHashValue);
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
return verified;
}
示例13: DecodePublicKey
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal)
{
if (oid.Value == Oids.Ecc)
{
return DecodeECDsaPublicKey((CertificatePal)certificatePal);
}
int algId = OidInfo.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
switch (algId)
{
case AlgId.CALG_RSA_KEYX:
case AlgId.CALG_RSA_SIGN:
{
byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.CNG_RSA_PUBLIC_KEY_BLOB, encodedKeyValue);
CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.GenericPublicBlob);
return new RSACng(cngKey);
}
#if !NETNATIVE
case AlgId.CALG_DSS_SIGN:
{
byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters);
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
dsa.ImportCspBlob(keyBlob);
return dsa;
}
#endif
default:
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
}
示例14: DecodePublicKey
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters)
{
int algId = OidInfo.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
switch (algId)
{
case AlgId.CALG_RSA_KEYX:
case AlgId.CALG_RSA_SIGN:
{
byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.RSA_CSP_PUBLICKEYBLOB, encodedKeyValue);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportCspBlob(keyBlob);
return rsa;
}
case AlgId.CALG_DSS_SIGN:
{
byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters);
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
dsa.ImportCspBlob(keyBlob);
return dsa;
}
default:
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
}
示例15: init
public void init(int key_size)
{
// KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
// keyGen.initialize(key_size, new SecureRandom());
// KeyPair pair = keyGen.generateKeyPair();
// PublicKey pubKey=pair.getPublic();
// PrivateKey prvKey=pair.getPrivate();
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(key_size);
DSAParameters DSAKeyInfo = dsa.ExportParameters(true);
// x=((DSAPrivateKey)prvKey).getX().toByteArray();
// y=((DSAPublicKey)pubKey).getY().toByteArray();
//
// DSAParams _params=((DSAKey)prvKey).getParams();
// p=_params.getP().toByteArray();
// q=_params.getQ().toByteArray();
// g=_params.getG().toByteArray();
x = DSAKeyInfo.X;
y = DSAKeyInfo.Y;
p = DSAKeyInfo.P;
q = DSAKeyInfo.Q;
g = DSAKeyInfo.G;
}