public static void DefaultKeySize() { using (var dsa = new DSACryptoServiceProvider()) { Assert.Equal(1024, dsa.KeySize); } }
public static void CreateKey_RoundtripBlob() { const int KeySize = 512; CspParameters cspParameters = new CspParameters(PROV_DSS_DH); byte[] blob; using (var dsa = new DSACryptoServiceProvider(KeySize, cspParameters)) { CspKeyContainerInfo containerInfo = dsa.CspKeyContainerInfo; Assert.Equal(PROV_DSS_DH, containerInfo.ProviderType); Assert.Equal(KeySize, dsa.KeySize); blob = dsa.ExportCspBlob(true); } using (var dsa = new DSACryptoServiceProvider()) { dsa.ImportCspBlob(blob); CspKeyContainerInfo containerInfo = dsa.CspKeyContainerInfo; // The provider information is not persisted in the blob Assert.Equal(PROV_DSS_DH, containerInfo.ProviderType); Assert.Equal(KeySize, dsa.KeySize); } }
public static void PublicOnly_WithPrivateKey() { using (var dsa = new DSACryptoServiceProvider()) { dsa.ImportParameters(DSATestData.GetDSA1024Params()); Assert.False(dsa.PublicOnly); } }
public static void PublicOnly_DefaultKey() { using (var dsa = new DSACryptoServiceProvider()) { // This will call the key into being, which should create a public/private pair, // therefore it should not be public-only. Assert.False(dsa.PublicOnly); } }
public static void CreateKey() { CspParameters cspParameters = new CspParameters(PROV_DSS_DH); using (var dsa = new DSACryptoServiceProvider(cspParameters)) { CspKeyContainerInfo containerInfo = dsa.CspKeyContainerInfo; Assert.Equal(PROV_DSS_DH, containerInfo.ProviderType); } }
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); }
static AsymmetricAlgorithm GetAsymmetricAlgorithm(DsaPrivateKeyParameters key, DsaPublicKeyParameters pub) { var parameters = GetDSAParameters(key); parameters.X = key.X.ToByteArrayUnsigned(); if (pub != null) { parameters.Y = pub.Y.ToByteArrayUnsigned(); } var dsa = new DSACryptoServiceProvider(); dsa.ImportParameters(parameters); return(dsa); }
/// <summary> Create a digital signature for the provided data and return it in a /// string. /// </summary> /// <param name="data">The data to sign. /// </param> /// <returns> The signature. /// </returns> /// <seealso cref="Owasp.Esapi.Interfaces.IEncryptor.Sign(string)"> /// </seealso> public string Sign(string data) { try { asymmetricKeyPair.Flags = CspProviderFlags.UseMachineKeyStore; DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(asymmetricKeyPair); Encoding textConverter = Encoding.GetEncoding(encoding); byte[] dataBytes = textConverter.GetBytes(data); byte[] signatureBytes = dsaCsp.SignData(dataBytes); bool valid = dsaCsp.VerifyData(dataBytes, signatureBytes); return(Esapi.Encoder().EncodeForBase64(signatureBytes, true)); } catch (Exception e) { throw new EncryptionException("Signature failure" + e.StackTrace, "Can't find signature algorithm " + signatureAlgorithm, e); } }
/// <summary> /// 验证签名 /// </summary> /// <param name="content">原字符串</param> /// <param name="privateKey">公钥</param> /// <param name="signature">签名</param> /// <returns></returns> public static bool VerifySignature(string content, string privateKey, string signature) { DSACryptoServiceProvider objdsa = new DSACryptoServiceProvider(); byte[] fileHashValue = new SHA1CryptoServiceProvider().ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(content)); string[] strSplit = signature.Split('-'); byte[] SignedHash = new byte[strSplit.Length]; for (int i = 0; i < strSplit.Length; i++) { SignedHash[i] = byte.Parse(strSplit[i], System.Globalization.NumberStyles.AllowHexSpecifier); } objdsa.FromXmlString(privateKey); return(objdsa.VerifySignature(fileHashValue, SignedHash)); }
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; } }
public virtual byte[] Sign(byte[] message) { if (mSigner != null) { return(mSigner.sign(message)); } if (certificate.PrivateKey is RSACryptoServiceProvider) { RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey; return(rsa.SignData(message, hashAlgorithm)); } else { DSACryptoServiceProvider dsa = (DSACryptoServiceProvider)certificate.PrivateKey; return(dsa.SignData(message)); } }
public static XmlLicense CheckLicense(string licenseFileName, string publicKeyFileName) { try { StreamReader sr = new StreamReader(publicKeyFileName); DSACryptoServiceProvider dsa = LoadKey(sr.ReadToEnd()); sr.Close(); XmlDocument xml = new XmlDocument(); // Format the document to ignore white spaces. xml.PreserveWhitespace = false; xml.Load(licenseFileName); // Create a new SignedXml object and pass it // the XML document class. SignedXml signedXml = new SignedXml(xml); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xml.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); if (!signedXml.CheckSignature(dsa)) { throw new Exception("The XML signature of the license is not valid."); } xml.DocumentElement.RemoveChild(nodeList[0]); XmlSerializer serializer = new XmlSerializer(typeof(XmlLicense)); XmlLicense l = (XmlLicense)serializer.Deserialize(new XmlNodeReader(xml)); if (l.Expired < DateTime.Now) { throw new Exception("The license is expired."); } return(l); } catch (Exception e) { throw new BadLicense(e.Message); } }
protected override ISignValue SignInternal(ArraySegment <byte> buffer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!Key.IncludePrivateKey()) { throw new ArgumentException("The PrivateKey does not exist and cannot be signed."); } using var provider = new DSACryptoServiceProvider(); provider.FromXmlString(Key.PrivateKey); var signature = provider.SignData(GetBytes(buffer)); return(CreateSignValue(signature)); }
//--METHOD UNTUK CREATE SIGNATURE static byte[] CreateSignature(byte[] dataSign, string privateKey) { byte[] result = null; //--CREATE OBJEK DSACryptoServiceProvider using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider()) { //--SET PRIVATE KEY dsa.FromXmlString(privateKey); //--CREATE FORMATTER UNTUK MENTRANSFER KEY DSASignatureFormatter formatter = new DSASignatureFormatter(dsa); //--SETTING ALGORITHM YANG DIPAKAI DENGAN SHA1 formatter.SetHashAlgorithm("SHA1"); //--CREATE SIGNATURE result = formatter.CreateSignature(dataSign); } return(result); }
public static void VerifyHash_CaseInsensitive_Success() { byte[] hashVal; using (SHA1 sha1 = SHA1.Create()) { hashVal = sha1.ComputeHash(DSATestData.HelloBytes); } using (var dsa = new DSACryptoServiceProvider()) { byte[] signVal = dsa.SignData(DSATestData.HelloBytes, new HashAlgorithmName("SHA1")); Assert.True(dsa.VerifyHash(hashVal, "SHA1", signVal)); signVal = dsa.SignData(DSATestData.HelloBytes, new HashAlgorithmName("SHA1")); // lowercase would fail here Assert.True(dsa.VerifyHash(hashVal, "sha1", signVal)); } }
static AsymmetricAlgorithm GetAsymmetricAlgorithm(DsaPrivateKeyParameters key, DsaPublicKeyParameters pub) { var parameters = GetDSAParameters(key); parameters.X = GetPaddedByteArray(key.X, parameters.Q.Length); if (pub != null) { parameters.Y = GetPaddedByteArray(pub.Y, parameters.P.Length); } var dsa = new DSACryptoServiceProvider(); dsa.ImportParameters(parameters); return(dsa); }
public virtual byte[] Sign(byte[] message) { if (certificate.PrivateKey is RSACryptoServiceProvider) { // Force rsa all PrivateKey properties //Including Private Parameters //Instead of cast that does not always work RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(certificate.PrivateKey.ToXmlString(true)); return(rsa.SignData(message, hashAlgorithm)); } else { DSACryptoServiceProvider dsa = (DSACryptoServiceProvider)certificate.PrivateKey; return(dsa.SignData(message)); } }
[PlatformSpecific(TestPlatforms.Windows)] // No support for CspParameters on Unix public static void NonExportable_Ephemeral() { CspParameters cspParameters = new CspParameters { ProviderType = PROV_DSS_DH, Flags = CspProviderFlags.UseNonExportableKey, }; using (var dsa = new DSACryptoServiceProvider(cspParameters)) { // Ephemeral keys don't successfully request the exportable bit. Assert.ThrowsAny <CryptographicException>(() => dsa.CspKeyContainerInfo.Exportable); Assert.Throws <CryptographicException>(() => dsa.ExportCspBlob(true)); Assert.Throws <CryptographicException>(() => dsa.ExportParameters(true)); } }
public static bool ValidateDSASignature(APIBaseRequest value, byte[] signature, byte[] publicKey) { DSAParameters algParams; using (MemoryStream mstr = new MemoryStream(publicKey)) { BinaryFormatter fmt = new BinaryFormatter(); try { algParams = (DSAParameters)fmt.Deserialize(mstr); } catch (SerializationException) { return(false); } } using (var provider = new DSACryptoServiceProvider()) { try { provider.ImportParameters(algParams); } catch (CryptographicException) { return(false); } return(provider.VerifyData(SerializingHelper.GetRequestBytes(value), signature)); } }
/// <summary> Verifies a digital signature (created with the sign method) and returns /// the boolean result. /// </summary> /// <param name="signature">The signature to verify. /// </param> /// <param name="data">The data to verify the signature against. /// </param> /// <returns> true, if successful /// </returns> /// <seealso cref="Owasp.Esapi.Interfaces.IEncryptor.VerifySignature(string, string)"> /// </seealso> public bool VerifySignature(string signature, string data) { try { DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(asymmetricKeyPair); Encoding textConverter = Encoding.GetEncoding(encoding); byte[] signatureBytes = Esapi.Encoder().DecodeFromBase64(signature); byte[] dataBytes = textConverter.GetBytes(data); return(dsaCsp.VerifyData(dataBytes, signatureBytes)); } catch (System.Exception e) { new EncryptionException("Invalid signature", "Problem verifying signature: " + e.Message, e); return(false); } }
/// <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 bool VerifySignature(Stream stream, string signature) { try { using (var dsaCryptoProvider = new DSACryptoServiceProvider()) { byte[] hash = (new SHA1Managed()).ComputeHash(stream);//for file or text dsaCryptoProvider.ImportParameters(PublicKey); var dsaDeformatter = new DSASignatureDeformatter(dsaCryptoProvider); dsaDeformatter.SetHashAlgorithm("SHA1"); return(dsaDeformatter.VerifySignature(hash, StringToByteArray(signature))); } } catch (CryptographicException e) { return(false); } }
/// <summary> /// 校验签名是否正确 /// </summary> /// <param name="decryptString"></param> /// <param name="key"></param> /// <returns></returns> public static bool VerifySignature(string decryptString, string key = strKeys) { bool ret = false; byte[] hashValue = { 22, 45, 78, 53, 1, 2, 205, 98, 75, 123, 45, 76, 143, 189, 205, 65, 12, 193, 211, 255 }; DSACryptoServiceProvider signer = new DSACryptoServiceProvider(); DSASignatureFormatter formatter = new DSASignatureFormatter(signer); formatter.SetHashAlgorithm("SHA1"); byte[] signedHashValue = formatter.CreateSignature(hashValue); DSASignatureDeformatter deformatter = new DSASignatureDeformatter(signer); deformatter.SetHashAlgorithm("SHA1"); ret = deformatter.VerifySignature(hashValue, signedHashValue); signer.Clear(); return(ret); }
public static bool verifySignature(byte[] hashValue, byte[] signature) { if (JAM_dotnet_verification_use_machine_keys() == 0) { DSACryptoServiceProvider.UseMachineKeyStore = true; } else { DSACryptoServiceProvider.UseMachineKeyStore = false; } DSACryptoServiceProvider key = new DSACryptoServiceProvider(); key.ImportParameters(dsaParms); DSASignatureDeformatter deformatter = new DSASignatureDeformatter(key); deformatter.SetHashAlgorithm("SHA1"); return(deformatter.VerifySignature(hashValue, signature)); }
//#region 文件处理 ///// <summary> ///// 加密文件 ///// </summary> ///// <param name="inName">来源文件</param> ///// <param name="outName">输出文件</param> ///// <param name="xmlString">密钥(至少含公钥)</param> //public static void EncryptFile(string inName, string outName, string xmlString) //{ // DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); // dsa.FromXmlString(xmlString); // FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); // using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write)) // { // fout.SetLength(0); // long rdlen = 0; //This is the total number of bytes written. // int len; //This is the number of bytes to be written at a time. // byte[] bin = new byte[FileReadStep]; // while (rdlen < fin.Length) // { // len = fin.Read(bin, 0, FileReadStep); // byte[] bs = dsa.Encrypt(bin, false); // fout.Write(bs, 0, bs.Length); // rdlen += len; // } // fin.Close(); // } //} ///// <summary> ///// 解密文件 ///// </summary> ///// <param name="inName">来源文件</param> ///// <param name="outName">输出文件</param> ///// <param name="xmlString">密钥(公钥私钥俱有)</param> //public static void DecryptFile(string inName, string outName, string xmlString) //{ // DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); // dsa.FromXmlString(xmlString); // FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); // using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write)) // { // fout.SetLength(0); // long rdlen = 0; //This is the total number of bytes written. // int len; //This is the number of bytes to be written at a time. // byte[] bin = new byte[FileReadStep]; // while (rdlen < fin.Length) // { // len = fin.Read(bin, 0, FileReadStep); // byte[] bs = dsa.Decrypt(bin, false); // fout.Write(bs, 0, bs.Length); // rdlen += len; // } // fin.Close(); // } //} //#endregion #region 字符串处理 /// <summary> /// DSA签名 /// </summary> /// <param name="PlainText">原始字符串</param> /// <param name="xmlString">密钥(公钥私钥俱有)</param> /// <returns>Base64编码后的已签名字符串</returns> public static string SignString(string PlainText, string xmlString) { DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.FromXmlString(xmlString); if (!string.IsNullOrEmpty(PlainText)) { byte[] bText = System.Text.Encoding.UTF8.GetBytes(PlainText.ToCharArray()); DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(dsa); DSAFormatter.SetHashAlgorithm("SHA1"); byte[] bEnc = DSAFormatter.CreateSignature(bText); return(System.Convert.ToBase64String(bEnc)); } return(string.Empty); }
/// <summary> /// Sign buffer /// </summary> private static bool CSPSignBuffer() { byte[] data = new byte[1025]; for (int i = 2; i < data.Length; i++) { data[i] = (byte)((data[i - 1] + data[i - 2]) % Byte.MaxValue); } using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider()) { byte[] sig = dsa.SignData(data, 25, 150); byte[] bufferPortion = new byte[150]; Array.Copy(data, 25, bufferPortion, 0, 150); return(dsa.VerifyData(bufferPortion, sig)); } }
/// <summary> /// Verify a file using a signature file and a public key. /// </summary> /// <param name="filePath">The file whose contents will be hashed.</param> /// <param name="signatureFilePath">The path of the signature file.</param> /// <param name="publicBlob">The public key.</param> /// <returns> True if the file is verified, otherwise false.</returns> public static bool VerifyFile(string filePath, string signatureFilePath, byte[] publicBlob) { if (publicBlob.Length == 0) { return(false); } bool verified = false; byte[] hash = null; try { // Compute a hash of the installer using (Stream fileStream = File.Open(filePath, FileMode.Open)) { SHA1 sha1 = new SHA1CryptoServiceProvider(); hash = sha1.ComputeHash(fileStream); } // Import the public key var dsa = new DSACryptoServiceProvider(); dsa.ImportCspBlob(publicBlob); var dsaDeformatter = new DSASignatureDeformatter(dsa); dsaDeformatter.SetHashAlgorithm("SHA1"); // Read the signature file byte[] signature = File.ReadAllBytes(signatureFilePath); // Verify the signature against the hash of the installer verified = dsaDeformatter.VerifySignature(hash, signature); Console.WriteLine("File verified: {0}", verified); } catch (Exception e) { Debug.WriteLine(e); return(false); } return(verified); }
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(); }
private void LoadKey() { try { StreamReader sr = new StreamReader(keyFileNameBox.Text); string k = sr.ReadToEnd(); sr.Close(); dsa = Manager.LoadKey(k); try { dsa.ExportParameters(true); isPrivateKeyOk = true; } catch { tabControl.SelectedTab = keyTabPage; isPrivateKeyOk = false; } keyInfoBox.Text = "Private key: " + (isPrivateKeyOk ? "Present" : "Absent") + "\r\n" + "Key size: " + dsa.KeySize + "\r\n" + "Signature algorithm: " + dsa.SignatureAlgorithm + "\r\n"; issueTabPage.Enabled = true; checkTabPage.Enabled = true; exportButton.Enabled = true; isPublicKeyOk = true; return; } catch (Exception e) { keyInfoBox.Text = "ERROR: " + e.Message; } issueTabPage.Enabled = false; checkTabPage.Enabled = false; exportButton.Enabled = false; isPublicKeyOk = false; isPrivateKeyOk = false; tabControl.SelectedTab = keyTabPage; }
public static void AssociatePersistedKey_CAPI_DSA(int provType) { const string KeyName = nameof(AssociatePersistedKey_CAPI_DSA); CspParameters cspParameters = new CspParameters(provType) { KeyContainerName = KeyName, Flags = CspProviderFlags.UseNonExportableKey, }; using (DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(cspParameters)) { dsaCsp.PersistKeyInCsp = false; X509SignatureGenerator dsaGen = new DSAX509SignatureGenerator(dsaCsp); // Use SHA-1 because that's all DSACryptoServiceProvider understands. HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={KeyName}-{provType}"), dsaGen.PublicKey, hashAlgorithm); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, dsaGen, now, now.AddDays(1), new byte[1])) using (X509Certificate2 certWithPrivateKey = cert.CopyWithPrivateKey(dsaCsp)) using (DSA dsa = certWithPrivateKey.GetDSAPrivateKey()) { byte[] signature = dsa.SignData(Array.Empty <byte>(), hashAlgorithm); Assert.True(dsaCsp.VerifyData(Array.Empty <byte>(), signature, hashAlgorithm)); } // Some certs have disposed, did they delete the key? cspParameters.Flags = CspProviderFlags.UseExistingKey; using (var stillPersistedKey = new DSACryptoServiceProvider(cspParameters)) { stillPersistedKey.SignData(Array.Empty <byte>(), hashAlgorithm); } } }
public static void Main() { try { DSAParameters privateKeyInfo; DSAParameters publicKeyInfo; // Create a new instance of DSACryptoServiceProvider to generate // a new key pair. using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider()) { privateKeyInfo = DSA.ExportParameters(true); publicKeyInfo = DSA.ExportParameters(false); } // The hash value to sign. byte[] HashValue = { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 }; // The value to hold the signed value. byte[] SignedHashValue = DSASignHash(HashValue, privateKeyInfo, "SHA1"); // Verify the hash and display the results. bool verified = DSAVerifyHash(HashValue, SignedHashValue, publicKeyInfo, "SHA1"); if (verified) { Console.WriteLine("The hash value was verified."); } else { Console.WriteLine("The hash value was not verified."); } } catch (ArgumentNullException e) { Console.WriteLine(e.Message); } }
[PlatformSpecific(TestPlatforms.Windows)] // No support for CspParameters on Unix public static void NamedKey_DefaultProvider() { const int KeySize = 1024; CspParameters cspParameters = new CspParameters { ProviderType = PROV_DSS_DH, KeyContainerName = Guid.NewGuid().ToString(), }; using (new DsaKeyLifetime(cspParameters)) { byte[] privateBlob; string uniqueKeyContainerName; using (var dsa = new DSACryptoServiceProvider(KeySize, cspParameters)) { Assert.True(dsa.PersistKeyInCsp, "dsa.PersistKeyInCsp"); Assert.Equal(cspParameters.KeyContainerName, dsa.CspKeyContainerInfo.KeyContainerName); uniqueKeyContainerName = dsa.CspKeyContainerInfo.UniqueKeyContainerName; Assert.NotNull(uniqueKeyContainerName); Assert.NotEqual(string.Empty, uniqueKeyContainerName); privateBlob = dsa.ExportCspBlob(true); Assert.True(dsa.CspKeyContainerInfo.Exportable, "dsa.CspKeyContainerInfo.Exportable"); } // Fail if the key didn't persist cspParameters.Flags |= CspProviderFlags.UseExistingKey; using (var dsa = new DSACryptoServiceProvider(cspParameters)) { Assert.True(dsa.PersistKeyInCsp); Assert.Equal(KeySize, dsa.KeySize); Assert.Equal(uniqueKeyContainerName, dsa.CspKeyContainerInfo.UniqueKeyContainerName); byte[] blob2 = dsa.ExportCspBlob(true); Assert.Equal(privateBlob, blob2); } } }
/// <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; }
/// <summary> /// Constructor /// </summary> /// <param name="publicKey">the public key</param> public SignatureVerifier(string publicKey) { // 1. try to load this from resource var data = TryGetResourceStream(publicKey) ?? TryGetFileResource(publicKey); // 2. check the resource if (data == null) { throw new Exception("Couldn't find public key for verification"); } // 3. read out the key value using (var reader = new StreamReader(data)) { var key = reader.ReadToEnd(); _provider = new DSACryptoServiceProvider(); _provider.FromXmlString(key); } }
public static LicenceTerms GetValidTerms(Licence lic, string privatekey) { DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.FromXmlString(privatekey); byte[] terms = Convert.FromBase64String(lic.LicenceTerms); byte[] signature = Convert.FromBase64String(lic.LicenceSignature); if (dsa.VerifyData(terms, signature)) { string s = ASCIIEncoding.ASCII.GetString(terms); return(Newtonsoft.Json.JsonConvert.DeserializeObject <LicenceTerms>(s)); } else { throw new Exception("Licence Signature Invalid!"); } }
public static void DefaultKey_NotPersisted() { using (var dsa = new DSACryptoServiceProvider()) { Assert.False(dsa.PersistKeyInCsp); } }
public static void NamedKey_DefaultProvider() { const int KeySize = 1024; CspParameters cspParameters = new CspParameters { ProviderType = PROV_DSS_DH, KeyContainerName = Guid.NewGuid().ToString(), }; using (new DsaKeyLifetime(cspParameters)) { byte[] privateBlob; string uniqueKeyContainerName; using (var dsa = new DSACryptoServiceProvider(KeySize, cspParameters)) { Assert.True(dsa.PersistKeyInCsp, "dsa.PersistKeyInCsp"); Assert.Equal(cspParameters.KeyContainerName, dsa.CspKeyContainerInfo.KeyContainerName); uniqueKeyContainerName = dsa.CspKeyContainerInfo.UniqueKeyContainerName; Assert.NotNull(uniqueKeyContainerName); Assert.NotEqual(string.Empty, uniqueKeyContainerName); privateBlob = dsa.ExportCspBlob(true); Assert.True(dsa.CspKeyContainerInfo.Exportable, "dsa.CspKeyContainerInfo.Exportable"); } // Fail if the key didn't persist cspParameters.Flags |= CspProviderFlags.UseExistingKey; using (var dsa = new DSACryptoServiceProvider(cspParameters)) { Assert.True(dsa.PersistKeyInCsp); Assert.Equal(KeySize, dsa.KeySize); Assert.Equal(uniqueKeyContainerName, dsa.CspKeyContainerInfo.UniqueKeyContainerName); byte[] blob2 = dsa.ExportCspBlob(true); Assert.Equal(privateBlob, blob2); } } }
public static void NonExportable_Ephemeral() { CspParameters cspParameters = new CspParameters { ProviderType = PROV_DSS_DH, Flags = CspProviderFlags.UseNonExportableKey, }; using (var dsa = new DSACryptoServiceProvider(cspParameters)) { // Ephemeral keys don't successfully request the exportable bit. Assert.ThrowsAny<CryptographicException>(() => dsa.CspKeyContainerInfo.Exportable); Assert.Throws<CryptographicException>(() => dsa.ExportCspBlob(true)); Assert.Throws<CryptographicException>(() => dsa.ExportParameters(true)); } }
public static void NonExportable_Persisted() { CspParameters cspParameters = new CspParameters { ProviderType = PROV_DSS_DH, KeyContainerName = Guid.NewGuid().ToString(), Flags = CspProviderFlags.UseNonExportableKey, }; using (new DsaKeyLifetime(cspParameters)) { using (var dsa = new DSACryptoServiceProvider(cspParameters)) { Assert.False(dsa.CspKeyContainerInfo.Exportable, "dsa.CspKeyContainerInfo.Exportable"); Assert.Throws<CryptographicException>(() => dsa.ExportCspBlob(true)); Assert.Throws<CryptographicException>(() => dsa.ExportParameters(true)); } } }
public void Dispose() { try { using (var dsa = new DSACryptoServiceProvider(_cspParameters)) { // Delete the key at the end of this using dsa.PersistKeyInCsp = false; } } catch (CryptographicException) { } }
public static void DefaultKey_Parameters() { using (var dsa = new DSACryptoServiceProvider()) { CspKeyContainerInfo keyContainerInfo = dsa.CspKeyContainerInfo; Assert.NotNull(keyContainerInfo); Assert.Equal(PROV_DSS_DH, keyContainerInfo.ProviderType); // This shouldn't be localized, so it should be safe to test on all cultures Assert.Equal("Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider", keyContainerInfo.ProviderName); Assert.Null(keyContainerInfo.KeyContainerName); Assert.Equal(string.Empty, keyContainerInfo.UniqueKeyContainerName); Assert.False(keyContainerInfo.HardwareDevice, "HardwareDevice"); Assert.False(keyContainerInfo.MachineKeyStore, "MachineKeyStore"); Assert.False(keyContainerInfo.Protected, "Protected"); Assert.False(keyContainerInfo.Removable, "Removable"); // Ephemeral keys don't successfully request the exportable bit. Assert.ThrowsAny<CryptographicException>(() => keyContainerInfo.Exportable); Assert.True(keyContainerInfo.RandomlyGenerated, "RandomlyGenerated"); Assert.Equal(KeyNumber.Signature, keyContainerInfo.KeyNumber); } }