/// <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; } }
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; }
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); } }
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); }
//------------------------------------------------------------------- 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; }
//------------------------------------------------------------------------- // Шифруем закрытым ключем Хеш-таблицу 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; }
/// <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(); } } }
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(); }
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; }
public byte[] sign() { m_cs.Close(); DSACryptoServiceProvider DSA = new DSACryptoServiceProvider(); DSA.ImportParameters(m_DSAKeyInfo); DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA); DSAFormatter.SetHashAlgorithm("SHA1"); byte[] sig = DSAFormatter.CreateSignature(m_sha1); return sig; }
/// <summary> /// Create a public key block from a private key. /// </summary> /// <param name="privateKey">The <see cref="DSA" /> PrivateKey.</param> /// <returns>The <see cref="DSACryptoServiceProvider" /> PublicKey.</returns> public static DSACryptoServiceProvider make_pubkey(DSA privateKey) { var publicKey = new DSACryptoServiceProvider(1024); publicKey.ImportParameters(privateKey.ExportParameters(false)); if (!publicKey.PublicOnly) { publicKey.Dispose(); throw new Exception("PublicKey contains PrivateKey information, cancelling."); } return publicKey; }
internal PrivateKey(DSAParameters dsaParameters) { privateKey = dsaParameters; var dsa = new DSACryptoServiceProvider(1024); dsa.ImportParameters(privateKey); PublicKey = dsa.ExportParameters(false); PublicKeyAsMPI = MultiPrecisionInteger.ByteArrayToMpi(PublicKey.P) .Concat(MultiPrecisionInteger.ByteArrayToMpi(PublicKey.Q)) .Concat(MultiPrecisionInteger.ByteArrayToMpi(PublicKey.G)) .Concat(MultiPrecisionInteger.ByteArrayToMpi(PublicKey.Y)) .ToArray(); }
public bool ReceiveKey(byte[] pseudo,byte[] hash, DSAParameters key ) { bool ret = false; ASCIIEncoding codage = new ASCIIEncoding(); DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider(); mycrypto.ImportParameters(key); if(mycrypto.VerifyData(pseudo,hash)) { string nick = codage.GetString(pseudo); _clients.Add(nick, key); ret = true; } return ret; }
public override void Read(System.IO.BinaryReader stream) { //Read P, Q, G, and Y. DSAParameters parameters = new DSAParameters(); parameters.P = ReadBytes(stream); parameters.Q = ReadBytes(stream); parameters.G = ReadBytes(stream); parameters.Y = ReadBytes(stream); //Set up the new DSA provider. DSACryptoServiceProvider dsa = new System.Security.Cryptography.DSACryptoServiceProvider(); dsa.ImportParameters(parameters); //Initialize the algorithm. InitializeAlgorithm(dsa); }
public string CreateSignatureForStream(Stream stream) { byte[] hash = (new SHA1Managed()).ComputeHash(stream);//for file or text try { using (var dsaCryptoProvider = new DSACryptoServiceProvider()) { dsaCryptoProvider.ImportParameters(PrivateKey); var dsaFormatter = new DSASignatureFormatter(dsaCryptoProvider); dsaFormatter.SetHashAlgorithm("SHA1"); byte[] signature = dsaFormatter.CreateSignature(hash); return ByteArrayToString(signature); } } catch (CryptographicException e) { return null; } }
public bool ReceiveMessage(byte[] mess, byte[] hashMess, string pseudo) { DSAParameters key; ASCIIEncoding codage = new ASCIIEncoding(); DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider(); bool ret = false; if (_clients.TryGetValue(pseudo,out key)) { mycrypto.ImportParameters(key); if (mycrypto.VerifyData(mess, hashMess)) { Console.WriteLine(pseudo + " a ecrit: " + codage.GetString(mess)); ret = true; } } return ret; }
private void ImportPrivateKey (X509Certificate certificate, CspParameters cspParams) { RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider; if (rsaCsp != null) { if (rsaCsp.PublicOnly) return; RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams); csp.ImportParameters(rsaCsp.ExportParameters(true)); csp.PersistKeyInCsp = true; return; } RSAManaged rsaMng = certificate.RSA as RSAManaged; if (rsaMng != null) { if (rsaMng.PublicOnly) return; RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams); csp.ImportParameters(rsaMng.ExportParameters(true)); csp.PersistKeyInCsp = true; return; } DSACryptoServiceProvider dsaCsp = certificate.DSA as DSACryptoServiceProvider; if (dsaCsp != null) { if (dsaCsp.PublicOnly) return; DSACryptoServiceProvider csp = new DSACryptoServiceProvider(cspParams); csp.ImportParameters(dsaCsp.ExportParameters(true)); csp.PersistKeyInCsp = true; } }
static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); DSAParameters dsap = new DSAParameters (); try { if ((blob [offset] != 0x07) || // PRIVATEKEYBLOB (0x07) (blob [offset + 1] != 0x02) || // Version (0x02) (blob [offset + 2] != 0x00) || // Reserved (word) (blob [offset + 3] != 0x00) || (ToUInt32LE (blob, offset + 8) != 0x32535344)) // DWORD magic throw new CryptographicException ("Invalid blob header"); int bitlen = ToInt32LE (blob, offset + 12); int bytelen = bitlen >> 3; int pos = offset + 16; dsap.P = new byte [bytelen]; Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen); Array.Reverse (dsap.P); pos += bytelen; dsap.Q = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20); Array.Reverse (dsap.Q); pos += 20; dsap.G = new byte [bytelen]; Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen); Array.Reverse (dsap.G); pos += bytelen; dsap.X = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.X, 0, 20); Array.Reverse (dsap.X); pos += 20; dsap.Counter = ToInt32LE (blob, pos); pos += 4; dsap.Seed = new byte [20]; Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20); Array.Reverse (dsap.Seed); pos += 20; } catch (Exception e) { throw new CryptographicException ("Invalid blob.", e); } #if INSIDE_CORLIB && MOBILE DSA dsa = (DSA)DSA.Create (); dsa.ImportParameters (dsap); #else DSA dsa = null; try { dsa = (DSA)DSA.Create (); dsa.ImportParameters (dsap); } catch (CryptographicException ce) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 try { CspParameters csp = new CspParameters (); csp.Flags = CspProviderFlags.UseMachineKeyStore; dsa = new DSACryptoServiceProvider (csp); dsa.ImportParameters (dsap); } catch { // rethrow original, not the later, exception if this fails throw ce; } } #endif return dsa; }
public static Boolean Test(Session session) { Boolean bRes = true; //String xml1, xml2, xml3; //String sign1, sign2, sign3; byte[] hashval = new byte[20]; for (int i = 0; i < hashval.Length; i++) hashval[i] = (Byte)i; DSACryptoServiceProvider dsa1 = new DSACryptoServiceProvider(session); DSACryptoServiceProvider dsa2 = new DSACryptoServiceProvider(session); //DSACryptoServiceProvider dsa3 = new DSACryptoServiceProvider(session); DSAParameters dsaParams = dsa1.ExportParameters(true); byte[] sig1 = dsa1.SignHash(hashval, MechanismType.SHA_1); //sign1 = (Convert.ToBase64String(sig1)); //xml1 = dsa1.ToXmlString(true); dsa2.ImportParameters(dsaParams); //dsa2.FromXmlString(xml1); //xml2 = (dsa2.ToXmlString(true)); //xml3 = (dsa3.ToXmlString(true)); byte[] sig2 = dsa2.SignHash(hashval, MechanismType.SHA_1); //sign2 = (Convert.ToBase64String(sig2)); //dsa3.HashAlgorithm = MechanismType.SHA_1; //byte[] sig3 = dsa3.SignHash(hashval); //sign3 = (Convert.ToBase64String(sig3)); //if ((xml1 != xml2) || (xml2 != xml3)) //{ // Log.Comment("WRONG : ToXmlString results are different"); // Log.Comment("XML1:\n" + xml1); // Log.Comment("XML2:\n" + xml2); // Log.Comment("XML3:\n" + xml3); // bRes = false; //} //Log.Comment(xml1); /* if ( (sign1!=sign2) || (sign2!=sign3) ) { Log.Comment("WRONG : signatures are different"); Log.Comment("First: " + sign1); Log.Comment("Second: " + sign2); Log.Comment("Third: " + sign3); bRes = false; } */ //Log.Comment("\n" + sign1); if (!dsa1.VerifyHash(hashval, MechanismType.SHA_1, sig2)) { Log.Comment("WRONG : Signature check (1) failed"); bRes = false; } if (!dsa2.VerifyHash(hashval, MechanismType.SHA_1, sig1)) { Log.Comment("WRONG : Signature check (1) failed"); bRes = false; } //if (!dsa3.VerifyHash(hashval, sig1)) //{ // Log.Comment("WRONG : Signature check (1) failed"); // bRes = false; //} return bRes; }
public void ExportCspBlob_MissingPrivateKey_PublicOnly () { dsa = new DSACryptoServiceProvider (minKeySize); DSAParameters dsap = AllTests.GetKey (false); dsa.ImportParameters (dsap); byte[] pubkey = dsa.ExportCspBlob (false); Assert.AreEqual ("06-02-00-00-00-22-00-00-44-53-53-31-00-04-00-00-D3-7B-C6-ED-3F-72-44-BD-22-7D-F2-D4-62-FE-7C-E3-75-8F-9C-DE-69-C0-3A-0C-E6-26-5A-46-3D-EF-0D-90-20-C6-F6-45-7C-73-E8-B9-7D-86-27-F7-97-76-C8-1C-8E-8B-CE-26-93-E6-21-53-20-93-58-25-45-1C-46-66-17-10-98-03-96-D0-E5-C8-30-80-72-B6-49-B3-82-95-B3-8D-3A-A5-E5-60-C6-42-3A-33-70-67-30-C5-1C-32-D9-EB-CF-C1-36-B3-F3-24-07-39-86-0D-E9-12-80-73-26-A7-8C-8B-8A-40-AA-51-43-8F-20-DE-D2-9C-F3-B3-51-73-83-62-A0-11-C9-50-93-E1-F0-64-BE-D0-9E-E0-5B-13-47-AA-56-65-62-47-FD-3A-94-B7-1B-E5-35-95-86-14-64-C0-D6-07-96-4C-55-1E-0A-4C-10-C2-B5-E6-FB-74-F9-A5-72-E0-42-96-62-0B-EF-B7-52-36-7D-E3-01-12-85-E6-FE-92-75-40-C2-A6-D0-9D-16-6F-C1-C7-A7-DF-48-80-A2-5D-A0-FD-84-BE-06-AC-CB-32-22-82-D2-D7-7C-69-FC-BC-94-78-2B-11-5B-1C-1E-AF-DB-7A-AA-31-F3-D8-74-84-00-3F-9D-B9-4B-B2-68-7E-F4-1B-C2-83-73-21-78-0F-D5-0F-B0-EB-76-41-F1-23-7A-6A-78-CC-4F-3D-BB-C7-03-89-C4-0B-66-86-80-D5-AA-34-E8-14-71-F9-29-BE-B9-EE-34-B1-5F-A2-C8-4D-CD-CF-0E-8E-A4-2E-D4-65-8C-27-FF-C1-41-26-F9-0E-E5-11-C9-CC-3E-45-87-EC-49-BA-7C-83-91-DE-70-E8-27-1C-47-EB-1D-E2-37-62-2F-AA-5B-30-80-8B-80-00-55-F4-64-C2-BE-5A-D3-54-4A-E7-0B-95-00-F4-BA-72-CD-F8-22-E6-30-4E-F6-BD-BE-3F-00-52-7F-E2-57-5F-C0-BE-82-C0-50-07-1C-7D-89-56-49-CE-28-52-8C-11-B1-D1-51-51-12-B2-E0-00-00-00-9B-AF-1B-E9-C1-C7-35-F5-E2-EB-C9-EE-F6-BA-25-6D-6F-39-83-B9", BitConverter.ToString (pubkey)); }
static bool VerifyDsaMessage(byte[] keyData, byte[] message, byte[] signature) { // Load the Public Key X.509 Format AsnKeyParser keyParser = new AsnKeyParser(keyData); DSAParameters publicKey = keyParser.ParseDSAPublicKey(); CspParameters csp = new CspParameters(); // Cannot use PROV_DSS_DH const int PROV_DSS = 3; csp.ProviderType = PROV_DSS; const int AT_SIGNATURE = 2; csp.KeyNumber = AT_SIGNATURE; csp.KeyContainerName = "DSA Test (OK to Delete)"; DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(csp); dsa.PersistKeyInCsp = false; dsa.ImportParameters(publicKey); SHA1 sha = new SHA1CryptoServiceProvider(); byte[] hash = sha.ComputeHash(message); DSASignatureDeformatter verifier = new DSASignatureDeformatter(dsa); verifier.SetHashAlgorithm("SHA1"); bool result = verifier.VerifySignature(hash, signature); // See http://blogs.msdn.com/tess/archive/2007/10/31/ // asp-net-crash-system-security-cryptography-cryptographicexception.aspx dsa.Clear(); return result; }
public void ExportCspBlob_MissingPrivateKey () { dsa = new DSACryptoServiceProvider (minKeySize); DSAParameters dsap = AllTests.GetKey (false); dsa.ImportParameters (dsap); dsa.ExportCspBlob (true); }
// This case wasn't fixed in Nov CTP public void CspKeyContainerInfo_ImportedPublicKey () { dsa = new DSACryptoServiceProvider (minKeySize); DSAParameters rsap = AllTests.GetKey (false); dsa.ImportParameters (rsap); CspKeyContainerInfo info = dsa.CspKeyContainerInfo; Assert.IsFalse (info.Accessible, "Accessible"); // info.CryptoKeySecurity throws a CryptographicException at this stage // info.Exportable throws a CryptographicException at this stage Assert.IsFalse (info.HardwareDevice, "HardwareDevice"); Assert.IsNotNull (info.KeyContainerName, "KeyContainerName"); Assert.AreEqual (KeyNumber.Signature, info.KeyNumber, "KeyNumber"); Assert.IsFalse (info.MachineKeyStore, "MachineKeyStore"); // info.Protected throws a CryptographicException at this stage Assert.IsNotNull (info.ProviderName, "ProviderName"); Assert.AreEqual (13, info.ProviderType, "ProviderType"); Assert.IsTrue (info.RandomlyGenerated, "RandomlyGenerated"); Assert.IsFalse (info.Removable, "Removable"); // info.UniqueKeyContainerName throws a CryptographicException at this stage }
public void CspKeyContainerInfo_ImportedKeypair () { dsa = new DSACryptoServiceProvider (minKeySize); DSAParameters rsap = AllTests.GetKey (true); dsa.ImportParameters (rsap); CspKeyContainerInfo info = dsa.CspKeyContainerInfo; Assert.IsTrue (info.Accessible, "Accessible"); // FIXME AssertNotNull ("CryptoKeySecurity", info.CryptoKeySecurity); Assert.IsTrue (info.Exportable, "Exportable"); Assert.IsFalse (info.HardwareDevice, "HardwareDevice"); Assert.IsNotNull (info.KeyContainerName, "KeyContainerName"); Assert.AreEqual (KeyNumber.Signature, info.KeyNumber, "KeyNumber"); Assert.IsFalse (info.MachineKeyStore, "MachineKeyStore"); Assert.IsFalse (info.Protected, "Protected"); Assert.IsNotNull (info.ProviderName, "ProviderName"); Assert.AreEqual (13, info.ProviderType, "ProviderType"); Assert.IsTrue (info.RandomlyGenerated, "RandomlyGenerated"); Assert.IsFalse (info.Removable, "Removable"); Assert.IsNotNull (info.UniqueKeyContainerName, "UniqueKeyContainerName"); }
public void DSAImportMissingSeed () { DSAParameters input = AllTests.GetKey (false); input.Seed = null; dsa = new DSACryptoServiceProvider (1024); dsa.ImportParameters (input); Assert.AreEqual (1024, dsa.KeySize, "MissingSeed.KeySize"); }
public void DSAImportMissingY () { DSAParameters input = AllTests.GetKey (false); input.Y = null; dsa = new DSACryptoServiceProvider (1024); dsa.ImportParameters (input); }
public bool LogIn(string nick, string password,byte[] nickhashed, int counter, byte[] G, byte[] J, byte[] P, byte[] Q, byte[] Seed, byte[] X, byte[] Y) { bool result = false; Chat instance = new Chat(); instance.Deserialiser(); User user = instance.SearchNick(nick); if (user != null) //si l'utilisateur existe { if (user.CheckPassword(password)) //si le mot de passe de l'utilisateur est bon { DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider(); DSAParameters key = Security.RecreateKey(counter, G, J, P, Q, Seed, X, Y); mycrypto.ImportParameters(key); ASCIIEncoding encoding = new ASCIIEncoding(); if (mycrypto.VerifyData(encoding.GetBytes(nick), nickhashed)) //verification de la cle publique recue { result = true; instance.RemoveUser(user); user.Publickey = key; //on stocke la cle publique pour la reception prochaine de message instance.AddUser(user); instance.Serialiser(); } } } return result; }
public void ImportDisposed () { DSACryptoServiceProvider import = new DSACryptoServiceProvider (minKeySize); import.Clear (); import.ImportParameters (AllTests.GetKey (false)); // no exception from Fx 2.0 + }
/// <summary> /// Verifies the signature. /// </summary> /// <param name="hash">The hash.</param> /// <param name="signature">The signature.</param> /// <returns> /// true if signature verified; otherwise false. /// </returns> public override bool VerifySignature(IEnumerable<byte> hash, IEnumerable<byte> signature) { using (var sha1 = new SHA1CryptoServiceProvider()) { using (var cs = new CryptoStream(System.IO.Stream.Null, sha1, CryptoStreamMode.Write)) { var data = hash.ToArray(); cs.Write(data, 0, data.Length); } using (var dsa = new DSACryptoServiceProvider()) { dsa.ImportParameters(new DSAParameters { Y = _publicKey.TrimLeadingZero().ToArray(), P = _p.TrimLeadingZero().ToArray(), Q = _q.TrimLeadingZero().ToArray(), G = _g.TrimLeadingZero().ToArray(), }); var dsaDeformatter = new DSASignatureDeformatter(dsa); dsaDeformatter.SetHashAlgorithm("SHA1"); long i = 0; long j = 0; byte[] tmp; var sig = signature.ToArray(); 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, (int)i, tmp, 0, (int)j); sig = tmp; } return dsaDeformatter.VerifySignature(sha1, sig); } } }
private static byte[] DSASignHash(byte[] HashValue, DSAParameters privatekeyinfo, string HashAlg) { byte[] sig = null; try { //Create a new instance of DSACryptoServiceProvider using(DSACryptoServiceProvider dsa = new DSACryptoServiceProvider()) { //Import the key information dsa.ImportParameters(privatekeyinfo); // 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 to the hash value and return it //To format files // To format hash data sig = dsa.SignData(HashValue, 0, HashValue.Length); //dsa.SignHash(HashValue, "SHA1"); //dsaFormatter.CreateSignature(HashValue); } } catch(Exception e) { Console.WriteLine(e.Message); } return sig; }
public static bool myVerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters DSAKeyInfo, string HashAlg) { try { //Create a new instance of DSACryptoServiceProvider. DSACryptoServiceProvider DSA = new DSACryptoServiceProvider(); //Import the key information. DSA.ImportParameters(DSAKeyInfo); //DSAKeyInfo. //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. return DSADeformatter.VerifySignature(HashValue, SignedHashValue); } catch (CryptographicException e) { Console.WriteLine(e.Message); return false; } }