// The parameters and signature come from FIPS 186-2 APPENDIX 5. EXAMPLE OF THE DSA internal static void GetDSA1024_186_2(out DSAParameters parameters, out byte[] signature, out byte[] data) { parameters = new DSAParameters() { P = ( "8df2a494492276aa3d25759bb06869cbeac0d83afb8d0cf7cbb8324f0d7882e5d0762fc5b7210eafc2e9adac32ab7aac" + "49693dfbf83724c2ec0736ee31c80291").HexToByteArray(), Q = ("c773218c737ec8ee993b4f2ded30f48edace915f").HexToByteArray(), G = ( "626d027839ea0a13413163a55b4cb500299d5522956cefcb3bff10f399ce2c2e71cb9de5fa24babf58e5b79521925c9c" + "c42e9f6f464b088cc572af53e6d78802").HexToByteArray(), X = ("2070b3223dba372fde1c0ffc7b2e3b498b260614").HexToByteArray(), Y = ( "19131871d75b1612a819f29d78d1b0d7346f7aa77bb62a859bfd6c5675da9d212d3a36ef1672ef660b8c7c255cc0ec74" + "858fba33f44c06699630a76b030ee333").HexToByteArray() }; signature = ( // r "8bac1ab66410435cb7181f95b16ab97c92b341c0" + // s "41e2345f1f56df2458f426d155b4ba2db6dcd8c8" ).HexToByteArray(); data = Encoding.ASCII.GetBytes("abc"); }
internal static DSAParameters GetDSA2048Params() { DSAParameters p = new DSAParameters(); p.G = ( "44A7D22DEBA29CE19D678D2DC11F118BAA10E3BEA94DE29C3EC36C10AB4D688004A1B7F4387FC1CC9613E6851FEDBBD54531" + "9EDE544B94E4FAE9C1069E7734F9E6AFC8A0B840696CDFFE286E1AF1AD6E39629D0C8C6016AC625F100BACF5FF74B2325C9D" + "99A6D8B0310B268F63E35F5D1C8DA663F94ABA90244CECCF9A8CE5DB5479B006F9131E5EA78222A32E2A103C1FEF16929B15" + "6E3230C954295CDA3E5F91F71B567FA3B774B842F128CD0D343D5468DB90734A678035E65E6A21CC7301F4F53E6B66718A83" + "FF285A6FDE89CA5AE1D1B9633A25A34A926F9D2808F9BF795D936787FF4C7286BC7FC4A82AFA9B06C9125109A923BAF3E377" + "55F1574BAFB5").HexToByteArray(); p.P = ( "AF8FB9B2B147C96F392360639BDAA6544FF2CD086B604A3324F485595F02CEAF32D2D49F2DD3AD9F5384DD09D03182DB8F0A" + "A06CE0A0FCA2366A5B031BD0E2FAD797BADC874A0C6781529C01E0D69704B43DF371AE4A9B3DD81EB03F5DAE283780112568" + "66337B73A824F7E8ACA61981A7C67649363D2D7D12CC2305308D084BEC68CC3B1B3EF577053A5E23449FBA3C3EB6F8CD8EA6" + "9F116B3748BD237F97F4F7E911C41C394D6F7D2D53B767618F0DED48E7BD7F30C6568948264A54C00D358A76E9826ED791C6" + "B6CBF8C29C245173B1D8D219438E59373CE7554EF49C7840A8C55CE2E5E2C33C10AAD8D90F28C7CB2EF14AD5ED8C4E6992B4" + "1ECEC65288F5").HexToByteArray(); p.Q = "C93AB229237282997F23541A399BBF75CECD30BE0BE9592C07043ED30221EACB".HexToByteArray(); p.X = "B8BFF7B3328E6B6DBC8325A275A1193EF81C975ECF88B340C468B770FB5E2658".HexToByteArray(); p.Y = ( "011BD85986A2C41315FF01C554A45E5A9C45B38EBDCC2660B6D17889604E800A6FDE8E017CED3793F4A6FBAFBB7613FEB7BA" + "87841ABD59935D18858939C00A6E4619B6562475955D6D72B2134BECF5AB34118F60D84B1FF268753F188E861255132D84CA" + "0AAB681B8551873394F18E0DAEF6B5F9577EC7CA2AA63281B539AF5894283E3FB6DCC5537D92C8BFE7C0723AC212EEF3B771" + "8D35C3FDD99F7AE0912CC7C47521A56FA511BE31712D979AE67F17A7BCC4E5810EA9CA138DEED3D78239EEEF239A772942D2" + "3C2810C2972219525646127F9C4B81612C12AEDC2DC91E81153B0A207C1FBC00795B3EB8E86796CED29AC1247FF7122A1EAF" + "081025751572").HexToByteArray(); return p; }
internal static void AssertKeyEquals(ref DSAParameters expected, ref DSAParameters actual) { Assert.Equal(expected.G, actual.G); Assert.Equal(expected.P, actual.P); Assert.Equal(expected.Q, actual.Q); Assert.Equal(expected.Y, actual.Y); Assert.Equal(expected.X, actual.X); }
private static void SignAndVerify(byte[] data, string hashAlgorithmName, DSAParameters dsaParameters, int expectedSignatureLength) { using (DSA dsa = DSAFactory.Create()) { dsa.ImportParameters(dsaParameters); byte[] signature = dsa.SignData(data, new HashAlgorithmName(hashAlgorithmName)); Assert.Equal(expectedSignatureLength, signature.Length); bool signatureMatched = dsa.VerifyData(data, signature, new HashAlgorithmName(hashAlgorithmName)); Assert.True(signatureMatched); } }
internal static void ValidateParameters(ref DSAParameters dsaParams) { Assert.NotNull(dsaParams.G); Assert.True(dsaParams.G.Length > 0); Assert.NotNull(dsaParams.P); Assert.True(dsaParams.P.Length > 0); Assert.NotNull(dsaParams.Q); Assert.True(dsaParams.Q.Length > 0); Assert.True(dsaParams.Y.Length > 0); Assert.NotNull(dsaParams.Y); }
public static void VerifyKnownSignature() { // The parameters and signature come from FIPS 186-2 APPENDIX 5. EXAMPLE OF THE DSA using (DSA dsa = DSAFactory.Create()) { DSAParameters dsaParameters = new DSAParameters { P = ( "8df2a494492276aa3d25759bb06869cbeac0d83afb8d0cf7" + "cbb8324f0d7882e5d0762fc5b7210eafc2e9adac32ab7aac" + "49693dfbf83724c2ec0736ee31c80291").HexToByteArray(), Q = ("c773218c737ec8ee993b4f2ded30f48edace915f").HexToByteArray(), G = ( "626d027839ea0a13413163a55b4cb500299d5522956cefcb" + "3bff10f399ce2c2e71cb9de5fa24babf58e5b79521925c9c" + "c42e9f6f464b088cc572af53e6d78802").HexToByteArray(), X = ("2070b3223dba372fde1c0ffc7b2e3b498b260614").HexToByteArray(), Y = ( "19131871d75b1612a819f29d78d1b0d7346f7aa77bb62a85" + "9bfd6c5675da9d212d3a36ef1672ef660b8c7c255cc0ec74" + "858fba33f44c06699630a76b030ee333").HexToByteArray(), }; byte[] signature = ( // r "8bac1ab66410435cb7181f95b16ab97c92b341c0" + // s "41e2345f1f56df2458f426d155b4ba2db6dcd8c8" ).HexToByteArray(); byte[] data = Encoding.ASCII.GetBytes("abc"); dsa.ImportParameters(dsaParameters); Assert.True(dsa.VerifyData(data, signature, HashAlgorithmName.SHA1)); // Negative case unchecked { --signature[signature.Length - 1]; } Assert.False(dsa.VerifyData(data, signature, HashAlgorithmName.SHA1)); } }
public ICertificatePal CopyWithPrivateKey(DSA privateKey) { DSAOpenSsl typedKey = privateKey as DSAOpenSsl; if (typedKey != null) { return(CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle())); } DSAParameters dsaParameters = privateKey.ExportParameters(true); using (PinAndClear.Track(dsaParameters.X)) using (typedKey = new DSAOpenSsl(dsaParameters)) { return(CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle())); } }
public static DsaPublicKeyParameters GetDsaPublicKey( DSAParameters dp) { DsaValidationParameters validationParameters = (dp.Seed != null) ? new DsaValidationParameters(dp.Seed, dp.Counter) : null; DsaParameters parameters = new DsaParameters( new BigInteger(1, dp.P), new BigInteger(1, dp.Q), new BigInteger(1, dp.G), validationParameters); return(new DsaPublicKeyParameters( new BigInteger(1, dp.Y), parameters)); }
public static void TestRead512Parameters_Public() { DSAParameters expectedParameters = DSATestData.Dsa512Parameters; expectedParameters.X = null; TestReadXml( // Bonus trait of this XML: it shows that the namespaces of the elements are not considered @" <DSAKeyValue xmlns:yep=""urn:ignored:yep"" xmlns:nope=""urn:ignored:nope"" xmlns:ign=""urn:ignored:ign""> <yep:P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</yep:P> <nope:Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</nope:Q> <G>CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPOqfch85sFuvlwUt78Z6WKKw==</G> <ign:Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</ign:Y> </DSAKeyValue>", expectedParameters); }
public override bool VerifySignature(SignaturePacket SigPacket) { if (!base.VerifySignature(SigPacket)) { return(false); } if (!(SigPacket.SecretKeyTransformedData is SecretKeyTransformedDSAData dsa)) { return(false); } var csp = new DSACryptoServiceProvider(); DSAParameters param = new DSAParameters { P = P, Q = Q, G = G, Y = Y }; csp.ImportParameters(param); if (SigPacket.HashedData.Length < Q.Length) { return(false); } var SubHash = SigPacket.HashedData.SubArray(0, Q.Length); byte[] SigVerify = new byte[dsa.R.Length + dsa.S.Length]; Array.Copy(dsa.R, 0, SigVerify, 0, dsa.R.Length); Array.Copy(dsa.S, 0, SigVerify, dsa.R.Length, dsa.S.Length); try { bool IsMatch = csp.VerifyHash(SubHash, SigPacket.HashAlgorithmName.Name, SigVerify); return(IsMatch); } catch { } return(false); }
public override DSAParameters ExportParameters(bool includePrivateParameters) { if (m_disposed) { throw new ObjectDisposedException(Locale.GetText("Keypair was disposed")); } if (!keypairGenerated) { Generate(); } if ((includePrivateParameters) && (x == null)) { throw new CryptographicException("no private key to export"); } DSAParameters param = new DSAParameters(); // all parameters must be in multiple of 4 bytes arrays // this isn't (generally) a problem for most of the parameters // except for J (but we won't take a chance) param.P = NormalizeArray(p.GetBytes()); param.Q = NormalizeArray(q.GetBytes()); param.G = NormalizeArray(g.GetBytes()); param.Y = NormalizeArray(y.GetBytes()); if (!j_missing) { param.J = NormalizeArray(j.GetBytes()); } if (seed != 0) { param.Seed = NormalizeArray(seed.GetBytes()); param.Counter = counter; } if (includePrivateParameters) { byte[] privateKey = x.GetBytes(); if (privateKey.Length == 20) { param.X = NormalizeArray(privateKey); } } return(param); }
/// <summary>デジタル署名を検証する</summary> /// <param name="data">デジタル署名を行なった対象データ</param> /// <param name="sign">対象データに対してデジタル署名したデジタル署名部分のデータ</param> /// <returns>検証結果( true:検証成功, false:検証失敗 )</returns> public override bool Verify(byte[] data, byte[] sign) { AsymmetricAlgorithm aa = null; // 検証結果フラグ ( true:検証成功, false:検証失敗 ) bool flg = false; // アルゴリズム(RSA or DSA)は、ココで決まるもよう。 if (this.X509Certificate.PrivateKey == null) { // *.cer aa = this.X509Certificate.PublicKey.Key; if (aa is RSACryptoServiceProvider) { return(((RSACryptoServiceProvider)aa).VerifyData(data, this._hashAlgorithmName, sign)); } else { return(((DSACryptoServiceProvider)aa).VerifyData(data, sign)); } } else { // *.pfx aa = this.X509Certificate.PrivateKey; if (aa is RSACryptoServiceProvider) { // RSACryptoServiceProvider : ExportParametersして生成し直している。 RSAParameters rsaParam = ((RSACryptoServiceProvider)(aa)).ExportParameters(true); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(this.X509Certificate.PrivateKey.KeySize); rsa.ImportParameters(rsaParam); flg = rsa.VerifyData(data, this._hashAlgorithmName, sign); } else { // DSACryptoServiceProvider : ExportParametersして生成し直している。 DSAParameters dsaParam = ((DSACryptoServiceProvider)(aa)).ExportParameters(true); DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(this.X509Certificate.PrivateKey.KeySize); dsa.ImportParameters(dsaParam); flg = dsa.VerifyData(data, sign); // SHA-1 固定のため? } } return(flg); }
public static void ImportFromPem_Pkcs8UnEncrypted_Simple() { using (DSA dsa = DSAFactory.Create()) { string pem = @" -----BEGIN PRIVATE KEY----- MIHGAgEAMIGoBgcqhkjOOAQBMIGcAkEA1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWN IHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQIVAPq19iXV 1eFkMKHvYw6+M4l8wiT5AkAIRMSQ5S71jgWQLGNtZNHV6yxggqDU87/RzgeOh7Q6 fve77OGaTv4qbZwinTYAg86p9yHzmwW6+XBS3vxnpYorBBYCFC49eoTIW2Z4Xh9v 55aYKyKwy5i8 -----END PRIVATE KEY-----"; dsa.ImportFromPem(pem); DSAParameters dsaParameters = dsa.ExportParameters(true); DSAImportExport.AssertKeyEquals(DSATestData.Dsa512Parameters, dsaParameters); } }
public override void LoadKeyAndCertificatesData(byte[] data) { using (var worker = new SshDataWorker(data)) { if (worker.ReadString(Encoding.ASCII) != this.Name) { throw new CryptographicException("Key and certificates were not created with this algorithm."); } var args = new DSAParameters(); args.P = worker.ReadMpint(); args.Q = worker.ReadMpint(); args.G = worker.ReadMpint(); args.Y = worker.ReadMpint(); _algorithm.ImportParameters(args); } }
public ICertificatePal CopyWithPrivateKey(DSA privateKey) { var typedKey = privateKey as DSAImplementation.DSASecurityTransforms; if (typedKey != null) { return(CopyWithPrivateKey(typedKey.GetKeys())); } DSAParameters dsaParameters = privateKey.ExportParameters(true); using (PinAndClear.Track(dsaParameters.X)) using (typedKey = new DSAImplementation.DSASecurityTransforms()) { typedKey.ImportParameters(dsaParameters); return(CopyWithPrivateKey(typedKey.GetKeys())); } }
private static void WriteDSSSeed(DSAParameters dsaParameters, BinaryWriter bw) { if (dsaParameters.Seed == null || dsaParameters.Seed.Length == 0) { bw.Write(0xFFFFFFFF); // counter // seed[20] needs to be all 0xFF for (int i = 0; i < 20; i += sizeof(uint)) { bw.Write(0xFFFFFFFF); } } else { bw.Write((int)dsaParameters.Counter); bw.WriteReversed(dsaParameters.Seed); } }
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); }
private static void LoadDsaPublicKey() { // // Load the Public Key // X.509 Format // AsnKeyParser keyParser = new AsnKeyParser("public.dsa.cs.ber"); DSAParameters publicKey = keyParser.ParseDSAPublicKey(); // // Initailize the CSP // Supresses creation of a new key // CspParameters csp = new CspParameters(); // const int PROV_DSS_DH = 13; 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)"; // // Initialize the Provider // DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(csp) { PersistKeyInCsp = false }; // // The moment of truth... // dsa.ImportParameters(publicKey); // See http://blogs.msdn.com/tess/archive/2007/10/31/ // asp-net-crash-system-security-cryptography-cryptographicexception.aspx dsa.Clear(); }
/// <summary>Constructor</summary> /// <param name="dsaParameters">DSAParameters</param> /// <param name="eaa">EnumDigitalSignAlgorithm</param> public DigitalSignParam(DSAParameters dsaParameters, EnumDigitalSignAlgorithm eaa) { AsymmetricAlgorithm aa = null; HashAlgorithm ha = null; AsymmetricAlgorithmCmnFunc.CreateDigitalSignSP(eaa, out aa, out ha); if (aa is DSA) { ((DSA)aa).ImportParameters(dsaParameters); } else { throw new ArgumentException("unmatched"); } this.AsymmetricAlgorithm = aa; this.HashAlgorithm = ha; }
public static byte[] ToCapiPublicKeyBlob(DSA dsa) { DSAParameters dsaparameters = dsa.ExportParameters(false); int num = dsaparameters.P.Length; byte[] array = new byte[16 + num + 20 + num + num + 4 + 20]; array[0] = 6; array[1] = 2; array[5] = 34; array[8] = 68; array[9] = 83; array[10] = 83; array[11] = 49; byte[] bytesLE = CryptoConvert.GetBytesLE(num << 3); array[12] = bytesLE[0]; array[13] = bytesLE[1]; array[14] = bytesLE[2]; array[15] = bytesLE[3]; int num2 = 16; byte[] array2 = dsaparameters.P; Array.Reverse(array2); Buffer.BlockCopy(array2, 0, array, num2, num); num2 += num; array2 = dsaparameters.Q; Array.Reverse(array2); Buffer.BlockCopy(array2, 0, array, num2, 20); num2 += 20; array2 = dsaparameters.G; Array.Reverse(array2); Buffer.BlockCopy(array2, 0, array, num2, num); num2 += num; array2 = dsaparameters.Y; Array.Reverse(array2); Buffer.BlockCopy(array2, 0, array, num2, num); num2 += num; Buffer.BlockCopy(CryptoConvert.GetBytesLE(dsaparameters.Counter), 0, array, num2, 4); num2 += 4; array2 = dsaparameters.Seed; Array.Reverse(array2); Buffer.BlockCopy(array2, 0, array, num2, 20); return(array); }
public void TestMethodRegisterAndLogin() { DSACryptoServiceProvider mycrypto = new DSACryptoServiceProvider(); DSAParameters Publickey = mycrypto.ExportParameters(false); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] hash = mycrypto.SignData(encoding.GetBytes("Cuddy")); ServiceReference1.ServeurChatSoapClient a = new ServiceReference1.ServeurChatSoapClient(); Assert.AreEqual(true, a.Register("Cuddy", "passbidon", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y)); Assert.AreEqual(false, a.Register("Cuddy", "rate", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y)); Assert.AreEqual(true, a.LogIn("Cuddy", "passbidon", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y)); Assert.AreEqual(false, a.LogIn("Cuddy", "badpass", hash, Publickey.Counter, Publickey.G, Publickey.J, Publickey.P, Publickey.Q, Publickey.Seed, Publickey.X, Publickey.Y)); //remise a zero du serveur 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"); }
internal static DSAParameters GetDSA1024Params() { DSAParameters p = new DSAParameters(); p.G = ( "6BC366B66355545E098F1FE90E5469B567E09FA79D817F2B367B45DECD4301A59C81D6911F7691D370E15AC692C04BC11872" + "C171A7FE654E963D7DDA575A9E98CE026FB7D3934A258608134A8EC5ED69A2AEDC89401B67ADDE427F17EDAEB72D7AF45D9A" + "B1D59E1B13D4EFBD17C764330267DDE352C20E05B80DB3C109FE8B9C").HexToByteArray(); p.P = ( "C16D26C74D6C1627799C0918548E553FE58C7881DA484629CAF64311F4B27CFEF6BDB0F21206B0FFC4999A2FED53B43B9EE2" + "910C68DA2C436A8018F4938F6472369F5647D005BCC96E22590CC15E3CD4EA0D132F5DA5AF6AAA0807B0CC4EF3404AF542F4" + "546B37BDD6A47E641130837DB99397C845635D7DC36D0537E4A84B31").HexToByteArray(); p.Q = "D83C0ECB73551E2FE30D51FCF4236C651883ADD7".HexToByteArray(); p.X = "C02678007779E52E360682214BD47F8FAF42BC2D".HexToByteArray(); p.Y = ( "690BB37A9145E05D6E7B47C457898AAEDD72501C9D16E79B1AD75A872CF017AA90BBFB90F1B3B7F5C03C87E46E8725665526" + "FD34157B26F596A1F0997F59F3E65EFC615A552D5E7569C5FFC4593D5A0299110E71C97E1221A5A03FE9A6935AEDD88EF0B3" + "B2F79D3A99ED75F7B871E6EAF2680D96D574A5F4C13BACE3B4B44DE1").HexToByteArray(); return p; }
private void load_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.Cancel) { return; } // получаем выбранный файл string filename = openFileDialog1.FileName; // читаем файл в строку string fileText = System.IO.File.ReadAllText(filename); textBox1.Text = Path.GetFullPath(openFileDialog1.FileName); StringReader stringReader = new StringReader(fileText); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(DSAParameters)); DSAParameters dsaparams = (DSAParameters)x.Deserialize(stringReader); //get possibly modified message as byte array byte[] messagebytes = Encoding.UTF8.GetBytes( richTextBox1.Text); //create digest of original message using SHA1 SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] hashbytes = sha1.ComputeHash(messagebytes); //create DSA object using parameters from signing DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.ImportParameters(dsaparams); //do verification on hash using OID for SHA-1 bool match = dsa.VerifyHash( hashbytes, "1.3.14.3.2.26", signaturebytes); status.Text = "Status : " + ((match) ? "SUCCESS": "FAIL"); }
public static void ImportFromPem_SubjectPublicKeyInfo_Simple() { using (DSA dsa = DSAFactory.Create()) { string pem = @" -----BEGIN PUBLIC KEY----- MIHxMIGoBgcqhkjOOAQBMIGcAkEA1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRn QNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQIVAPq19iXV1eFk MKHvYw6+M4l8wiT5AkAIRMSQ5S71jgWQLGNtZNHV6yxggqDU87/RzgeOh7Q6fve7 7OGaTv4qbZwinTYAg86p9yHzmwW6+XBS3vxnpYorA0QAAkEAwwDg5n2HfmztOf7q qsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8 PKRWBQ== -----END PUBLIC KEY-----"; dsa.ImportFromPem(pem); DSAParameters dsaParameters = dsa.ExportParameters(false); DSAImportExport.AssertKeyEquals(DSATestData.Dsa512Parameters.ToPublic(), dsaParameters); } }
public static byte[] ToCapiPrivateKeyBlob(DSA dsa) { DSAParameters dSAParameters = dsa.ExportParameters(includePrivateParameters: true); int num = dSAParameters.P.Length; byte[] array = new byte[16 + num + 20 + num + 20 + 4 + 20]; array[0] = 7; array[1] = 2; array[5] = 34; array[8] = 68; array[9] = 83; array[10] = 83; array[11] = 50; byte[] bytesLE = GetBytesLE(num << 3); array[12] = bytesLE[0]; array[13] = bytesLE[1]; array[14] = bytesLE[2]; array[15] = bytesLE[3]; int num2 = 16; byte[] p = dSAParameters.P; Array.Reverse(p); Buffer.BlockCopy(p, 0, array, num2, num); num2 += num; p = dSAParameters.Q; Array.Reverse(p); Buffer.BlockCopy(p, 0, array, num2, 20); num2 += 20; p = dSAParameters.G; Array.Reverse(p); Buffer.BlockCopy(p, 0, array, num2, num); num2 += num; p = dSAParameters.X; Array.Reverse(p); Buffer.BlockCopy(p, 0, array, num2, 20); num2 += 20; Buffer.BlockCopy(GetBytesLE(dSAParameters.Counter), 0, array, num2, 4); num2 += 4; p = dSAParameters.Seed; Array.Reverse(p); Buffer.BlockCopy(p, 0, array, num2, 20); return(array); }
/// <summary> /// Constructeur par defaut /// </summary> public PrincipalForm() { InitializeComponent(); SaveForm param_fenetre = Serializer.DeserialiserFenetre(); if (param_fenetre != null) { this.Size = new System.Drawing.Size(param_fenetre.Weightform, param_fenetre.Heightform); this.splitContainer1.SplitterDistance = param_fenetre.Splitterdistance; this.Location = new System.Drawing.Point(param_fenetre.LocalisationX, param_fenetre.LocalisationY); } //initialisation de liaison avec le service client = new ServeurChat.ServeurChatSoapClient(); //generation des clé pour la session qui va etre lance crypto = new DSACryptoServiceProvider(); securitykey = crypto.ExportParameters(false); connected = false; }
static internal DSA DecodeDSA(byte[] rawPublicKey, byte[] rawParameters) { DSAParameters dsaParams = new DSAParameters(); try { // for DSA rawPublicKey contains 1 ASN.1 integer - Y ASN1 pubkey = new ASN1(rawPublicKey); if (pubkey.Tag != 0x02) { throw new CryptographicException(Locale.GetText("Missing DSA Y integer.")); } dsaParams.Y = GetUnsignedBigInteger(pubkey.Value); ASN1 param = new ASN1(rawParameters); if ((param == null) || (param.Tag != 0x30) || (param.Count < 3)) { throw new CryptographicException(Locale.GetText("Missing DSA parameters.")); } if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02)) { throw new CryptographicException(Locale.GetText("Invalid DSA parameters.")); } dsaParams.P = GetUnsignedBigInteger(param [0].Value); dsaParams.Q = GetUnsignedBigInteger(param [1].Value); dsaParams.G = GetUnsignedBigInteger(param [2].Value); } catch (Exception e) { string msg = Locale.GetText("Error decoding the ASN.1 structure."); throw new CryptographicException(msg, e); } #if MOONLIGHT DSA dsa = (DSA) new DSAManaged(dsaParams.Y.Length << 3); #else DSA dsa = (DSA) new DSACryptoServiceProvider(dsaParams.Y.Length << 3); #endif dsa.ImportParameters(dsaParams); return(dsa); }
private DSAParameters ExtractParameters(byte[] blob) { int length = blob[2] << 8 | blob[3]; byte[] sequence = new byte[length]; Buffer.BlockCopy(blob, 4, sequence, 0, length); byte[][] data = new byte[5][]; for (int i = 0, index = -1; i < sequence.Length; i += length, index++) { i++; length = sequence[i++]; if ((length & 0x80) != 0) { var length2 = length & 0x7F; length = 0; while (length2-- > 0) { length = length << 8 | sequence[i++]; } } else { length = length & 0x7F; } if (index > -1) { data[index] = new byte[length]; Buffer.BlockCopy(sequence, i, data[index], 0, length); } } var key = new DSAParameters(); key.P = data[0]; key.Q = data[1]; key.G = data[2]; key.Y = data[3]; key.X = data[4]; return(key); }
/* SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING } */ private ASN1 SubjectPublicKeyInfo() { ASN1 keyInfo = new ASN1(0x30); if (aa is RSA) { keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1")); RSAParameters p = (aa as RSA).ExportParameters(false); /* RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER } -- e */ ASN1 key = new ASN1(0x30); key.Add(ASN1Convert.FromUnsignedBigInteger(p.Modulus)); key.Add(ASN1Convert.FromUnsignedBigInteger(p.Exponent)); keyInfo.Add(new ASN1(UniqueIdentifier(key.GetBytes()))); } else if (aa is DSA) { DSAParameters p = (aa as DSA).ExportParameters(false); /* Dss-Parms ::= SEQUENCE { * p INTEGER, * q INTEGER, * g INTEGER } */ ASN1 param = new ASN1(0x30); param.Add(ASN1Convert.FromUnsignedBigInteger(p.P)); param.Add(ASN1Convert.FromUnsignedBigInteger(p.Q)); param.Add(ASN1Convert.FromUnsignedBigInteger(p.G)); keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.10040.4.1", param)); ASN1 key = keyInfo.Add(new ASN1(0x03)); // DSAPublicKey ::= INTEGER -- public key, y key.Add(ASN1Convert.FromUnsignedBigInteger(p.Y)); } else { throw new NotSupportedException("Unknown Asymmetric Algorithm " + aa.ToString()); } return(keyInfo); }
/// <summary> /// Gere le coutton d'enregistrement /// </summary> private void buttonRegister_Click_1(object sender, EventArgs e) { DSAParameters key = main.Securitykey; ASCIIEncoding encoding = new ASCIIEncoding(); string nick = textBoxLogin.Text; string password = textBoxPassword.Text; try { if (textBoxPassword.Text == "" || textBoxLogin.Text == "") //si le login et le password sont valide { labelError.Text = "Login/password vide interdit"; } else { if (textBoxPassword.Text == textBoxConfirmPassword.Text) //si le la confirmation est identique au password { byte[] nicksigned = main.Crypto.SignData(encoding.GetBytes(nick)); //on signe le login if (main.Client.Register(nick, password, nicksigned, key.Counter, key.G, key.J, key.P, key.Q, key.Seed, key.X, key.Y) == false) { labelError.Text = "Login deja utilise"; } else { MessageBox.Show("Creation du compte reussi", "Creation reussi"); main.Session = nick; main.Enabled = true; this.Close(); } } else { labelError.Text = "Erreur verification mot de passe"; } } } catch (System.ServiceModel.EndpointNotFoundException) { MessageBox.Show("Erreur de connexion,Verifiez votre connexion ", "Error"); } }
private bool DsaVerifyHash(byte[] hashValue, byte[] signedHashValue, DSAParameters dsaKey, string hashAlg) { var verified = false; try { using (var dsa = new DSACryptoServiceProvider()) { dsa.ImportParameters(dsaKey); var dsaDeformatter = new DSASignatureDeformatter(dsa); dsaDeformatter.SetHashAlgorithm(hashAlg); verified = dsaDeformatter.VerifySignature(hashValue, signedHashValue); } } catch (CryptographicException e) { MessageBox.Show(e.Message); } return(verified); }
private static AsymmetricAlgorithm DecodeDsaPublicKey(byte[] encodedKeyValue, byte[] encodedParameters) { DSAParameters dsaParameters = new DSAParameters(); DerSequenceReader parameterReader = new DerSequenceReader(encodedParameters); parameterReader.ReadSubjectPublicKeyInfo(encodedKeyValue, ref dsaParameters); DSA dsa = DSA.Create(); try { dsa.ImportParameters(dsaParameters); return(dsa); } catch (Exception) { dsa.Dispose(); throw; } }
public static void ImportFromEncryptedPem_Pkcs8_Encrypted_Char_Simple() { using (DSA dsa = DSAFactory.Create()) { string pem = @" -----BEGIN ENCRYPTED PRIVATE KEY----- MIIBIDBLBgkqhkiG9w0BBQ0wPjApBgkqhkiG9w0BBQwwHAQIkM/kCKe6rYsCAggA MAwGCCqGSIb3DQIJBQAwEQYFKw4DAgcECBOccveL65bDBIHQiCcCqwxJs93g1+16 7Gx1D5lL4/nZ94fRa+Hl4nGEX4gmjuxH6pOHKyywwflAyXNTfVhOCP9zBedwENx9 MGHbpaaShD6iJfoGMRX0frr0mMCtuOOZkkjBF9pSpkhaH0TDSq1PrVLxcM0/S4Vs +//2uPrP8U+CTW9W7CXCZw698BAuevZRuD0koT2Bn9ErhTiuVZZMcOjtLmN2oXHG dVYwfovccu8ktEAwk5XAOo0r+5CCw2lDDw/hbDeO87BToC5Cc5nu3F5LxAUj8Flc v8pi3w== -----END ENCRYPTED PRIVATE KEY-----"; dsa.ImportFromEncryptedPem(pem, "test"); DSAParameters dsaParameters = dsa.ExportParameters(true); DSAImportExport.AssertKeyEquals(DSATestData.Dsa512Parameters, dsaParameters); } }
private void GenerateKeyButton_Click(object sender, EventArgs e) { using (var dsa = new DSACryptoServiceProvider()) { _privateKey = dsa.ExportParameters(true); _publicKey = dsa.ExportParameters(false); } Message = MessageTextBox.Text; byte[] byteMessage = Encoding.UTF8.GetBytes(Message); hash = (new SHA1Managed()).ComputeHash(byteMessage); signedHash = DsaSignHash(hash, _privateKey, "SHA1"); var stringBuilder = new StringBuilder(); foreach (byte t in signedHash) { stringBuilder.Append(t.ToString("x2")); } SignatureTextBox.Text = stringBuilder.ToString(); }
internal static DSAParameters GetDSA1024Params() { DSAParameters p = new DSAParameters(); p.G = ( "6BC366B66355545E098F1FE90E5469B567E09FA79D817F2B367B45DECD4301A59C81D6911F7691D370E15AC692C04BC11872" + "C171A7FE654E963D7DDA575A9E98CE026FB7D3934A258608134A8EC5ED69A2AEDC89401B67ADDE427F17EDAEB72D7AF45D9A" + "B1D59E1B13D4EFBD17C764330267DDE352C20E05B80DB3C109FE8B9C").HexToByteArray(); p.P = ( "C16D26C74D6C1627799C0918548E553FE58C7881DA484629CAF64311F4B27CFEF6BDB0F21206B0FFC4999A2FED53B43B9EE2" + "910C68DA2C436A8018F4938F6472369F5647D005BCC96E22590CC15E3CD4EA0D132F5DA5AF6AAA0807B0CC4EF3404AF542F4" + "546B37BDD6A47E641130837DB99397C845635D7DC36D0537E4A84B31").HexToByteArray(); p.Q = "D83C0ECB73551E2FE30D51FCF4236C651883ADD7".HexToByteArray(); p.X = "C02678007779E52E360682214BD47F8FAF42BC2D".HexToByteArray(); p.Y = ( "690BB37A9145E05D6E7B47C457898AAEDD72501C9D16E79B1AD75A872CF017AA90BBFB90F1B3B7F5C03C87E46E8725665526" + "FD34157B26F596A1F0997F59F3E65EFC615A552D5E7569C5FFC4593D5A0299110E71C97E1221A5A03FE9A6935AEDD88EF0B3" + "B2F79D3A99ED75F7B871E6EAF2680D96D574A5F4C13BACE3B4B44DE1").HexToByteArray(); return(p); }
public static void ImportFromEncryptedPem_Pkcs8_Encrypted_Byte_Simple() { using (DSA dsa = DSAFactory.Create()) { string pem = @" -----BEGIN ENCRYPTED PRIVATE KEY----- MIIBLDBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIfcoipdEY/C4CAggA MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAECBBC9heEphj00fB89aP6chSOjBIHQ HF2RLrIw6654q2hjUdCG4PhhYNXlck0zD0mOuaVQHmnKIKArk/1DSpgSrYnKw6aE 2eujwNdySLLEwUj5l+X/IXwhOnPIZDJqUN7oMagUYJX28gnQmXyDvrt3r16utbpd ho0YNYGUDSgOs6RxBpw1rJUCnAlHNU09peCjEP+aZSrhsxlejN/GpVS4e0JTmMeo xTL6VO9mx52x6h5WDAQAisMVeMkBoxQUWLANXiw1zSfVbsmB7mDknsRcvD3tcgMs 7YLD7LQMiPAIjDlOP8XP/w== -----END ENCRYPTED PRIVATE KEY-----"; byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); dsa.ImportFromEncryptedPem(pem, passwordBytes); DSAParameters dsaParameters = dsa.ExportParameters(true); DSAImportExport.AssertKeyEquals(DSATestData.Dsa512Parameters, dsaParameters); } }
private static void WriteKeyBlobHeader(DSAParameters dsaParameters, BinaryWriter bw, bool isPrivate, out bool isV3) { // Write out the BLOBHEADER (or PUBLICKEYSTRUC). isV3 = false; // If Y is present and this is a private key, // or Y and J are present and this is a public key, this should be a v3 blob. byte version = BLOBHEADER_CURRENT_BVERSION; if (((dsaParameters.Y != null) && isPrivate) || ((dsaParameters.Y != null) && (dsaParameters.J != null))) { Debug.Assert(dsaParameters.Y.Length > 0); isV3 = true; version = 0x3; } bw.Write((byte)(isPrivate ? PRIVATEKEYBLOB : PUBLICKEYBLOB)); // BLOBHEADER.bType bw.Write((byte)version); // BLOBHEADER.bVersion bw.Write((ushort)0); // BLOBHEADER.wReserved bw.Write((int)CapiHelper.CALG_DSS_SIGN); // BLOBHEADER.aiKeyAlg }
public abstract virtual void ImportParameters(DSAParameters parameters) {}
internal static DSAParameters ExportDsaParameters(SafeDsaHandle key, bool includePrivateParameters) { Debug.Assert( key != null && !key.IsInvalid, "Callers should check the key is invalid and throw an exception with a message"); if (key == null || key.IsInvalid) { throw new CryptographicException(); } IntPtr p_bn, q_bn, g_bn, y_bn, x_bn; // these are not owned int p_cb, q_cb, g_cb, y_cb, x_cb; bool refAdded = false; try { key.DangerousAddRef(ref refAdded); // Protect access to the *_bn variables if (!GetDsaParameters(key, out p_bn, out p_cb, out q_bn, out q_cb, out g_bn, out g_cb, out y_bn, out y_cb, out x_bn, out x_cb)) { throw new CryptographicException(); } // Match Windows semantics where p, g and y have same length int pgy_cb = GetMax(p_cb, g_cb, y_cb); // Match Windows semantics where q and x have same length int qx_cb = GetMax(q_cb, x_cb); DSAParameters dsaParameters = new DSAParameters { P = Crypto.ExtractBignum(p_bn, pgy_cb), Q = Crypto.ExtractBignum(q_bn, qx_cb), G = Crypto.ExtractBignum(g_bn, pgy_cb), Y = Crypto.ExtractBignum(y_bn, pgy_cb), }; if (includePrivateParameters) { dsaParameters.X = Crypto.ExtractBignum(x_bn, qx_cb); } return dsaParameters; } finally { if (refAdded) key.DangerousRelease(); } }
public virtual void ImportParameters(DSAParameters parameters) {}
static internal DSA DecodeDSA (byte[] rawPublicKey, byte[] rawParameters) { DSAParameters dsaParams = new DSAParameters (); try { // for DSA rawPublicKey contains 1 ASN.1 integer - Y ASN1 pubkey = new ASN1 (rawPublicKey); if (pubkey.Tag != 0x02) throw new CryptographicException (Locale.GetText ("Missing DSA Y integer.")); dsaParams.Y = GetUnsignedBigInteger (pubkey.Value); ASN1 param = new ASN1 (rawParameters); if ((param == null) || (param.Tag != 0x30) || (param.Count < 3)) throw new CryptographicException (Locale.GetText ("Missing DSA parameters.")); if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02)) throw new CryptographicException (Locale.GetText ("Invalid DSA parameters.")); dsaParams.P = GetUnsignedBigInteger (param [0].Value); dsaParams.Q = GetUnsignedBigInteger (param [1].Value); dsaParams.G = GetUnsignedBigInteger (param [2].Value); } catch (Exception e) { string msg = Locale.GetText ("Error decoding the ASN.1 structure."); throw new CryptographicException (msg, e); } DSA dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3); dsa.ImportParameters (dsaParams); return dsa; }